text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change it to upload to pypi
#!/usr/bin/env python try: from setuptools import setup, find_packages from setuptools.command.test import test except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test import os here = os.path.dirname(os.path.abspath(__file__)) f = open(os.path.join(here, 'README.rst')) long_description = f.read().strip() f.close() setup( name='django-common-tivix', version='0.1.2', author='Matthew Farver', author_email='mfarver@tivix.com', url='http://github.com/tivix/django-common', description = 'Common things every Django app needs!', packages=find_packages(), long_description=long_description, keywords = 'django', zip_safe=False, install_requires=[ 'Django>=1.2.3', 'South>=0.7.2' ], # test_suite = 'django_common.tests', include_package_data=True, # cmdclass={}, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
#!/usr/bin/env python try: from setuptools import setup, find_packages from setuptools.command.test import test except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test import os here = os.path.dirname(os.path.abspath(__file__)) f = open(os.path.join(here, 'README.rst')) long_description = f.read().strip() f.close() setup( name='django-common-helpers', version='0.1', author='Sumit Chachra', author_email='chachra@tivix.com', url='http://github.com/tivix/django-common', description = 'Common things every Django app needs!', packages=find_packages(), long_description=long_description, keywords = 'django', zip_safe=False, install_requires=[ 'Django>=1.2.3', 'South>=0.7.2' ], # test_suite = 'django_common.tests', include_package_data=True, # cmdclass={}, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
Exclude velocity auto config. Problematic in multi webapp deployments. Further review necessary to determine why the class linkage problem exists. Since WebAPI is headless, seemed appropriate to exclude.
package org.ohdsi.webapi; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; /** * Launch as java application or deploy as WAR (@link {@link WebApplication} will source this file). */ @SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class,VelocityAutoConfiguration.class}) public class WebApi extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) { return application.sources(WebApi.class); } public static void main(final String[] args) throws Exception { new SpringApplicationBuilder(WebApi.class).run(args); } }
package org.ohdsi.webapi; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; /** * Launch as java application or deploy as WAR (@link {@link WebApplication} will source this file). */ @SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class) public class WebApi extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) { return application.sources(WebApi.class); } public static void main(final String[] args) throws Exception { new SpringApplicationBuilder(WebApi.class).run(args); } }
Add query param with id to send message
'use strict'; /* This declares the function that will send a message */ function sendMessage(e) { e.preventDefault(); const inputNode = e.target.message; const message = inputNode.value + '\n'; console.log("Sending message:", message); // Clear node inputNode.value = ''; // Send the message const xhr = new XMLHttpRequest(); xhr.onload = (e) => { if (xhr.status !== 200) { return window.alert("Error sending message to server"); } } xhr.addEventListener("error", (e) => { console.log(e); }); xhr.open("POST", config.hostUrl + '?id=' config.id.toString()); xhr.setRequestHeader("Content-type", "text/plain"); xhr.send(message); } function initializeForm() { const form = document.getElementById('message-form'); form.addEventListener('submit', sendMessage); } initializeForm();
'use strict'; /* This declares the function that will send a message */ function sendMessage(e) { e.preventDefault(); const inputNode = e.target.message; const message = inputNode.value + '\n'; console.log("Sending message:", message); // Clear node inputNode.value = ''; // Send the message const xhr = new XMLHttpRequest(); xhr.onload = (e) => { if (xhr.status !== 200) { return window.alert("Error sending message to server"); } } xhr.addEventListener("error", (e) => { console.log(e); }); xhr.open("POST", config.hostUrl); xhr.setRequestHeader("Content-type", "text/plain"); xhr.send(message); } function initializeForm() { const form = document.getElementById('message-form'); form.addEventListener('submit', sendMessage); } initializeForm();
Change binary name, and encode whether it uses a JIT compiler or not Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from som.vm.universe import main, Exit from rpython.rlib import jit #from rpython.rlib.debug import debug_start, debug_stop, debug_print # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit, e: return e.code return 1 # _____ Define and setup target ___ def target(driver, args): if driver.config.translation.jit: driver.exe_name = 'RPySOM-jit' else: driver.exe_name = 'RPySOM-no-jit' return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv))
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from som.vm.universe import main, Exit from rpython.rlib import jit #from rpython.rlib.debug import debug_start, debug_stop, debug_print # __________ Entry points __________ def entry_point(argv): try: main(argv) except Exit, e: return e.code return 1 # _____ Define and setup target ___ def target(driver, args): driver.exe_name = 'som' return entry_point, None def jitpolicy(driver): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': from rpython.translator.driver import TranslationDriver f, _ = target(TranslationDriver(), sys.argv) sys.exit(f(sys.argv))
Add className to Title component
import cn from 'classnames' import React from 'react' import styles from './Text.css' export function Caption ({ children }) { return ( <div className={styles.caption}> {children} </div> ) } export function Headline ({ children }) { return ( <h3 className={styles.headline}> {children} </h3> ) } export function Hint ({ children, className }) { return ( <div className={cn(styles.hint, className)}> {children} </div> ) } export function PrimaryText ({ children, className }) { return ( <div className={cn(styles.primary, className)}> {children} </div> ) } export function SecondaryText ({ children, className }) { return ( <div className={cn(styles.secondary, className)}> {children} </div> ) } export function Title ({ children, className }) { return ( <div className={cn(styles.title, className)}> {children} </div> ) }
import cn from 'classnames' import React from 'react' import styles from './Text.css' export function Caption ({ children }) { return ( <div className={styles.caption}> {children} </div> ) } export function Headline ({ children }) { return ( <h3 className={styles.headline}> {children} </h3> ) } export function Hint ({ children, className }) { return ( <div className={cn(styles.hint, className)}> {children} </div> ) } export function PrimaryText ({ children, className }) { return ( <div className={cn(styles.primary, className)}> {children} </div> ) } export function SecondaryText ({ children, className }) { return ( <div className={cn(styles.secondary, className)}> {children} </div> ) } export function Title ({ children }) { return ( <div className={styles.title}> {children} </div> ) }
Revert "clean up module implementation by removing conditional exports" This reverts commit de34cc3e55cb4580220a26e0157a61db9ae4f8c4. The commit negated the intention of commit 642323e - "Return early if no `window` object (eg. Node.js)".
'use strict'; var isWindow = require('./isWindow'); if (typeof window === 'undefined') { module.exports.window = undefined; module.exports.realWindow = undefined; } else { // get wrapped window if using Shadow DOM polyfill module.exports.realWindow = window; // create a TextNode var el = window.document.createTextNode(''); // check if it's wrapped by a polyfill if (el.ownerDocument !== window.document && typeof window.wrap === 'function' && window.wrap(el) === el) { // return wrapped window module.exports.window = window.wrap(window); } // no Shadow DOM polyfil or native implementation module.exports.window = window; } module.exports.getWindow = function getWindow (node) { if (isWindow(node)) { return node; } var rootNode = (node.ownerDocument || node); return rootNode.defaultView || rootNode.parentWindow || module.exports.window; };
'use strict'; var isWindow = require('./isWindow'); var isShadowDom = function() { // create a TextNode var el = window.document.createTextNode(''); // check if it's wrapped by a polyfill return el.ownerDocument !== window.document && typeof window.wrap === 'function' && window.wrap(el) === el; }; var win = { window: undefined, realWindow: window, getWindow: function getWindow (node) { if (isWindow(node)) { return node; } var rootNode = (node.ownerDocument || node); return rootNode.defaultView || rootNode.parentWindow || win.window; } }; if (typeof window !== 'undefined') { if (isShadowDom()) { win.window = window.wrap(window); } else { win.window = window; } } module.exports = win;
Add more time to mqtt.test.client
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True)
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(TestMQTT, MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True)
Reset the Gruntfile after a test failure.
var checkForDevFile = function (callback) { var cwd = process.cwd(); var fs = require("fs"); var path = require("path"); var testFile = path.join(cwd, "lib", "modernizr-dev.js"); var remoteTestFile = "http://modernizr.com/downloads/modernizr-latest.js"; var http = require("http"); var file = fs.createWriteStream(testFile); var request = http.get(remoteTestFile, function (response) { response.pipe(file); response.on("end", function () { callback(); }); }); }; checkForDevFile(function () { var Mocha = require("mocha"); var mocha = new Mocha({ setup : "bdd", reporter : process.env.TRAVIS ? "tap" : "spec", slow : 5000, timeout : 30000 }); mocha.addFile("test/tests.js"); var runner = mocha.run(); runner.on("fail", function (test, err) { var cp = require("child_process"); var cwd = process.cwd(); var path = require("path"); var child = cp.spawn("git", [ "checkout", "--", path.join(cwd, "Gruntfile.js") ], { stdio: "inherit" }); child.on("exit", function () { process.exit(1); }); process.stderr.write(" " + err.toString() + "\n\n"); }); });
var checkForDevFile = function (callback) { var cwd = process.cwd(); var fs = require("fs"); var path = require("path"); var testFile = path.join(cwd, "lib", "modernizr-dev.js"); var remoteTestFile = "http://modernizr.com/downloads/modernizr-latest.js"; var http = require("http"); var file = fs.createWriteStream(testFile); var request = http.get(remoteTestFile, function (response) { response.pipe(file); response.on("end", function () { callback(); }); }); }; checkForDevFile(function () { var Mocha = require("mocha"); var mocha = new Mocha({ setup : "bdd", reporter : process.env.TRAVIS ? "tap" : "spec", slow : 5000, timeout : 30000 }); mocha.addFile("test/tests.js"); var runner = mocha.run(); runner.on("fail", function (test, err) { process.stderr.write(" " + err.toString() + "\n\n"); process.exit(1); }); });
[V0.4][Logic] Refactor - remove magic string
package seedu.address.logic.parser; import static seedu.address.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT_LIST; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.ListCommand; /** * Parses input arguments and creates a new ListCommand object */ public class ListCommandParser { private ListCommandParser() { } private static final String LIST_SEPARATOR = "\\s+"; /** * Parses the given {@code String} of arguments in the context of the FindCommand * and returns an FindCommand object for execution. */ public static Command parse(String args) { if (args == null) { return new ListCommand(); } // if not match, show all the unfinished task final Matcher matcher = KEYWORDS_ARGS_FORMAT_LIST.matcher(args.trim()); if (!matcher.matches()) { return new ListCommand(); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split(LIST_SEPARATOR); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new ListCommand(keywordSet); } }
package seedu.address.logic.parser; import static seedu.address.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT_LIST; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.ListCommand; /** * Parses input arguments and creates a new ListCommand object */ public class ListCommandParser { private ListCommandParser() { } /** * Parses the given {@code String} of arguments in the context of the FindCommand * and returns an FindCommand object for execution. */ public static Command parse(String args) { if (args == null) { return new ListCommand(); } // if not match, show all the unfinished task final Matcher matcher = KEYWORDS_ARGS_FORMAT_LIST.matcher(args.trim()); if (!matcher.matches()) { return new ListCommand(); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new ListCommand(keywordSet); } }
Make the cursor as pointer for quick notifications
<?php /** * Template file for notifications * * @package Dragooon:WeNotif * @author Shitiz "Dragooon" Garg <Email mail@dragooon.net> <Url http://smf-media.com> * @copyright 2012, Shitiz "Dragooon" Garg <mail@dragooon.net> * @license * Licensed under "New BSD License (3-clause version)" * http://www.opensource.org/licenses/BSD-3-Clause * @version 1.0 */ function template_notifications_block() { global $txt, $context, $settings, $scripturl; echo ' <section> <span class="note', $context['unread_notifications'] ? 'nice' : '', '" style="font-size: 9pt;">', $context['unread_notifications'], '</span>&nbsp; <a href="', $scripturl, '?action=notification" class="title">', $txt['notification_unread_title'], '</a>'; foreach ($context['quick_notifications'] as $notification) { echo ' <p class="description" style="font-size: 1em; cursor: pointer;" onclick="document.location = \'', $scripturl, '?action=notification;area=redirect;id=', $notification->getID(), '\'"> ', $notification->getText(), '<br /> <span class="smalltext">', timeformat($notification->getTime()), '</span> </p>'; } echo ' </section>'; } ?>
<?php /** * Template file for notifications * * @package Dragooon:WeNotif * @author Shitiz "Dragooon" Garg <Email mail@dragooon.net> <Url http://smf-media.com> * @copyright 2012, Shitiz "Dragooon" Garg <mail@dragooon.net> * @license * Licensed under "New BSD License (3-clause version)" * http://www.opensource.org/licenses/BSD-3-Clause * @version 1.0 */ function template_notifications_block() { global $txt, $context, $settings, $scripturl; echo ' <section> <span class="note', $context['unread_notifications'] ? 'nice' : '', '" style="font-size: 9pt;">', $context['unread_notifications'], '</span>&nbsp; <a href="', $scripturl, '?action=notification" class="title">', $txt['notification_unread_title'], '</a>'; foreach ($context['quick_notifications'] as $notification) { echo ' <p class="description" style="font-size: 1em;" onclick="document.location = \'', $scripturl, '?action=notification;area=redirect;id=', $notification->getID(), '\'"> ', $notification->getText(), '<br /> <span class="smalltext">', timeformat($notification->getTime()), '</span> </p>'; } echo ' </section>'; } ?>
Add error checking to username and password (DEV-99)
package sg.ncl.service.authentication.controllers; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import sg.ncl.common.exceptions.BadRequestException; import sg.ncl.service.authentication.AuthenticationService; import javax.inject.Inject; /** * @author Christopher Zhong */ @RestController @RequestMapping(path = "/authentication", produces = MediaType.APPLICATION_JSON_VALUE) public class AuthenticationController { private final AuthenticationService authenticationService; @Inject protected AuthenticationController(final AuthenticationService authenticationService) { this.authenticationService = authenticationService; } @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public String login(@RequestHeader("X-Username") String username, @RequestHeader("X-Password") String password) { if (username.isEmpty() || password.isEmpty()) { throw new BadRequestException(); } return authenticationService.login(username, password); } @RequestMapping(method = RequestMethod.DELETE) public void logout() { authenticationService.logout(); } }
package sg.ncl.service.authentication.controllers; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import sg.ncl.service.authentication.AuthenticationService; import javax.inject.Inject; /** * @author Christopher Zhong */ @RestController @RequestMapping(path = "/authentication", produces = MediaType.APPLICATION_JSON_VALUE) public class AuthenticationController { private final AuthenticationService authenticationService; @Inject protected AuthenticationController(final AuthenticationService authenticationService) { this.authenticationService = authenticationService; } @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public String login(@RequestHeader("X-Username") String username, @RequestHeader("X-Password") String password) { return authenticationService.login(username, password); } @RequestMapping(method = RequestMethod.DELETE) public void logout() { authenticationService.logout(); } }
Correct author list, add OCA
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # 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/>. # ############################################################################## {'name': 'Sale Payment Method - Automatic Worflow (link module)', 'version': '1.0', 'author': 'Camptocamp,Akretion,Odoo Community Association (OCA)', 'license': 'AGPL-3', 'category': 'Generic Modules/Others', 'depends': ['sale_payment_method', 'sale_automatic_workflow'], 'website': 'http://www.camptocamp.com', 'data': ['view/sale_order_view.xml', 'view/payment_method_view.xml', ], 'test': [], 'installable': True, 'auto_install': True, }
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # 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/>. # ############################################################################## {'name': 'Sale Payment Method - Automatic Worflow (link module)', 'version': '1.0', 'author': ['Camptocamp', 'Akretion'], 'license': 'AGPL-3', 'category': 'Generic Modules/Others', 'depends': ['sale_payment_method', 'sale_automatic_workflow'], 'website': 'http://www.camptocamp.com', 'data': ['view/sale_order_view.xml', 'view/payment_method_view.xml', ], 'test': [], 'installable': True, 'auto_install': True, }
Change the order of the answer_id field
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDiscussionsTable extends Migration { public function up() { Schema::create('discussions', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('user_id')->unsigned(); $table->integer('topic_id')->unsigned(); $table->bigInteger('answer_id')->unsigned()->nullable(); $table->string('title'); $table->longText('body'); //$table->string('slug'); $table->timestamps(); $table->softDeletes(); }); } public function down() { Schema::dropIfExists('discussions'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDiscussionsTable extends Migration { public function up() { Schema::create('discussions', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('user_id')->unsigned(); $table->integer('topic_id')->unsigned(); $table->string('title'); $table->longText('body'); //$table->string('slug'); $table->bigInteger('answer_id')->unsigned()->nullable(); $table->timestamps(); $table->softDeletes(); }); } public function down() { Schema::dropIfExists('discussions'); } }
Store + Shipping + Menus * Using new Store feature from Elcodi * Added Store management in Admin * Changed all definitions that was depending on such implementation * Removed under construction logic and tests * Removed menu fixtures * Defined them as dynamic content. Some of them are generated dinamically, and some of them statically. * Added neede menu builders in every Admin bundle * Changed the way menu is loaded in Admin * Removed dependency with Configuration and Configuration annotation, in order to use new implementation. * Removed configuration elements * Removed all `elcodi_config` twig extension usage * Moved custom shipping logic from elcodi/elcodi to elcodi-plugins/* * Added full repo inside Plugin folder * Using new Shipping engine * Updated some code in order to be compatible with Sf2.7 deprecations Ready for Elcodi Beta! Auu! Auu!
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014-2015 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Plugin\GoogleAnalyticsBundle; use Symfony\Component\Console\Application; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\HttpKernel\Bundle\Bundle; use Elcodi\Component\Plugin\Interfaces\PluginInterface; use Elcodi\Plugin\GoogleAnalyticsBundle\DependencyInjection\ElcodiGoogleAnalyticsExtension; /** * Class ElcodiGoogleAnalyticsBundle */ class ElcodiGoogleAnalyticsBundle extends Bundle implements PluginInterface { /** * Returns the bundle's container extension. * * @return ExtensionInterface The container extension */ public function getContainerExtension() { return new ElcodiGoogleAnalyticsExtension(); } /** * Register Commands. * * Disabled as commands are registered as services. * * @param Application $application An Application instance * * @return null */ public function registerCommands(Application $application) { return null; } }
<?php /* * This file is part of the Elcodi package. * * Copyright (c) 2014-2015 Elcodi.com * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> * @author Aldo Chiecchia <zimage@tiscali.it> * @author Elcodi Team <tech@elcodi.com> */ namespace Elcodi\Plugin\GoogleAnalyticsBundle; use Symfony\Component\Console\Application; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\HttpKernel\Bundle\Bundle; use Elcodi\Component\Plugin\Interfaces\PluginInterface; use Elcodi\Plugin\GoogleAnalyticsBundle\DependencyInjection\ElcodiGoogleAnalyticsExtension; /** * Class ElcodiGoogleAnalyticsBundle */ class ElcodiGoogleAnalyticsBundle extends Bundle implements PluginInterface { /** * Returns the bundle's container extension. * * @return ExtensionInterface The container extension */ public function getContainerExtension() { return new ElcodiGoogleAnalyticsExtension(); } /** * Register Commands. * * Disabled as commands are registered as services. * * @param Application $application An Application instance */ public function registerCommands(Application $application) { return null; } }
Use codecs to handle README encoding
# -*- coding: UTF-8 -*- from distutils.core import setup from setuptools import find_packages import codecs #import time #_version = "3.0.dev%s" % int(time.time()) _version = "3.0.0" _packages = find_packages('.', exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) setup( name='laterpay-client', version=_version, description="LaterPay API client", long_description=codecs.open("README.rst", encoding='utf-8').read(), author="LaterPay GmbH", author_email="support@laterpay.net", url="https://github.com/laterpay/laterpay-client-python", license='MIT', keywords="LaterPay API client", test_suite="test_client", packages=_packages, package_data={'laterpay.django': ['templates/laterpay/inclusion/*']}, classifiers=( "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", ), )
# -*- coding: UTF-8 -*- from distutils.core import setup from setuptools import find_packages #import time #_version = "3.0.dev%s" % int(time.time()) _version = "3.0.0" _packages = find_packages('.', exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) setup( name='laterpay-client', version=_version, description="LaterPay API client", long_description=open("README.rst").read(), author="LaterPay GmbH", author_email="support@laterpay.net", url="https://github.com/laterpay/laterpay-client-python", license='MIT', keywords="LaterPay API client", test_suite="test_client", packages=_packages, package_data={'laterpay.django': ['templates/laterpay/inclusion/*']}, classifiers=( "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", ), )
Make the test failure message for timer restart more explicit
// (c) Copyright IBM Corp. 2021 // (c) Copyright Instana Inc. 2020 package internal_test import ( "sync/atomic" "testing" "time" "github.com/instana/go-sensor/autoprofile/internal" "github.com/instana/testify/assert" ) func TestTimer_Stop_Restart(t *testing.T) { var fired int64 timer := internal.NewTimer(0, 60*time.Millisecond, func() { atomic.AddInt64(&fired, 1) }) time.Sleep(100 * time.Millisecond) timer.Stop() assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) time.Sleep(200 * time.Millisecond) assert.EqualValues(t, 1, atomic.LoadInt64(&fired), "a stopped timer should not be restarted") } func TestTimer_Sleep_Stopped(t *testing.T) { timer := internal.NewTimer(20*time.Millisecond, 0, func() { t.Error("stopped timer has fired") }) timer.Stop() time.Sleep(30 * time.Millisecond) }
// (c) Copyright IBM Corp. 2021 // (c) Copyright Instana Inc. 2020 package internal_test import ( "sync/atomic" "testing" "time" "github.com/instana/go-sensor/autoprofile/internal" "github.com/instana/testify/assert" ) func TestTimer_Stop(t *testing.T) { var fired int64 timer := internal.NewTimer(0, 60*time.Millisecond, func() { atomic.AddInt64(&fired, 1) }) time.Sleep(100 * time.Millisecond) timer.Stop() assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) time.Sleep(200 * time.Millisecond) assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) } func TestTimer_Sleep_Stopped(t *testing.T) { timer := internal.NewTimer(20*time.Millisecond, 0, func() { t.Error("stopped timer has fired") }) timer.Stop() time.Sleep(30 * time.Millisecond) }
Fix crash on empty report by converting to string
import logging class Browser: def __init__(self, actors, subreddit, db, cursor): self.actors = actors self.subreddit = subreddit self.db = db self.cursor = cursor def check_command(self, command, mod, post): for actor in self.actors: actor.parse(command, mod, post) def scan_reports(self): try: for post in self.subreddit.mod.reports(limit=None): for mod_report in post.mod_reports: yield (str(mod_report[0]), mod_report[1], post) except Exception as e: logging.error("Error fetching reports: {err}".format(err=e)) def run(self): for command, mod, post in self.scan_reports(): self.check_command(command, mod, post) for actor in self.actors: actor.after()
import logging class Browser: def __init__(self, actors, subreddit, db, cursor): self.actors = actors self.subreddit = subreddit self.db = db self.cursor = cursor def check_command(self, command, mod, post): for actor in self.actors: actor.parse(command, mod, post) def scan_reports(self): try: for post in self.subreddit.mod.reports(limit=None): for mod_report in post.mod_reports: yield (mod_report[0], mod_report[1], post) except Exception as e: logging.error("Error fetching reports: {err}".format(err=e)) def run(self): for command, mod, post in self.scan_reports(): self.check_command(command, mod, post) for actor in self.actors: actor.after()
Fix image size adjustment on gallery images Gallery images are being adjusted wrongly, this patch adds .gallerybox to the Class Blacklist for the adjustThumbWidths transform. Bug: T228287 Change-Id: Ib69397229385357fe82a1f4d8dc2b3044d324bcb
'use strict'; const MATHOID_IMG_CLASS = 'mwe-math-fallback-image-inline'; const MediaSelectors = [ '*[typeof^=mw:Image]', '*[typeof^=mw:Video]', '*[typeof^=mw:Audio]', `img.${MATHOID_IMG_CLASS}` ]; // Exclusions for various categories of content. See MMVB.isAllowedThumb in mediawiki-extensions- // MultimediaViewer. const MediaBlacklist = [ '.metadata', '.noviewer', '.gallerybox', ]; const VideoSelectors = MediaSelectors.filter(selector => selector.includes('Video')); const PronunciationParentSelector = 'span.IPA'; const PronunciationSelector = 'a[rel=mw:MediaLink]'; const SpokenWikipediaId = '#section_SpokenWikipedia'; module.exports = { MediaSelectors, MediaBlacklist, VideoSelectors, PronunciationParentSelector, PronunciationSelector, SpokenWikipediaId, MATHOID_IMG_CLASS };
'use strict'; const MATHOID_IMG_CLASS = 'mwe-math-fallback-image-inline'; const MediaSelectors = [ '*[typeof^=mw:Image]', '*[typeof^=mw:Video]', '*[typeof^=mw:Audio]', `img.${MATHOID_IMG_CLASS}` ]; // Exclusions for various categories of content. See MMVB.isAllowedThumb in mediawiki-extensions- // MultimediaViewer. const MediaBlacklist = [ '.metadata', '.noviewer' ]; const VideoSelectors = MediaSelectors.filter(selector => selector.includes('Video')); const PronunciationParentSelector = 'span.IPA'; const PronunciationSelector = 'a[rel=mw:MediaLink]'; const SpokenWikipediaId = '#section_SpokenWikipedia'; module.exports = { MediaSelectors, MediaBlacklist, VideoSelectors, PronunciationParentSelector, PronunciationSelector, SpokenWikipediaId, MATHOID_IMG_CLASS };
Check the url of the remote & ensure the updating commands are executed in the correct directory
import os.path import subprocess class DefaultRepositoryHandler(): def __init__(self, cwd): self.cwd = cwd def repository_exists(self, path): return os.path.exists(path + os.path.sep + '.git') def update_repository(self, path, remote_url, remote_branch): print 'Updating repository %s ...' % path remote_name = 'origin' url = subprocess.check_output(['git', 'config', 'remote.%s.url' % remote_name], cwd=path) if url != remote_url: subprocess.check_call(['git', 'config', 'remote.%s.url' % remote_name, remote_url], cwd=path) subprocess.check_call(['git', 'pull', '--rebase'], cwd=path) def clone_repository(self, path, remote_url, remote_branch): print 'Cloning repository %s ...' % path subprocess.check_call(['git', 'clone', remote_url, '-b', remote_branch, path]) def update_or_clone(self, path, remote_url, remote_branch): if self.repository_exists(path): self.update_repository(path, remote_url, remote_branch) else: self.clone_repository(path, remote_url, remote_branch)
import os.path import subprocess class DefaultRepositoryHandler(): def __init__(self, cwd): self.cwd = cwd def repository_exists(self, path): return os.path.exists(path + os.path.sep + '.git') def update_repository(self, path, remote_url, remote_branch): print 'Updating repository %s ...' % path subprocess.check_call(['git', 'pull', '--rebase']) def clone_repository(self, path, remote_url, remote_branch): print 'Cloning repository %s ...' % path subprocess.check_call(['git', 'clone', remote_url, '-b', remote_branch, path]) def update_or_clone(self, path, remote_url, remote_branch): if self.repository_exists(path): self.update_repository(path, remote_url, remote_branch) else: self.clone_repository(path, remote_url, remote_branch)
Fix interaction with door by replicating the BlockReginoComponent.
/* * Copyright 2013 MovingBlocks * * 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.terasology.world.block.regions; import org.terasology.entitySystem.Component; import org.terasology.math.Region3i; import org.terasology.network.Replicate; /** * @author Immortius */ public class BlockRegionComponent implements Component { @Replicate public Region3i region = Region3i.EMPTY; public boolean overrideBlockEntities = true; public BlockRegionComponent() { } public BlockRegionComponent(Region3i region) { this.region = region; } }
/* * Copyright 2013 MovingBlocks * * 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.terasology.world.block.regions; import org.terasology.entitySystem.Component; import org.terasology.math.Region3i; /** * @author Immortius */ public class BlockRegionComponent implements Component { public Region3i region = Region3i.EMPTY; public boolean overrideBlockEntities = true; public BlockRegionComponent() { } public BlockRegionComponent(Region3i region) { this.region = region; } }
Add try block to allow fallback to runtime check for HAS_BLOCK symbol
import Ember from 'ember'; import emberVersionInfo from './ember-version-info'; const { major, minor, isGlimmer } = emberVersionInfo(); let hasBlockSymbol; try { if (major > 3 || (major == 3 && minor >= 1)) { // Ember-glimmer moved to TypeScript since v3.1 // Do nothing since the symbol is not exported } else if (isGlimmer) { hasBlockSymbol = Ember.__loader.require('ember-glimmer/component')[ 'HAS_BLOCK' ]; } else { hasBlockSymbol = Ember.__loader.require('ember-htmlbars/component')[ 'HAS_BLOCK' ]; } } catch (e) { // Fallback to use runtime check } // NOTE: I really don't know how to test this export default function hasBlock(emberComponent) { // Since Glimmer moved to TypeScript, we can't get the symbol. // This is a terrible but working way to get the value. if (!hasBlockSymbol) { const regex = /HAS_BLOCK/; hasBlockSymbol = Object.getOwnPropertyNames(emberComponent).find(key => regex.test(key) ); } return Ember.get(emberComponent, hasBlockSymbol); }
import Ember from 'ember'; import emberVersionInfo from './ember-version-info'; const { major, minor, isGlimmer } = emberVersionInfo(); let hasBlockSymbol; if (major > 3 || (major == 3 && minor >= 1)) { // Ember-glimmer moved to TypeScript since v3.1 // Do nothing since the symbol is not exported } else if (isGlimmer) { hasBlockSymbol = Ember.__loader.require('ember-glimmer/component')[ 'HAS_BLOCK' ]; } else { hasBlockSymbol = Ember.__loader.require('ember-htmlbars/component')[ 'HAS_BLOCK' ]; } // NOTE: I really don't know how to test this export default function hasBlock(emberComponent) { // Since Glimmer moved to TypeScript, we can't get the symbol. // This is a terrible but working way to get the value. if (!hasBlockSymbol) { const regex = /HAS_BLOCK/; hasBlockSymbol = Object.getOwnPropertyNames(emberComponent).find(key => regex.test(key) ); } return Ember.get(emberComponent, hasBlockSymbol); }
Make force publish better on IE7 Disable linked modals on IE7, as modals don’t work well.
(function(Modules) { "use strict"; /* If `data-toggle=modal` and `data-target` are used on a link element in Bootstrap 3, then Bootstrap attempts to load the contents of the link's href remotely, putting it into the modal container. There's no way of disabling this. (The feature is being removed in Bootstrap 4) We still want a link that works when js is broken or disabled. This is a workaround. Use `data-module=linked-modal` rather than `data-toggle=modal` */ Modules.LinkedModal = function() { this.start = function(element) { // Bootstrap 3 modals don't work well in IE7 // For IE7 just follow the link if (window.ieVersion !== 7) { element.on('click', openModal); } function openModal(evt) { var $target = $(element.data('target')); $target.modal('show'); evt.preventDefault(); } } }; })(window.GOVUKAdmin.Modules);
(function(Modules) { "use strict"; /* If `data-toggle=modal` and `data-target` are used on a link element in Bootstrap 3, then Bootstrap attempts to load the contents of the link's href remotely, putting it into the modal container. There's no way of disabling this. (The feature is being removed in Bootstrap 4) We still want a link that works when js is broken or disabled. This is a workaround. Use `data-module=linked-modal` rather than `data-toggle=modal` */ Modules.LinkedModal = function() { this.start = function(element) { element.on('click', openModal); function openModal(evt) { var $target = $(element.data('target')); $target.modal('show'); evt.preventDefault(); } } }; })(window.GOVUKAdmin.Modules);
Add new-style TEMPLATES setting for tests
import sys import django from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, MIDDLEWARE_CLASSES=(), TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': False, 'DIRS': ('tests/templates',), }, ] ) if django.VERSION >= (1, 7): django.setup() try: from django.test.runner import DiscoverRunner except ImportError: # Django < 1.6 from discover_runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
import sys import django from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, MIDDLEWARE_CLASSES=(), TEMPLATE_DIRS=('tests/templates',), ) if django.VERSION >= (1, 7): django.setup() try: from django.test.runner import DiscoverRunner except ImportError: # Django < 1.6 from discover_runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
Change version of API client
#!/usr/bin/env python # Copyright 2017 Google Inc. 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. """This is the setup file for the project.""" from setuptools import find_packages from setuptools import setup setup( name=u'timesketch-api-client', version=u'20170815', description=u'Timesketch API client', license=u'Apache License, Version 2.0', url=u'http://www.timesketch.org/', maintainer=u'Timesketch development team', maintainer_email=u'timesketch-dev@googlegroups.com', classifiers=[ u'Development Status :: 4 - Beta', u'Environment :: Console', u'Operating System :: OS Independent', u'Programming Language :: Python', ], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=frozenset([ u'requests', u'BeautifulSoup', ]) )
#!/usr/bin/env python # Copyright 2017 Google Inc. 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. """This is the setup file for the project.""" from setuptools import find_packages from setuptools import setup setup( name=u'timesketch-api-client', version=u'20170721', description=u'Timesketch', license=u'Apache License, Version 2.0', url=u'http://www.timesketch.org/', maintainer=u'Timesketch development team', maintainer_email=u'timesketch-dev@googlegroups.com', classifiers=[ u'Development Status :: 4 - Beta', u'Environment :: Console', u'Operating System :: OS Independent', u'Programming Language :: Python', ], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=frozenset([ u'requests', u'BeautifulSoup', ]) )
Add params to share url
import { connect } from 'react-redux'; import shareIcon from 'assets/icons/share.svg'; import facebookIcon from 'assets/icons/facebook.svg'; import twitterIcon from 'assets/icons/twitter.svg'; import mailIcon from 'assets/icons/mail.svg'; import linkIcon from 'assets/icons/link.svg'; import copy from 'copy-to-clipboard'; import Component from './share-menu-component'; const mapStateToProps = (state, { path }) => { const url = location.origin + (path || location.pathname) + location.search; const copyUrl = () => copy(url); const shareMenuOptions = [ { label: 'Email', icon: mailIcon, link: `mailto:?subject=Climate%20Watch&body=${url}` }, { label: 'Facebook', icon: facebookIcon, link: `https://www.facebook.com/sharer/sharer.php?u=${url}` }, { label: 'Twitter', icon: twitterIcon, link: `https://twitter.com/intent/tweet?url=${url}` }, { label: 'Copy link', icon: linkIcon, action: copyUrl } ]; return { shareMenuOptions, shareIcon }; }; export default connect(mapStateToProps, null)(Component);
import { connect } from 'react-redux'; import shareIcon from 'assets/icons/share.svg'; import facebookIcon from 'assets/icons/facebook.svg'; import twitterIcon from 'assets/icons/twitter.svg'; import mailIcon from 'assets/icons/mail.svg'; import linkIcon from 'assets/icons/link.svg'; import copy from 'copy-to-clipboard'; import Component from './share-menu-component'; const mapStateToProps = (state, { path }) => { const url = location.origin + (path || location.pathname); const copyUrl = () => copy(url); const shareMenuOptions = [ { label: 'Email', icon: mailIcon, link: `mailto:?subject=Climate%20Watch&body=${url}` }, { label: 'Facebook', icon: facebookIcon, link: `https://www.facebook.com/sharer/sharer.php?u=${url}` }, { label: 'Twitter', icon: twitterIcon, link: `https://twitter.com/intent/tweet?url=${url}` }, { label: 'Copy link', icon: linkIcon, action: copyUrl } ]; return { shareMenuOptions, shareIcon }; }; export default connect(mapStateToProps, null)(Component);
Add images to the asset pipeline
<?php namespace SMVC\Controller; class Asset extends \Base\Controller { public static $mapping = array( 'scripts' => '\Base\JavascriptAssetView', 'images' => '\Base\PngAssetView', 'scriptMap' => '\Base\SourceMapAssetView' ); public function run() { $args = func_get_args(); $section = array_shift($args); $fullfilename = array_pop($args); $args[] = preg_replace('/\.[a-z]+$/i', '', $fullfilename); $path = implode('/', $args); if (!array_key_exists($section, static::$mapping)) { $this->content = $section; // return $this->show_404(); } // Exception ... source maps if (preg_match('/\.map$/', $fullfilename)) { $section = 'scriptMap'; if (isProduction()) { return $this->content = '{}'; } } $viewClass = static::$mapping[$section]; header('Content-Type: ' . $viewClass::$mime); $view = new $viewClass($path); echo $view->render(); } }
<?php namespace SMVC\Controller; class Asset extends \Base\Controller { public static $mapping = array( 'scripts' => '\Base\JavascriptAssetView', 'scriptMap' => '\Base\SourceMapAssetView' ); public function run() { $args = func_get_args(); $section = array_shift($args); $fullfilename = array_pop($args); $args[] = preg_replace('/\.[a-z]+$/i', '', $fullfilename); $path = implode('/', $args); if (!array_key_exists($section, static::$mapping)) { $this->content = $section; // return $this->show_404(); } // Exception ... source maps if (preg_match('/\.map$/', $fullfilename)) { $section = 'scriptMap'; if (isProduction()) { return $this->content = '{}'; } } $viewClass = static::$mapping[$section]; header('Content-Type: ' . $viewClass::$mime); $view = new $viewClass($path); echo $view->render(); } }
Implement absolutely qualified namespace resolution.
<?php namespace Phortress; use PhpParser\Node\Name; use PhpParser\Node\Name\Relative; /** * The global environment for a program. * * @package Phortress */ class GlobalEnvironment extends NamespaceEnvironment { /** * The superglobals for this environment. * * @var array */ private $superglobals; public function __construct() { parent::__construct('Global', null); $this->superglobals = array( 'GLOBALS' => &$this->variables, '_SERVER' => array(), '_GET' => array(), '_POST' => array(), '_FILES' => array(), '_COOKIE' => array(), '_SESSION' => array(), '_REQUEST' => array(), '_ENV' => array() ); self::copyValueReferences($this->variables, $this->superglobals); } /** * Gets the superglobals in this global environment. * * @return array */ public function &getSuperglobals() { return $this->superglobals; } public function getGlobal() { return $this; } public function resolveNamespace(Name $namespaceName = null) { if (self::isAbsolutelyQualified($namespaceName)) { $namespaceName = new Relative( $namespaceName->parts, $namespaceName->getAttributes()); } return parent::resolveNamespace($namespaceName); } }
<?php namespace Phortress; /** * The global environment for a program. * * @package Phortress */ class GlobalEnvironment extends NamespaceEnvironment { /** * The superglobals for this environment. * * @var array */ private $superglobals; public function __construct() { parent::__construct('Global', null); $this->superglobals = array( 'GLOBALS' => &$this->variables, '_SERVER' => array(), '_GET' => array(), '_POST' => array(), '_FILES' => array(), '_COOKIE' => array(), '_SESSION' => array(), '_REQUEST' => array(), '_ENV' => array() ); self::copyValueReferences($this->variables, $this->superglobals); } public function getGlobal() { return $this; } /** * Gets the superglobals in this global environment. * * @return array */ public function &getSuperglobals() { return $this->superglobals; } }
Use util.log in uncaughtExpcetion handler.
"use strict"; var util = require("util"), express = require("express"), routes = require("./routes"), plugin = require("./plugin"); var app = express(), port = routes.config.port, staticFiles = express.static, apiUrl = routes.config.apiUrl; process.on("uncaughtException", function (err) { util.log(err); }); app.use(staticFiles(routes.config.staticFiles)); app.use(apiUrl, routes.apis); app.listen(port, function () { util.log("Argo listening on http://localhost:" + port); util.log("Argo listening apis on http://localhost:" + port + apiUrl); }).on("upgrade", function (request, socket, body) { routes.stream.run(request, socket, body); util.log("Argo streaming prices and events on ws://localhost:" + port + routes.config.streamUrl); }); plugin.startBridge();
"use strict"; var util = require("util"), express = require("express"), routes = require("./routes"), plugin = require("./plugin"); var app = express(), port = routes.config.port, staticFiles = express.static, apiUrl = routes.config.apiUrl; process.on("uncaughtException", function (err) { console.log(err); }); app.use(staticFiles(routes.config.staticFiles)); app.use(apiUrl, routes.apis); app.listen(port, function () { util.log("Argo listening on http://localhost:" + port); util.log("Argo listening apis on http://localhost:" + port + apiUrl); }).on("upgrade", function (request, socket, body) { routes.stream.run(request, socket, body); util.log("Argo streaming prices and events on ws://localhost:" + port + routes.config.streamUrl); }); plugin.startBridge();
Put a override to check if it's admin and put the correct design path
<?php class WizardsFugue_Core_Model_Design_Package extends Mage_Core_Model_Design_Package { protected function _fallback($file, array &$params, array $fallbackScheme = array(array())) { if($params['_area'] == 'adminhtml') { // set on the custom admin design dir Mage::app()->getConfig()->getOptions()->setData('design_dir', Mage::app()->getConfig()->getOptions()->getAdminDesignDir()); } $result = parent::_fallback($file, $params, $fallbackScheme); if( !$result ){ if($params['_area'] == 'adminhtml') { $result = 'adminhtml/default/default/' . $file; } else { $result = 'frontend/base/default/template/' . $file; } } return $result; } }
<?php class WizardsFugue_Core_Model_Design_Package extends Mage_Core_Model_Design_Package { protected function _fallback($file, array &$params, array $fallbackScheme = array(array())) { $result = parent::_fallback($file, $params, $fallbackScheme); /* var_dump( $file, $result, file_exists($result) ); die(__FILE__.':'.__LINE__); */ if( !$result ){ $result = 'frontend/base/default/template/' . $file; } return $result; } }
Add test for dash case
package com.karateca.jstoolbox.dashcamel; import org.junit.Test; import static org.junit.Assert.*; public class CaseHelperTest { @Test public void shouldTransformToCamelCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one-two-three")); assertEquals("one", CaseHelper.toCamelCase("one")); assertEquals("o", CaseHelper.toCamelCase("o")); } @Test public void shouldTransformEmptyString() { assertEquals("", CaseHelper.toCamelCase("")); } @Test public void shouldAcceptSpaces() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("x", CaseHelper.toCamelCase(" x -- - - - ")); } @Test public void shouldAcceptMultipleDashes() { assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("one--two---threeee ")); assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("---one--two---threeee---")); } @Test public void shouldCorrectUpperCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("ONE-TWO-THREE")); } @Test public void shouldTransformCamelToDash() { assertEquals("one-two", CaseHelper.toDashCase("oneTwo")); } }
package com.karateca.jstoolbox.dashcamel; import org.junit.Test; import static org.junit.Assert.*; public class CaseHelperTest { @Test public void shouldTransformToCamelCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one-two-three")); assertEquals("one", CaseHelper.toCamelCase("one")); } @Test public void shouldTransformEmptyString() { assertEquals("", CaseHelper.toCamelCase("")); } @Test public void shouldAcceptSpaces() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); assertEquals("oneTwoThree", CaseHelper.toCamelCase("one two-three")); } @Test public void shouldAcceptMultipleDashes() { assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("one--two---threeee ")); assertEquals("oneTwoThreeee", CaseHelper.toCamelCase("---one--two---threeee---")); } @Test public void shouldCorrectUpperCase() { assertEquals("oneTwoThree", CaseHelper.toCamelCase("ONE-TWO-THREE")); } }
Make the parameters argument optional
<?php namespace BinSoul\Db; /** * Represents a connection to a database. */ interface Connection { /** * Opens the connection. * * @return bool */ public function open(); /** * Closes the connection. * * @return bool */ public function close(); /** * Executes an arbitrary statement. * * @param string $statement * @param mixed[] $parameters * * @return Result */ public function execute($statement, array $parameters = []); /** * Starts a new transaction. * * @return bool */ public function begin(); /** * Commits the current transaction. * * @return bool */ public function commit(); /** * Rolls back the current transaction. * * @return bool */ public function rollback(); }
<?php namespace BinSoul\Db; /** * Represents a connection to a database. */ interface Connection { /** * Opens the connection. * * @return bool */ public function open(); /** * Closes the connection. * * @return bool */ public function close(); /** * Executes an arbitrary statement using the given parameters. * * @param string $statement * @param mixed[] $parameters * * @return Result */ public function execute($statement, array $parameters); /** * Starts a new transaction. * * @return bool */ public function begin(); /** * Commits the current transaction. * * @return bool */ public function commit(); /** * Rolls back the current transaction. * * @return bool */ public function rollback(); }
Remove old caching logic, and add missing docblock.
<?php namespace VotingApp\Models; use Illuminate\Database\Eloquent\Model; use Cviebrock\EloquentSluggable\SluggableInterface; use Cviebrock\EloquentSluggable\SluggableTrait; class Category extends Model implements SluggableInterface { use SluggableTrait; /** * The attributes which may be mass-assigned. * * @var array */ protected $fillable = [ 'name' ]; /** * Configuration for generating slug with Eloquent-Sluggable. * * @var array */ protected $sluggable = [ 'build_from' => 'name', 'save_to' => 'slug' ]; /** * A category has many candidates. * @return mixed */ public function candidates() { return $this->hasMany('VotingApp\Models\Candidate')->orderBy('name', 'asc'); } }
<?php namespace VotingApp\Models; use Illuminate\Database\Eloquent\Model; use Cviebrock\EloquentSluggable\SluggableInterface; use Cviebrock\EloquentSluggable\SluggableTrait; class Category extends Model implements SluggableInterface { use SluggableTrait; public static function boot() { parent::boot(); Category::saved(function ($category) { // Clear categories cache whenever model is updated \Cache::forget('categories'); }); } /** * The attributes which may be mass-assigned. * * @var array */ protected $fillable = [ 'name' ]; /** * Configuration for generating slug with Eloquent-Sluggable. * * @var array */ protected $sluggable = [ 'build_from' => 'name', 'save_to' => 'slug' ]; public function candidates() { return $this->hasMany('VotingApp\Models\Candidate')->orderBy('name', 'asc'); } }
Fix sample for custom tooling model: ToolingModelBuilder is an interface.
package org.gradle.sample.plugin; import javax.inject.Inject; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.tooling.provider.model.ToolingModelBuilder; import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry; /** * A plugin that exposes a custom tooling model. */ public class CustomPlugin implements Plugin<Project> { private final ToolingModelBuilderRegistry registry; /** * Need to use a {@link ToolingModelBuilderRegistry} to register the custom tooling model, so inject this into * the constructor. */ @Inject public CustomPlugin(ToolingModelBuilderRegistry registry) { this.registry = registry; } public void apply(Project project) { // Register a builder for the custom tooling model registry.register(new CustomToolingModelBuilder()); } private static class CustomToolingModelBuilder implements ToolingModelBuilder { public boolean canBuild(String modelName) { // The default name for a model is the name of the Java interface return modelName.equals(CustomModel.class.getName()); } public Object buildAll(String modelName, Project project) { return new DefaultModel(); } } }
package org.gradle.sample.plugin; import javax.inject.Inject; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.tooling.provider.model.ToolingModelBuilder; import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry; /** * A plugin that exposes a custom tooling model. */ public class CustomPlugin implements Plugin<Project> { private final ToolingModelBuilderRegistry registry; /** * Need to use a {@link ToolingModelBuilderRegistry} to register the custom tooling model, so inject this into * the constructor. */ @Inject public CustomPlugin(ToolingModelBuilderRegistry registry) { this.registry = registry; } public void apply(Project project) { // Register a builder for the custom tooling model registry.register(new CustomToolingModelBuilder()); } private static class CustomToolingModelBuilder extends ToolingModelBuilder { public boolean canBuild(String modelName) { // The default name for a model is the name of the Java interface return modelName.equals(CustomModel.class.getName()); } public Object buildAll(String modelName, Project project) { return new DefaultModel(); } } }
fix(form): Update PlanTripButton to work with recent API refactor
import React, { Component, PropTypes } from 'react' import { Button } from 'react-bootstrap' import { connect } from 'react-redux' import { routingQuery } from '../../actions/api' class PlanTripButton extends Component { static propTypes = { routingType: PropTypes.string, text: PropTypes.string, onClick: PropTypes.func, planTrip: PropTypes.func, profileTrip: PropTypes.func } _onClick = () => { this.props.routingQuery() } render () { return ( <Button className='plan-trip-button' onClick={this._onClick || this.props.onClick} >{this.props.text || 'Plan Trip'}</Button> ) } } const mapStateToProps = (state, ownProps) => { return {} } const mapDispatchToProps = (dispatch, ownProps) => { return { routingQuery: () => { dispatch(routingQuery()) } } } export default connect(mapStateToProps, mapDispatchToProps)(PlanTripButton)
import React, { Component, PropTypes } from 'react' import { Button } from 'react-bootstrap' import { connect } from 'react-redux' import { planTrip, profileTrip } from '../../actions/api' class PlanTripButton extends Component { static propTypes = { routingType: PropTypes.string, text: PropTypes.string, onClick: PropTypes.func, planTrip: PropTypes.func, profileTrip: PropTypes.func } _onClick = () => { switch (this.props.routingType) { case 'ITINERARY': this.props.planTrip() break case 'PROFILE': this.props.profileTrip() break } } render () { return ( <Button className='plan-trip-button' onClick={this._onClick || this.props.onClick} >{this.props.text || 'Plan Trip'}</Button> ) } } const mapStateToProps = (state, ownProps) => { return { routingType: state.otp.currentQuery.routingType } } const mapDispatchToProps = (dispatch, ownProps) => { return { planTrip: () => { dispatch(planTrip()) }, profileTrip: () => { dispatch(profileTrip()) } } } export default connect(mapStateToProps, mapDispatchToProps)(PlanTripButton)
Add jinja2 as a dependency for HTML generation.
#!/usr/bin/env python # encoding: utf-8 from setuptools import setup, find_packages setup( name='reddit2Kindle', scripts=['r2K.py'], packages=find_packages(), install_requires=[ 'markdown2', 'praw', 'docopt', 'jinja2' ], version='0.5.0', author='Antriksh Yadav', author_email='antrikshy@gmail.com', url='http://www.antrikshy.com/projects/reddit2Kindle.htm', description=( 'Compiles top posts from a specified subreddit for a specified time' 'period into a well-formatted Kindle book.' ), long_description=( 'See http://www.github.com/Antrikshy/reddit2Kindle for instructions.' 'Requires KindleGen from Amazon to convert HTML result to .mobi for' 'Kindle.' ), classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', 'Development Status :: 4 - Beta', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'License :: OSI Approved :: MIT License' ], )
#!/usr/bin/env python # encoding: utf-8 from setuptools import setup, find_packages setup( name='reddit2Kindle', scripts=['r2K.py'], packages=find_packages(), install_requires=[ 'markdown2', 'praw', 'docopt' ], version='0.5.0', author='Antriksh Yadav', author_email='antrikshy@gmail.com', url='http://www.antrikshy.com/projects/reddit2Kindle.htm', description=( 'Compiles top posts from a specified subreddit for a specified time' 'period into a well-formatted Kindle book.' ), long_description=( 'See http://www.github.com/Antrikshy/reddit2Kindle for instructions.' 'Requires KindleGen from Amazon to convert HTML result to .mobi for' 'Kindle.' ), classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', 'Development Status :: 4 - Beta', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'License :: OSI Approved :: MIT License' ], )
Fix how hppcorbaserver is killed in ServerManager
# Copyright (c) 2020, CNRS # Authors: Guilhem Saurel <guilhem.saurel@laas.fr> import os import subprocess import time import hpp.corbaserver try: from subprocess import DEVNULL, run except ImportError: # Python2 fallback DEVNULL = os.open(os.devnull, os.O_RDWR) def run(*args): subprocess.Popen(*args).wait() class ServerManager: """A context to ensure a server is running.""" def __init__(self, server="hppcorbaserver"): self.server = server run(["killall", self.server]) def __enter__(self): """Run the server in background stdout and stderr outputs of the child process are redirected to devnull. preexec_fn is used to ignore ctrl-c signal send to the main script (otherwise they are forwarded to the child process) """ self.process = subprocess.Popen( self.server, stdout=DEVNULL, stderr=DEVNULL, preexec_fn=os.setpgrp ) # give it some time to start time.sleep(3) def __exit__(self, exc_type, exc_value, exc_traceback): tool = hpp.corbaserver.tools.Tools() tool.shutdown() self.process.communicate()
# Copyright (c) 2020, CNRS # Authors: Guilhem Saurel <guilhem.saurel@laas.fr> import os import subprocess import time try: from subprocess import DEVNULL, run except ImportError: # Python2 fallback DEVNULL = os.open(os.devnull, os.O_RDWR) def run(*args): subprocess.Popen(*args).wait() class ServerManager: """A context to ensure a server is running.""" def __init__(self, server="hppcorbaserver"): self.server = server run(["killall", self.server]) def __enter__(self): """Run the server in background stdout and stderr outputs of the child process are redirected to devnull. preexec_fn is used to ignore ctrl-c signal send to the main script (otherwise they are forwarded to the child process) """ self.process = subprocess.Popen( self.server, stdout=DEVNULL, stderr=DEVNULL, preexec_fn=os.setpgrp ) # give it some time to start time.sleep(3) def __exit__(self, exc_type, exc_value, exc_traceback): self.process.kill()
Remove artifacts from transpilation of ts -> js in config.
// A real test configuration // @todo: consider reading from env vars exports.server = { passportSecret: "something", loggerLevel: "debug", http: { active: true, port: 1080 }, recording_url_base: "http://test.site/recording" }; exports.s3 = { publicKey: "minio", privateKey: "miniostorage", bucket: "cacophony", endpoint: "http://127.0.0.1:9001" }; exports.fileProcessing = { port: 2008 }; // ======= Database settings ======= exports.database = { username: "test", password: "test", database: "cacophonytest", host: "localhost", dialect: "postgres" }; // This is needed because Sequelize looks for development by default // when using db:migrate exports.development = exports.database; exports.default = { server: exports.server, s3: exports.s3, fileProcessing: exports.fileProcessing, database: exports.database, };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // A real test configuration // @todo: consider reading from env vars exports.server = { passportSecret: "something", loggerLevel: "debug", http: { active: true, port: 1080 }, recording_url_base: "http://test.site/recording" }; exports.s3 = { publicKey: "minio", privateKey: "miniostorage", bucket: "cacophony", endpoint: "http://127.0.0.1:9001" }; exports.fileProcessing = { port: 2008 }; // ======= Database settings ======= exports.database = { username: "test", password: "test", database: "cacophonytest", host: "localhost", dialect: "postgres" }; // This is needed because Sequelize looks for development by default // when using db:migrate exports.development = exports.database; exports.default = { server: exports.server, s3: exports.s3, fileProcessing: exports.fileProcessing, database: exports.database, };
Fix NPE in server address Fixed an NPE in `GrpcServerAddress` when the address is passed in unresolved. pr-link: Alluxio/alluxio#8679 change-id: cid-d04e4417be2f96add1f85d718d74a96bdb6a76f4
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 (the * "License"). You may not use this work except in compliance with the License, which is available * at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.grpc; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * Defines an gRPC server endpoint. */ public class GrpcServerAddress { /** Physical address. */ private SocketAddress mSocketAddress; /** Target host name. */ private String mHostName; /** * @param socketAddress physical address */ public GrpcServerAddress(InetSocketAddress socketAddress) { mHostName = socketAddress.getHostName(); mSocketAddress = socketAddress; } /** * @param hostName target host name * @param socketAddress physical address */ public GrpcServerAddress(String hostName, SocketAddress socketAddress) { mHostName = hostName; mSocketAddress = socketAddress; } /** * @return the host name */ public String getHostName() { return mHostName; } /** * @return the host name */ public SocketAddress getSocketAddress() { return mSocketAddress; } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 (the * "License"). You may not use this work except in compliance with the License, which is available * at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.grpc; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * Defines an gRPC server endpoint. */ public class GrpcServerAddress { /** Physical address. */ private SocketAddress mSocketAddress; /** Target host name. */ private String mHostName; /** * @param socketAddress physical address */ public GrpcServerAddress(InetSocketAddress socketAddress) { mHostName = socketAddress.getAddress().getHostName(); mSocketAddress = socketAddress; } /** * @param hostName target host name * @param socketAddress physical address */ public GrpcServerAddress(String hostName, SocketAddress socketAddress) { mHostName = hostName; mSocketAddress = socketAddress; } /** * @return the host name */ public String getHostName() { return mHostName; } /** * @return the host name */ public SocketAddress getSocketAddress() { return mSocketAddress; } }
Check for the specified env variable
<?php namespace Dock\System\Environ; use Dock\IO\ProcessRunner; use Symfony\Component\Process\Process; class BashEnvironManipulator implements EnvironManipulator { /** * @var string */ private $file; /** * @var ProcessRunner */ private $processRunner; /** * @param string $file */ public function __construct(ProcessRunner $processRunner, $file) { $this->file = $file; $this->processRunner = $processRunner; } /** * {@inheritdoc} */ public function save(EnvironmentVariable $environmentVariable) { $command = 'echo "'.$environmentVariable->getName().'='.$environmentVariable->getValue().'" >> '.$this->file; $process = new Process($command); $this->processRunner->run($process); } /** * {@inheritdoc} */ public function has(EnvironmentVariable $environmentVariable) { $process = $this->processRunner->run( new Process("grep {$environmentVariable->getName()} $this->file"), false ); $result = $process->getOutput(); return !empty($result); } }
<?php namespace Dock\System\Environ; use Dock\IO\ProcessRunner; use Symfony\Component\Process\Process; class BashEnvironManipulator implements EnvironManipulator { /** * @var string */ private $file; /** * @var ProcessRunner */ private $processRunner; /** * @param string $file */ public function __construct(ProcessRunner $processRunner, $file) { $this->file = $file; $this->processRunner = $processRunner; } /** * {@inheritdoc} */ public function save(EnvironmentVariable $environmentVariable) { $command = 'echo "'.$environmentVariable->getName().'='.$environmentVariable->getValue().'" >> '.$this->file; $process = new Process($command); $this->processRunner->run($process); } /** * {@inheritdoc} */ public function has(EnvironmentVariable $environmentVariable) { $process = $this->processRunner->run( new Process('grep DOCKER_HOST '.$this->file), false ); $result = $process->getOutput(); return !empty($result); } }
Print newline for error message
package main import ( "flag" "fmt" "os" ) func main() { defer func() { if r := recover(); r != nil { fmt.Fprintf(os.Stderr, "%s\n", r) } }() var chewing bool var ctx BenchmarkContext defer func() { ctx.deinit() }() flag.BoolVar(&chewing, "chewing", true, "Enable libchewing benchmark") flag.Parse() if chewing { ctx.addBenchmarkItem(newChewingBenchmarkItem()) } for _, input := range flag.Args() { fmt.Printf("Processing %s ... ", input) inputSeq, err := getBenchmarkInput(input) if err != nil { fmt.Fprintf(os.Stderr, "Cannot open %s\n", input) continue } for _, input := range inputSeq { ctx.enterBenchmarkInput(&input) } fmt.Printf("Done\n") } ctx.print() }
package main import ( "flag" "fmt" "os" ) func main() { defer func() { if r := recover(); r != nil { fmt.Fprint(os.Stderr, r) } }() var chewing bool var ctx BenchmarkContext defer func() { ctx.deinit() }() flag.BoolVar(&chewing, "chewing", true, "Enable libchewing benchmark") flag.Parse() if chewing { ctx.addBenchmarkItem(newChewingBenchmarkItem()) } for _, input := range flag.Args() { fmt.Printf("Processing %s ... ", input) inputSeq, err := getBenchmarkInput(input) if err != nil { fmt.Fprintf(os.Stderr, "Cannot open %s\n", input) continue } for _, input := range inputSeq { ctx.enterBenchmarkInput(&input) } fmt.Printf("Done\n") } ctx.print() }
Ch23: Use horizontal filter for M2M in PostAdmin.
from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ('title', 'pub_date') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)}
from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ('title', 'pub_date') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('startups',) filter_vertical = ('tags',) prepopulated_fields = {"slug": ("title",)}
Add test to event bus with different types of events
"use strict"; var EventBus = require('../lib/messages/EventBus'); describe('Event Bus', function () { it("should publish an event", function () { var eventBus = new EventBus(), subscriber = { action: function (data) { } }; spyOn(subscriber, "action"); eventBus.subscribe("TEST_NOTIFICATION", subscriber.action); eventBus.publish("TEST_NOTIFICATION", {test: 10}); expect(subscriber.action).toHaveBeenCalledWith({test: 10}); expect(subscriber.action.calls.count()).toBe(1); }); it("should not receive the event if wrong type of event", function () { var eventBus = new EventBus(), subscriber = { action: function (data) { } }; spyOn(subscriber, "action"); eventBus.subscribe("TEST_NOTIFICATION_WRONG", subscriber.action); eventBus.publish("TEST_NOTIFICATION", {test: 10}); expect(subscriber.action.calls.count()).toBe(0); }); });
"use strict"; var EventBus = require('../lib/messages/EventBus'); describe('Event Bus', function () { it("should publish an event", function () { var eventBus = new EventBus(), subscriber = { action: function (data) { } }; spyOn(subscriber, "action"); eventBus.subscribe("TEST_NOTIFICATION", subscriber.action); eventBus.publish("TEST_NOTIFICATION", {test: 10}); expect(subscriber.action).toHaveBeenCalledWith({test: 10}); expect(subscriber.action.calls.count()).toBe(1); }); });
Fix wrong message in $error404 variable.
<?php header("Content-type:application/json"); require_once 'details/user_management.php'; if (!is_logged_in()) exit('{"error":{"code":403,"reason":"Not authenticated"}}'); require_once 'details/user.php'; $db = new PDO('sqlite:../sql/OIS.db'); $field = 'UserId'; $error400 = '{"error":{"code":400,"reason":"Bad request"}}'; $error404 = '{"error":{"code":404,"reason":"User not found"}}'; if (!array_key_exists($field, $_GET)) { exit($error400); } $userIdStr = htmlspecialchars($_GET[$field]); $user = new User; $error = $user->queryDbById($userIdStr); if ($error) { $error = "error" . $error; exit($$error); } echo $user->encode("json");
<?php header("Content-type:application/json"); require_once 'details/user_management.php'; if (!is_logged_in()) exit('{"error":{"code":403,"reason":"Not authenticated"}}'); require_once 'details/user.php'; $db = new PDO('sqlite:../sql/OIS.db'); $field = 'UserId'; $error400 = '{"error":{"code":400,"reason":"Bad request"}}'; $error404 = '{"error":{"code":404,"reason":"Invoice not found"}}'; if (!array_key_exists($field, $_GET)) { exit($error400); } $userIdStr = htmlspecialchars($_GET[$field]); $user = new User; $error = $user->queryDbById($userIdStr); if ($error) { $error = "error" . $error; exit($$error); } echo $user->encode("json");
Remove square brackets around log level in log ouput
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s %(levelname)s %(message)s') formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
Enable version in -h output
#!/usr/bin/env node var cli = require('cli').enable('version');; var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ append: ['a', 'append to the given FILEs, do not overwrite'], suppress: ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
#!/usr/bin/env node var cli = require('cli'); var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ append: ['a', 'append to the given FILEs, do not overwrite'], suppress: ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
Change expected from `TINYINT` to `BOOLEAN` The value of Boolean::$type was changed from `TINYINT` to `BOOLEAN` in a [commit](The https://github.com/zendframework/zf2/commit/e287ebfc9935e0fbc74998fe138aba67764250db) made by @SlayerBirden. It appears the tests were not changed to account for the new value.
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Db\Sql\Ddl\Column; use Zend\Db\Sql\Ddl\Column\Boolean; class BooleanTest extends \PHPUnit_Framework_TestCase { /** * @covers Zend\Db\Sql\Ddl\Column\Boolean::getExpressionData */ public function testGetExpressionData() { $column = new Boolean('foo'); $this->assertEquals( array(array('%s %s NOT NULL', array('foo', 'BOOLEAN'), array($column::TYPE_IDENTIFIER, $column::TYPE_LITERAL))), $column->getExpressionData() ); } /** * @covers Zend\Db\Sql\Ddl\Column\Boolean * * @group 6257 */ public function testIsAlwaysNotNullable() { $column = new Boolean('foo', true); $this->assertFalse($column->isNullable()); $column->setNullable(true); $this->assertFalse($column->isNullable()); } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Db\Sql\Ddl\Column; use Zend\Db\Sql\Ddl\Column\Boolean; class BooleanTest extends \PHPUnit_Framework_TestCase { /** * @covers Zend\Db\Sql\Ddl\Column\Boolean::getExpressionData */ public function testGetExpressionData() { $column = new Boolean('foo'); $this->assertEquals( array(array('%s %s NOT NULL', array('foo', 'TINYINT'), array($column::TYPE_IDENTIFIER, $column::TYPE_LITERAL))), $column->getExpressionData() ); } /** * @covers Zend\Db\Sql\Ddl\Column\Boolean * * @group 6257 */ public function testIsAlwaysNotNullable() { $column = new Boolean('foo', true); $this->assertFalse($column->isNullable()); $column->setNullable(true); $this->assertFalse($column->isNullable()); } }
Make self posts without text bodies to not have any media adapter delegate
package com.veyndan.redditclient.post.media.mutator; import android.text.TextUtils; import com.veyndan.redditclient.api.reddit.model.PostHint; import com.veyndan.redditclient.post.media.model.Text; import com.veyndan.redditclient.post.model.Post; import rx.Observable; final class TextMutatorFactory implements MutatorFactory { static TextMutatorFactory create() { return new TextMutatorFactory(); } private TextMutatorFactory() { } @Override public Observable<Post> mutate(final Post post) { return Observable.just(post) .filter(post1 -> post1.getPostHint().equals(PostHint.SELF) && !TextUtils.isEmpty(post1.getBodyHtml())) .map(post1 -> { post1.setMediaObservable(Observable.just(new Text(post1.getBodyHtml()))); return post1; }); } }
package com.veyndan.redditclient.post.media.mutator; import com.veyndan.redditclient.api.reddit.model.PostHint; import com.veyndan.redditclient.post.media.model.Text; import com.veyndan.redditclient.post.model.Post; import rx.Observable; final class TextMutatorFactory implements MutatorFactory { static TextMutatorFactory create() { return new TextMutatorFactory(); } private TextMutatorFactory() { } @Override public Observable<Post> mutate(final Post post) { return Observable.just(post) .filter(post1 -> post1.getPostHint().equals(PostHint.SELF)) .map(post1 -> { post1.setMediaObservable(Observable.just(new Text(post1.getBodyHtml()))); return post1; }); } }
Fix nasty hardcoded class name.
/** * JReversePro - Java Decompiler / Disassembler. * Copyright (C) 2008 Karthik Kumar. * * 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.jreversepro.jls.emitter.java14; import java.util.HashMap; import java.util.Map; import org.jreversepro.ast.block.MethodBlock; import org.jreversepro.ast.block.Statement; import org.jreversepro.jls.emitter.BlockEmitterConfig; /** * * @author karthikeyanc * */ public class BlockEmitterConfigImpl_14 extends BlockEmitterConfig { @Override public Map<String, String> getConfig() { Map<String, String> map = new HashMap<String, String>(); map.put(MethodBlock.class.getName(), MethodEmitter.class.getName()); map.put(Statement.class.getName(), StatementEmitter.class.getName()); return map; } }
/** * JReversePro - Java Decompiler / Disassembler. * Copyright (C) 2008 Karthik Kumar. * * 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.jreversepro.jls.emitter.java14; import java.util.HashMap; import java.util.Map; import org.jreversepro.jls.emitter.BlockEmitterConfig; /** * * @author karthikeyanc * */ public class BlockEmitterConfigImpl_14 extends BlockEmitterConfig { public Map<String, String> getConfig() { Map<String, String> map = new HashMap<String, String>(); map.put("net.sf.jrevpro.ast.block.MethodBlock", "net.sf.jrevpro.jls.emitter.java14.MethodEmitter"); map.put("net.sf.jrevpro.ast.block.Statement", "net.sf.jrevpro.jls.emitter.java14.StatementEmitter"); return map; } }
Remove _ prefix for private class attribute Was from Pear coding conventions but doesnt make sense anymore since PHP has now access modifiers
<?php /** * @title Singleton Helper Trait * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Pattern * @version 1.0 */ namespace PH7\Framework\Pattern; defined('PH7') or exit('Restricted access'); trait Singleton { use Statik; /** * @staticvar object $oInstance */ protected static $oInstance = null; /** * Get instance of class. * * @return self Returns the instance class or create initial instance of the class. */ public static function getInstance() { return null === static::$oInstance ? static::$oInstance = new static : static::$oInstance; } /** * Directly call "static::getInstance()" method when the object is called as a function. */ public function __invoke() { return static::getInstance(); } /** * Private serialize/unserialize method to prevent serializing/unserializing. */ private function __wakeup() { } private function __sleep() { } }
<?php /** * @title Singleton Helper Trait * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Pattern * @version 1.0 */ namespace PH7\Framework\Pattern; defined('PH7') or exit('Restricted access'); trait Singleton { use Statik; /** * @staticvar object $_oInstance */ protected static $_oInstance = null; /** * Get instance of class. * * @return self Returns the instance class or create initial instance of the class. */ public static function getInstance() { return null === static::$_oInstance ? static::$_oInstance = new static : static::$_oInstance; } /** * Directly call "static::getInstance()" method when the object is called as a function. */ public function __invoke() { return static::getInstance(); } /** * Private serialize/unserialize method to prevent serializing/unserializing. */ private function __wakeup() { } private function __sleep() { } }
Make conditional rendering even shorter syntax
import React from 'react'; import PropTypes from 'prop-types'; import styles from './boardCard.css'; const BoardCard = ({ alt, name, role, src, description }) => ( <div className={styles.boardCard}> <img className={styles.img} src={src} alt={alt} /> <span className={styles.name}> {name} </span> <hr className={styles.hr} /> <span className={styles.item}> <span className={styles.upper}>Role: </span> {role} {description && <p>{description}</p>} </span> </div> ); BoardCard.propTypes = { name: PropTypes.string.isRequired, src: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, role: PropTypes.string.isRequired, description: PropTypes.string }; BoardCard.defaultProps = { description: null }; export default BoardCard;
import React from 'react'; import PropTypes from 'prop-types'; import styles from './boardCard.css'; const BoardCard = ({ alt, name, role, src, description }) => ( <div className={styles.boardCard}> <img className={styles.img} src={src} alt={alt} /> <span className={styles.name}> {name} </span> <hr className={styles.hr} /> <span className={styles.item}> <span className={styles.upper}>Role: </span> {role} {description !== null && <p>{description}</p>} </span> </div> ); BoardCard.propTypes = { name: PropTypes.string.isRequired, src: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, role: PropTypes.string.isRequired, description: PropTypes.string }; BoardCard.defaultProps = { description: null }; export default BoardCard;
Improve top level class description
// Internal: CavyReporter is responsible for sending the test results to // the CLI. export default class CavyReporter { // Internal: Creates a websocket connection to the cavy-cli server. onStart() { const url = 'ws://127.0.0.1:8082/'; this.ws = new WebSocket(url); } // Internal: Send report to cavy-cli over the websocket connection. onFinish(report) { // WebSocket.readyState 1 means the web socket connection is OPEN. if (this.ws.readyState == 1) { try { this.ws.send(JSON.stringify(report)); console.log('Cavy test report successfully sent to cavy-cli'); } catch (e) { console.group('Error sending test results'); console.warn(e.message); console.groupEnd(); } } else { // If cavy-cli is not running, let people know in a friendly way const message = "Skipping sending test report to cavy-cli - if you'd " + 'like information on how to set up cavy-cli, check out the README ' + 'https://github.com/pixielabs/cavy-cli'; console.log(message); } } }
// cavy-cli reporter class. export default class CavyReporter { // Internal: Creates a websocket connection to the cavy-cli server. onStart() { const url = 'ws://127.0.0.1:8082/'; this.ws = new WebSocket(url); } // Internal: Send report to cavy-cli over the websocket connection. onFinish(report) { // WebSocket.readyState 1 means the web socket connection is OPEN. if (this.ws.readyState == 1) { try { this.ws.send(JSON.stringify(report)); console.log('Cavy test report successfully sent to cavy-cli'); } catch (e) { console.group('Error sending test results'); console.warn(e.message); console.groupEnd(); } } else { // If cavy-cli is not running, let people know in a friendly way const message = "Skipping sending test report to cavy-cli - if you'd " + 'like information on how to set up cavy-cli, check out the README ' + 'https://github.com/pixielabs/cavy-cli'; console.log(message); } } }
Fix CSS not updating on development mode
// Compile SCSS files into CSS (dev mode is not compressed) module.exports = { dev: { options: { style: 'expanded' }, files: { 'dist/vizabi.css': 'src/assets/style/vizabi.scss' } }, prod: { options: { style: 'compressed' }, files: { 'dist/vizabi.css': 'src/assets/style/vizabi.scss' } }, preview: { options: { style: 'compressed' }, files: { 'preview_src/assets/css/main.css': 'preview_src/assets/sass/main.scss' } } };
// Compile SCSS files into CSS (dev mode is not compressed) module.exports = { dev: { options: { style: 'expanded' }, files: { 'preview/vizabi.css': 'src/assets/style/vizabi.scss' } }, prod: { options: { style: 'compressed' }, files: { 'dist/vizabi.css': 'src/assets/style/vizabi.scss' } }, preview: { options: { style: 'compressed' }, files: { 'preview_src/assets/css/main.css': 'preview_src/assets/sass/main.scss' } } };
Update sortArray to return the sorted array
package uk.co.johnjtaylor; /** * A Simple bubblesort class used as an easy base-line for algorithm testing * @author John * @param <T> * */ public class BubbleSort<T extends Comparable<T>> extends Sort<T> { /** * Takes an array of any comparable type and sorts it * @param array The array the be sorted */ public T[] sortArray(T[] array) { int swaps; do { swaps = 0; for(int i = 0; i < array.length-1; i++) { if(array[i].compareTo(array[i+1]) > 0) { T temp = array[i+1]; array[i+1] = array[i]; array[i] = temp; swaps++; } } } while (swaps > 0); return array; } }
package uk.co.johnjtaylor; /** * A Simple bubblesort class used as an easy base-line for algorithm testing * @author John * @param <T> * */ public class BubbleSort<T extends Comparable<T>> extends Sort { /** * Takes an array of any comparable type and sorts it * @param array The array the be sorted */ public void sortArray(T[] array) { int swaps; do { swaps = 0; for(int i = 0; i < array.length-1; i++) { if(array[i].compareTo(array[i+1]) > 0) { T temp = array[i+1]; array[i+1] = array[i]; array[i] = temp; swaps++; } } } while (swaps > 0); } }
Add back in providerType - was too quick on the trigger to remove it
'use strict'; let angular = require('angular'); module.exports = angular .module('spinnaker.gce.serverGroup.transformer', [ require('../../core/utils/lodash.js'), ]) .factory('gceServerGroupTransformer', function ($q, _) { function normalizeServerGroup(serverGroup) { return $q.when(serverGroup); // no-op } function convertServerGroupCommandToDeployConfiguration(base) { // use _.defaults to avoid copying the backingData, which is huge and expensive to copy over var command = _.defaults({backingData: [], viewState: []}, base); if (base.viewState.mode !== 'clone') { delete command.source; } command.cloudProvider = 'gce'; command.availabilityZones = {}; command.availabilityZones[command.region] = [base.zone]; command.account = command.credentials; delete command.region; delete command.viewState; delete command.backingData; delete command.selectedProvider; delete command.implicitSecurityGroups; return command; } return { convertServerGroupCommandToDeployConfiguration: convertServerGroupCommandToDeployConfiguration, normalizeServerGroup: normalizeServerGroup, }; }).name;
'use strict'; let angular = require('angular'); module.exports = angular .module('spinnaker.gce.serverGroup.transformer', [ require('../../core/utils/lodash.js'), ]) .factory('gceServerGroupTransformer', function ($q, _) { function normalizeServerGroup(serverGroup) { return $q.when(serverGroup); // no-op } function convertServerGroupCommandToDeployConfiguration(base) { // use _.defaults to avoid copying the backingData, which is huge and expensive to copy over var command = _.defaults({backingData: [], viewState: []}, base); if (base.viewState.mode !== 'clone') { delete command.source; } command.cloudProvider = 'gce'; command.availabilityZones = {}; command.availabilityZones[command.region] = [base.zone]; command.account = command.credentials; delete command.region; delete command.viewState; delete command.backingData; delete command.selectedProvider; delete command.implicitSecurityGroups; delete command.providerType; return command; } return { convertServerGroupCommandToDeployConfiguration: convertServerGroupCommandToDeployConfiguration, normalizeServerGroup: normalizeServerGroup, }; }).name;
Fix the accurate file to prevent import errors Change-Id: I0e4d246518bbdd9745d61a06d6960b89cf9ed611
#!/usr/bin/env python # Copyright 2014 - Rackspace Hosting # # 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 sys from oslo_config import cfg from solum.common import context from solum.openstack.common import log as logging from solum.worker import api LOG = logging.getLogger(__name__) if __name__ == '__main__': conf_files = ['--config-file=/etc/solum/solum.conf'] cfg.CONF(conf_files, project='solum') message = ' '.join(sys.argv[1:]) api.API(context=context.RequestContext()).echo(message)
#!/usr/bin/env python # Copyright 2014 - Rackspace Hosting # # 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 sys from oslo.config import cfg from solum.common import context from solum.openstack.common import log as logging from solum.worker import api LOG = logging.getLogger(__name__) if __name__ == '__main__': conf_files = ['--config-file=/etc/solum/solum.conf'] cfg.CONF(conf_files, project='solum') message = ' '.join(sys.argv[1:]) api.API(context=context.RequestContext()).echo(message)
Update Dotenv config to the new version
<?php declare(strict_types=1); /* * This file is part of gpupo/common-schema * Created by Gilmar Pupo <contact@gpupo.com> * For the information of copyright and license you should read the file * LICENSE which is distributed with this source code. * Para a informação dos direitos autorais e de licença você deve ler o arquivo * LICENSE que é distribuído com este código-fonte. * Para obtener la información de los derechos de autor y la licencia debe leer * el archivo LICENSE que se distribuye con el código fuente. * For more information, see <https://opensource.gpupo.com/>. * */ use Symfony\Component\Dotenv\Dotenv; if (!class_exists('\Gpupo\Common\Console\Application')) { require __DIR__.'/../vendor/autoload.php'; } if (!class_exists(Dotenv::class)) { throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'); } // load all the .env files (new Dotenv(true))->loadEnv(dirname(__DIR__).'/.env');
<?php declare(strict_types=1); /* * This file is part of gpupo/common-schema * Created by Gilmar Pupo <contact@gpupo.com> * For the information of copyright and license you should read the file * LICENSE which is distributed with this source code. * Para a informação dos direitos autorais e de licença você deve ler o arquivo * LICENSE que é distribuído com este código-fonte. * Para obtener la información de los derechos de autor y la licencia debe leer * el archivo LICENSE que se distribuye con el código fuente. * For more information, see <https://opensource.gpupo.com/>. * */ use Symfony\Component\Dotenv\Dotenv; if (!class_exists('\Gpupo\Common\Console\Application')) { require __DIR__.'/../vendor/autoload.php'; } if (!class_exists(Dotenv::class)) { throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'); } // load all the .env files (new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
Set max_len default to 200 when making glue datasets
import argparse import os import dill from metal.mmtl.glue.glue_datasets import get_glue_dataset def make_datasets(task, bert_version): datasets = {} for split in ["train", "dev", "test"]: datasets[split] = get_glue_dataset( task, split, bert_version, max_len=200, run_spacy=True ) return datasets def pickle_datasets(datasets, task, bert_version): bert_str = bert_version.replace("-", "_") filename = f"{task}_{bert_str}_spacy_datasets" filepath = f"{os.environ['GLUEDATA']}/datasets/{filename}.dill" with open(filepath, "wb") as f: dill.dump(datasets, f) return True if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--task", type=str) parser.add_argument("--bert_version", type=str, default="bert-base-uncased") args = parser.parse_args() assert args.task.isupper() datasets = make_datasets(args.task, args.bert_version) if pickle_datasets(datasets, args.task, args.bert_version): print(f"FINISHED: {args.task}") else: print(f"FAILED: {args.task}")
import argparse import os import dill from metal.mmtl.glue.glue_datasets import get_glue_dataset def make_datasets(task, bert_version): datasets = {} for split in ["train", "dev", "test"]: datasets[split] = get_glue_dataset(task, split, bert_version, run_spacy=True) return datasets def pickle_datasets(datasets, task, bert_version): bert_str = bert_version.replace("-", "_") filename = f"{task}_{bert_str}_spacy_datasets" filepath = f"{os.environ['GLUEDATA']}/datasets/{filename}.dill" with open(filepath, "wb") as f: dill.dump(datasets, f) return True if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--task", type=str) parser.add_argument("--bert_version", type=str, default="bert-base-uncased") args = parser.parse_args() assert args.task.isupper() datasets = make_datasets(args.task, args.bert_version) if pickle_datasets(datasets, args.task, args.bert_version): print(f"FINISHED: {args.task}") else: print(f"FAILED: {args.task}")
Check if tab’s url is defined before hibernating
var performCommand = function(event) { if(event.command === 'hibernateTabs') { var c = 0; var xmlHttp = new XMLHttpRequest(); xmlHttp.open('GET', safari.extension.baseURI + 'lib/hibernationPage/index.html', true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState === 4) { var html = xmlHttp.responseText; _.each(safari.application.browserWindows, function(win) { _.each(win.tabs, function(tab) { if(typeof tab.url !== 'undefined') { if(tab === win.activeTab) return; if(!tab.url.match(/^https?:\/\//)) return; _.delay(function() { var pageInfo = { url: tab.url, title: tab.title }; var pageHtml = html.replace(/\{\/\*pageInfoObject\*\/\}/, JSON.stringify(pageInfo)); var dataURL = 'data:text/html;charset=utf-8,' + encodeURIComponent(pageHtml); tab.url = dataURL; }, c * 100); c++; } }); }); } }; xmlHttp.send(null); } }; safari.application.addEventListener('command', performCommand, false);
var performCommand = function(event) { if(event.command === 'hibernateTabs') { var c = 0; var xmlHttp = new XMLHttpRequest(); xmlHttp.open('GET', safari.extension.baseURI + 'lib/hibernationPage/index.html', true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState === 4) { var html = xmlHttp.responseText; _.each(safari.application.browserWindows, function(win) { _.each(win.tabs, function(tab) { if(tab === win.activeTab) return; if(!tab.url.match(/^https?:\/\//)) return; _.delay(function() { var pageInfo = { url: tab.url, title: tab.title }; var pageHtml = html.replace(/\{\/\*pageInfoObject\*\/\}/, JSON.stringify(pageInfo)); var dataURL = 'data:text/html;charset=utf-8,' + encodeURIComponent(pageHtml); tab.url = dataURL; }, c * 100); c++; }); }); } }; xmlHttp.send(null); } }; safari.application.addEventListener('command', performCommand, false);
Add name_en field due to 'not null' constraint on the Category table
import os from app import create_app, db from app.models import User, Category from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) #pylint: disable-msg=E1101 @manager.command def adduser(email, username, admin=False): """ Register a new user""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit("Error: Passwords do not match!") db.create_all() category = Category.get_by_name('Almenn frétt') if category is None: category = Category(name='Almenn frétt', name_en='General News', active=True) db.session.add(category) user = User(email=email, username=username, password=password, is_admin=admin) db.session.add(user) db.session.commit() print('User {0} was registered successfully!'.format(username)) if __name__ == '__main__': manager.run()
import os from app import create_app, db from app.models import User, Category from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) #pylint: disable-msg=E1101 @manager.command def adduser(email, username, admin=False): """ Register a new user""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit("Error: Passwords do not match!") db.create_all() category = Category.get_by_name('Almenn frétt') if category is None: category = Category(name='Almenn frétt', active=True) db.session.add(category) user = User(email=email, username=username, password=password, is_admin=admin) db.session.add(user) db.session.commit() print('User {0} was registered successfully!'.format(username)) if __name__ == '__main__': manager.run()
Fix AlertActions test's handling of async functions The problem was that submitNeedHelpAlert returns immediately, after initiating a promise but without returning that promise. So the 'then' callback was being run before the actual promise had resolved.
import '../testHelper'; import AlertActions from '../../app/assets/javascripts/actions/alert_actions.js'; import AlertsStore from '../../app/assets/javascripts/stores/alerts_store.js'; import sinon from 'sinon'; describe('AlertActions', () => { beforeEach(() => { sinon.stub($, "ajax").yieldsTo("success", { success: true }); }); afterEach(() => { $.ajax.restore(); AlertActions.resetNeedHelpAlert(); }); it('.submitNeedHelpAlert sets getNeedHelpAlertSubmitting to true', (done) => { AlertActions.submitNeedHelpAlert({}).then(() => { expect(AlertsStore.getNeedHelpAlertSubmitting()).to.be.true; done(); }); }); it('.createNeedHelpAlert sets getNeedHelpAlertSubmitted to true', (done) => { AlertActions.createNeedHelpAlert({}).then(() => { expect(AlertsStore.getNeedHelpAlertSubmitted()).to.be.true; done(); }); }); });
import '../testHelper'; import AlertActions from '../../app/assets/javascripts/actions/alert_actions.js'; import AlertsStore from '../../app/assets/javascripts/stores/alerts_store.js'; import sinon from 'sinon'; describe('AlertActions', () => { beforeEach(() => { sinon.stub($, 'ajax').yieldsTo('success', { success: true }); }); afterEach(() => { $.ajax.restore(); }); it('makes an ajax call for submitNeedHelpAlert', () => { AlertActions.submitNeedHelpAlert({}).then(() => { expect(AlertsStore.getNeedHelpAlertSubmitted()).to.be.true; }); expect($.ajax.calledOnce).to.be.true; AlertActions.resetNeedHelpAlert().then(() => { expect(AlertsStore.getNeedHelpAlertSubmitted()).to.be.false; expect(AlertsStore.getNeedHelpAlertSubmitting()).to.be.false; }); }); });
Check that GreatestCommonDivisor handles large numbers
package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } @Test public void acceptsNegativeSecondArgument() { assertThat(GreatestCommonDivisor.of(6, -4), is(2)); } @Test public void acceptsBothArgumentsNegative() { assertThat(GreatestCommonDivisor.of(-6, -4), is(-2)); } @Test public void canComputeGreatestCommonDivisorOfLargeArguments() { assertThat(GreatestCommonDivisor.of(1071, 462), is(21)); } }
package se.ericthelin.fractions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class GreatestCommonDivisorTest { @Test public void returnsFirstWhenSecondIsZero() { assertThat(GreatestCommonDivisor.of(6, 0), is(6)); } @Test public void returnsSecondWhenFirstIsZero() { assertThat(GreatestCommonDivisor.of(0, 4), is(4)); } @Test public void returnsGreatestCommonDivisorOfFirstAndSecond() { assertThat(GreatestCommonDivisor.of(6, 4), is(2)); } @Test public void acceptsArgumentsInReverseOrder() { assertThat(GreatestCommonDivisor.of(4, 6), is(2)); } @Test public void acceptsNegativeFirstArgument() { assertThat(GreatestCommonDivisor.of(-6, 4), is(-2)); } @Test public void acceptsNegativeSecondArgument() { assertThat(GreatestCommonDivisor.of(6, -4), is(2)); } @Test public void acceptsBothArgumentsNegative() { assertThat(GreatestCommonDivisor.of(-6, -4), is(-2)); } }
[test] Add jsdom init prop to global
// Global configuration uese for tests. require('babel/register')({ optional: ['runtime', 'es7.asyncFunctions'] }); const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); const chaiSubset = require('chai-subset'); chai.use(chaiSubset); chai.use(sinonChai); const React = require('react'); // Globals global.React = React; global.expect = chai.expect; global.sinon = sinon; global.TestUtils = require('react-addons-test-utils'); // Js dom import jsdom from 'jsdom'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = document.defaultView; // take all properties of the window object and also attach it to the // from mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80 function propagateToGlobal (window) { for (const key in window) { if (!window.hasOwnProperty(key)) {continue; } if (key in global) {continue; } global[key] = window[key]; } } // mocha global object propagateToGlobal(window); process.on('unhandledRejection', (error)=>{ console.error('Unhandled Promise Rejection:'); console.error(error && error.stack || error); });
// Global configuration uese for tests. require('babel/register')({ optional: ['runtime', 'es7.asyncFunctions'] }); const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); const chaiSubset = require('chai-subset'); chai.use(chaiSubset); chai.use(sinonChai); const React = require('react/addons'); // Globals global.React = React; global.expect = chai.expect; global.sinon = sinon; global.TestUtils = React.addons.TestUtils; // Js dom import jsdom from 'jsdom'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = document.defaultView; process.on('unhandledRejection', (error)=>{ console.error('Unhandled Promise Rejection:'); console.error(error && error.stack || error); });
Make sure rollbar is setup correctly
package main import ( "os" "github.com/albertyw/reaction-pics/server" "github.com/joho/godotenv" newrelic "github.com/newrelic/go-agent" "github.com/rollbar/rollbar-go" ) func setupEnv() { err := godotenv.Load() if err != nil { panic(err) } } func getNewRelicApp() newrelic.Application { newrelicKey := os.Getenv("NEWRELIC_KEY") config := newrelic.NewConfig("Reaction.pics", newrelicKey) app, err := newrelic.NewApplication(config) if err != nil { panic(err) } return app } func setupRollbar() { rollbar.SetToken(os.Getenv("ROLLBAR_SERVER_TOKEN")) rollbar.SetEnvironment(os.Getenv("ENVIRONMENT")) } func main() { setupEnv() setupRollbar() newrelicApp := getNewRelicApp() server.Run(newrelicApp) }
package main import ( "os" "github.com/albertyw/reaction-pics/server" "github.com/joho/godotenv" newrelic "github.com/newrelic/go-agent" "github.com/rollbar/rollbar-go" ) func setupEnv() { err := godotenv.Load() if err != nil { panic(err) } } func getNewRelicApp() newrelic.Application { newrelicKey := os.Getenv("NEWRELIC_KEY") config := newrelic.NewConfig("Reaction.pics", newrelicKey) app, err := newrelic.NewApplication(config) if err != nil { panic(err) } return app } func setupRollbar() { rollbar.SetToken(os.Getenv("ROLLBAR_SERVER_TOKEN")) rollbar.SetEnvironment(os.Getenv("ENVIRONMENT")) } func main() { setupEnv() newrelicApp := getNewRelicApp() server.Run(newrelicApp) }
Change karma log lvl to WARN
const browsers = ['Firefox']; if (!process.env.CI) { browsers.push('Chrome'); switch (process.platform) { case 'darwin': browsers.push('Safari'); break; case 'win32': browsers.push('IE'); browsers.push('Edge'); break; } } module.exports = (config) => { config.set({ basePath: '../', frameworks: ['mocha', 'chai'], files: [ 'dist/browser-id3-writer.min.js', 'test/common.js', 'test/browser.js', { pattern: 'test/assets/song.mp3', included: false, served: true } ], reporters: ['dots'], browsers: browsers, singleRun: true, logLevel: config.LOG_WARN }); };
const browsers = ['Firefox']; if (!process.env.CI) { browsers.push('Chrome'); switch (process.platform) { case 'darwin': browsers.push('Safari'); break; case 'win32': browsers.push('IE'); browsers.push('Edge'); break; } } module.exports = (config) => { config.set({ basePath: '../', frameworks: ['mocha', 'chai'], files: [ 'dist/browser-id3-writer.min.js', 'test/common.js', 'test/browser.js', { pattern: 'test/assets/song.mp3', included: false, served: true } ], reporters: ['dots'], browsers: browsers, singleRun: true }); };
Fix description content type for PyPi
""" The setup package to install MasterQA requirements """ from setuptools import setup, find_packages # noqa from os import path this_directory = path.abspath(path.dirname(__file__)) long_description = None try: with open(path.join(this_directory, 'README.md'), 'rb') as f: long_description = f.read().decode('utf-8') except IOError: long_description = ( 'Automation-Assisted Manual Testing - http://masterqa.com') setup( name='masterqa', version='1.1.5', description='Automation-Assisted Manual Testing - http://masterqa.com', long_description=long_description, long_description_content_type='text/markdown', platforms='Mac * Windows * Linux', url='http://masterqa.com', author='Michael Mintz', author_email='mdmintz@gmail.com', maintainer='Michael Mintz', license='The MIT License', install_requires=[ 'seleniumbase', ], packages=['masterqa'], entry_points={ 'nose.plugins': [] } )
""" The setup package to install MasterQA requirements """ from setuptools import setup, find_packages # noqa from os import path this_directory = path.abspath(path.dirname(__file__)) long_description = None try: with open(path.join(this_directory, 'README.md'), 'rb') as f: long_description = f.read().decode('utf-8') except IOError: long_description = ( 'Automation-Assisted Manual Testing - http://masterqa.com') setup( name='masterqa', version='1.1.5', description='Automation-Assisted Manual Testing - http://masterqa.com', long_description=long_description, platforms='Mac * Windows * Linux', url='http://masterqa.com', author='Michael Mintz', author_email='mdmintz@gmail.com', maintainer='Michael Mintz', license='The MIT License', install_requires=[ 'seleniumbase', ], packages=['masterqa'], entry_points={ 'nose.plugins': [] } )
Allow passing `onlyDirection` as falsy value Currently the default option for `onlyDirection` (false) causes a warning to be raised if no value is explicitly passed. This occurs after the second import as the `options` get mutated in the `index.js` export: `options = validateOptions(options)`
const defaultOptions = { addPrefixToSelector: false, // customized function for joining prefix and selector prefixType: 'attribute', // type of dir-prefix: attribute [dir] or class .dir, onlyDirection: false // "ltr", "rtl": compile only one-direction version } const validateOptions = (options = {}) => { const {addPrefixToSelector, prefixType, onlyDirection} = options let fixedOptions = {} if (addPrefixToSelector && typeof addPrefixToSelector !== 'function') { fixedOptions.addPrefixToSelector = defaultOptions.addPrefixToSelector console.warn('Incorrect **addPrefixToSelector option. Must be a function') } if (onlyDirection && typeof onlyDirection !== 'string') { fixedOptions.onlyDirection = defaultOptions.onlyDirection console.warn('Incorrect onlyDirection option. Allowed values: ltr, rtl') } if (prefixType && ['attribute', 'class'].indexOf(prefixType) < 0) { fixedOptions.prefixType = defaultOptions.prefixType console.warn('Incorrect prefixType option. Allowed values: attribute, class') } return Object.assign({}, defaultOptions, options, fixedOptions ) } module.exports = { validateOptions }
const defaultOptions = { addPrefixToSelector: false, // customized function for joining prefix and selector prefixType: 'attribute', // type of dir-prefix: attribute [dir] or class .dir, onlyDirection: false // "ltr", "rtl": compile only one-direction version } const validateOptions = (options = {}) => { const {addPrefixToSelector, prefixType, onlyDirection} = options let fixedOptions = {} if (addPrefixToSelector && typeof addPrefixToSelector !== 'function') { fixedOptions.addPrefixToSelector = defaultOptions.addPrefixToSelector console.warn('Incorrect **addPrefixToSelector option. Must be a function') } if (onlyDirection !== undefined && typeof onlyDirection !== 'string') { fixedOptions.onlyDirection = defaultOptions.onlyDirection console.warn('Incorrect onlyDirection option. Allowed values: ltr, rtl') } if (prefixType && ['attribute', 'class'].indexOf(prefixType) < 0) { fixedOptions.prefixType = defaultOptions.prefixType console.warn('Incorrect prefixType option. Allowed values: attribute, class') } return Object.assign({}, defaultOptions, options, fixedOptions ) } module.exports = { validateOptions }
Test finding usernames in database
const test = require('tape'); const User = require('../../../models/User'); const { connect, add, remove, findUser } = require('../../database'); test('connection to database', async (assert) => { const actual = await connect(); const expected = 0; assert.equal(actual, expected, 'It should connect to the database without errors'); assert.end(); }); test('adding to database', async (assert) => { const actual = await add(User, 'sample', 'secret'); const expected = 0; await remove(User, 'sample'); assert.equal(actual, expected, 'It should add documents to the database without errors'); assert.end(); }); test('adding duplicates to database', async (assert) => { await add(User, 'sample', 'secret'); const actual = await add(User, 'sample', 'secret'); const expected = 2; await remove(User, 'sample'); assert.equal(actual, expected, 'It should not add duplicate documents to the database'); assert.end(); }); test('finding usernames in database', async (assert) => { await add(User, 'sample', 'secret'); const actual = await findUser(User, 'sample'); const expected = 1; await remove(User, 'sample'); assert.equal(actual, expected, 'It should tell if the user exists in the database without errors'); assert.end(); });
const test = require('tape'); const User = require('../../../models/User'); const { connect, add, remove } = require('../../database'); test('connection to database', async (assert) => { const actual = await connect(); const expected = 0; assert.equal(actual, expected, 'It should connect to the database without errors'); assert.end(); }); test('adding to database', async (assert) => { const actual = await add(User, 'sample', 'secret'); const expected = 0; await remove(User, 'sample'); assert.equal(actual, expected, 'It should add documents to the database without errors'); assert.end(); }); test('adding duplicates to database', async (assert) => { await add(User, 'sample', 'secret'); const actual = await add(User, 'sample', 'secret'); const expected = 2; await remove(User, 'sample'); assert.equal(actual, expected, 'It should not add duplicate documents to the database'); assert.end(); });
Update encoding test to work with new interface.
package pd1_test import ( // "math/rand" "fmt" "reflect" "testing" "time" "github.com/influxdb/influxdb/tsdb/engine/pd1" ) func TestEncoding_FloatBlock(t *testing.T) { valueCount := 1000 times := getTimes(valueCount, 60, time.Second) values := make(pd1.Values, len(times)) for i, t := range times { values[i] = pd1.NewValue(t, float64(i)) } b := values.Encode(nil) fmt.Println("**** ", len(b)) decodedValues := values.DecodeSameTypeBlock(b) if !reflect.DeepEqual(decodedValues, values) { t.Fatalf("unexpected results:\n\tgot: %v\n\texp: %v\n", decodedValues, values) } } func getTimes(n, step int, precision time.Duration) []time.Time { t := time.Now().Round(precision) a := make([]time.Time, n) for i := 0; i < n; i++ { a[i] = t.Add(60 * precision) } return a }
package pd1_test import ( // "math/rand" // "reflect" "testing" "time" // "github.com/influxdb/influxdb/tsdb/engine/pd1" ) func TestEncoding_FloatBlock(t *testing.T) { // valueCount := 100 // times := getTimes(valueCount, 60, time.Second) // values := make([]Value, len(times)) // for i, t := range times { // values[i] = pd1.NewValue(t, rand.Float64()) // } // b := pd1.EncodeFloatBlock(nil, values) // decodedValues, err := pd1.DecodeFloatBlock(b) // if err != nil { // t.Fatalf("error decoding: %s", err.Error) // } // if !reflect.DeepEqual(decodedValues, values) { // t.Fatalf("unexpected results:\n\tgot: %v\n\texp: %v\n", decodedValues, values) // } } func getTimes(n, step int, precision time.Duration) []time.Time { t := time.Now().Round(precision) a := make([]time.Time, n) for i := 0; i < n; i++ { a[i] = t.Add(60 * precision) } return a }
Throw ConfigurationException on urlparse exception
package org.yamcs.api.ws; import java.net.URI; import java.net.URISyntaxException; import org.yamcs.ConfigurationException; public class YamcsConnectionProperties { private String host; private int port; private String instance; public YamcsConnectionProperties(String host, int port, String instance) { this.host = host; this.port = port; this.instance = instance; } public URI webResourceURI(String relativePath) { if (!relativePath.startsWith("/")) { relativePath = "/" + relativePath; } try { return new URI("http://" + host + ":" + port + "/" + instance + relativePath); } catch (URISyntaxException e) { throw new ConfigurationException("Invalid URL", e); } } public URI webSocketURI() { try { return new URI("ws://" + host + ":" + port + "/" + instance + "/_websocket"); } catch (URISyntaxException e) { throw new ConfigurationException("Invalid URL", e); } } }
package org.yamcs.api.ws; import java.net.URI; import java.net.URISyntaxException; public class YamcsConnectionProperties { private String host; private int port; private String instance; public YamcsConnectionProperties(String host, int port, String instance) { this.host = host; this.port = port; this.instance = instance; } public URI webResourceURI(String relativePath) { if (!relativePath.startsWith("/")) { relativePath = "/" + relativePath; } try { return new URI("http://" + host + ":" + port + "/" + instance + relativePath); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public URI webSocketURI() { try { return new URI("ws://" + host + ":" + port + "/" + instance + "/_websocket"); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }
Remove the identifier parameter in the object constructor.
package org.obda.query.domain.imp; import java.net.URI; import org.obda.query.domain.Predicate; public class PredicateImp implements Predicate{ private int arity = -1; private URI name = null; private int identfier = -1; protected PredicateImp (URI name, int arity){ this.name = name; this.identfier = name.toString().hashCode(); this.arity = arity; } public void setName(URI name) { this.name = name; } @Override public int getArity() { return arity; } @Override public URI getName() { return name; } @Override public boolean equals(Object obj) { if (obj == null|| !(obj instanceof PredicateImp)) return false; PredicateImp pred2 = (PredicateImp) obj; if (pred2.arity != arity) return false; return this.identfier == pred2.identfier; } @Override public int hashCode(){ return identfier; } @Override public Predicate copy() { return new PredicateImp(this.name, this.arity); } @Override public String toString() { return getName().toString(); } }
package org.obda.query.domain.imp; import java.net.URI; import org.obda.query.domain.Predicate; public class PredicateImp implements Predicate{ private int arity = -1; private URI name = null; private int identfier = -1; //TODO PredicateImp remove identifier protected PredicateImp (URI name, int identifier, int arity){ this.name = name; this.identfier = name.toString().hashCode(); this.arity = arity; } public int getArity() { return arity; } public URI getName() { return name; } public void setName(URI name) { this.name = name; } @Override public boolean equals(Object obj){ if(obj == null|| !(obj instanceof PredicateImp)){ return false; }else{ PredicateImp pred2 =(PredicateImp)obj; if (pred2.arity != arity) return false; return this.identfier == pred2.identfier; } } @Override public int hashCode(){ return identfier; } public Predicate copy() { return new PredicateImp(this.name, this.identfier, this.arity); } public String toString() { return this.name.toString(); } }
Remove returned pile b/c mutating directly
from collections import deque def isVerticallyStackable(pile): vertical_stack = [] while pile: largest_cube = remove_largest_cube_from_pile(pile) if vertical_stack == []: vertical_stack.append(largest_cube) else: top_of_stack = vertical_stack[-1] if(top_of_stack < largest_cube): return False vertical_stack.append(largest_cube) return True def remove_largest_cube_from_pile(cube_sizes): if(cube_sizes == []): return None elif(cube_sizes[0] > cube_sizes[-1]): return cube_sizes.popleft() else: return cube_sizes.pop() num_test_cases = int(input()) for i in range(num_test_cases): num_cubes = int(input()) pile = deque(map(int, input().strip().split(" "))) if(isVerticallyStackable(pile)): print("Yes") else: print("No")
from collections import deque def isVerticallyStackable(pile): vertical_stack = [] while pile: largest_cube, cube_sizes = remove_largest_cube_from_pile(pile) if vertical_stack == []: vertical_stack.append(largest_cube) else: top_of_stack = vertical_stack[-1] if(top_of_stack < largest_cube): return False vertical_stack.append(largest_cube) return True def remove_largest_cube_from_pile(cube_sizes): if(cube_sizes == []): return (None, cube_sizes) elif(cube_sizes[0] > cube_sizes[-1]): largest_cube = cube_sizes.popleft() return (largest_cube, cube_sizes) else: largest_cube = cube_sizes.pop() return (largest_cube, cube_sizes) num_test_cases = int(input()) for i in range(num_test_cases): num_cubes = int(input()) pile = deque(map(int, input().strip().split(" "))) if(isVerticallyStackable(pile)): print("Yes") else: print("No")
Fix compatibility with latest stable glue version
import operator import numpy as np from glue.qt import get_qapp from glue.core.data import Data from glue.core.data_collection import DataCollection try: from glue.app.qt.application import GlueApplication except: from glue.qt.glue_application import GlueApplication from glue.core.subset import InequalitySubsetState # from glue.core.tests.util import simple_session from ..vol_glue_viewer import GlueVispyViewer def test_viewer(): app = get_qapp() data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.) dc = DataCollection([data]) app = GlueApplication(dc) app.new_data_viewer(GlueVispyViewer, data=data) subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt) dc.new_subset_group(label='test_subset1', subset_state=subset_state1) subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt) dc.new_subset_group(label='test_subset2', subset_state=subset_state2) app.show()
import operator import numpy as np from glue.qt import get_qapp from glue.core.data import Data from glue.core.data_collection import DataCollection from glue.app.qt.application import GlueApplication from glue.core.subset import InequalitySubsetState # from glue.core.tests.util import simple_session from ..vol_glue_viewer import GlueVispyViewer def test_viewer(): app = get_qapp() data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.) dc = DataCollection([data]) app = GlueApplication(dc) app.new_data_viewer(GlueVispyViewer, data=data) subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt) dc.new_subset_group(label='test_subset1', subset_state=subset_state1) subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt) dc.new_subset_group(label='test_subset2', subset_state=subset_state2) app.show()
Use to make GET request
'use strict'; /* Controllers */ angular.module('myApp.controllers', []). controller('AppCtrl', function($scope, $http) { $scope.website = {url: ''}; $scope.check = function() { var url = $scope.website.url; if (url !== "") { $scope.makeRequest(url); } } $scope.makeRequest = function(url) { $http({method: 'GET', url: "/?url=" +encodeURIComponent(url)}). success(function(data, status, headers, config) { console.log(status); console.log(data); }). error(function(data, status, headers, config) { console.log(status); }); } });
'use strict'; /* Controllers */ angular.module('myApp.controllers', []). controller('AppCtrl', function($scope) { $scope.website = {url: ''}; $scope.check = function() { var url = $scope.website.url; if (url !== "") { $scope.makeRequest(url, $scope.handleRequest); } } $scope.handleRequest = function(code, body) { writeTitle(); if (code === 200) { writeMessage(body.message); } else { writeError(body.error); } } $scope.makeRequest = function(url, cb) { console.log(url); var http = new XMLHttpRequest(); console.log(encodeURIComponent(url)) http.open("GET", "/?url=" + encodeURIComponent(url), true); http.onreadystatechange = function() { if (http.readyState == 4) { console.log(http.responseText) cb(http.status, JSON.parse(http.responseText)); } }; http.send(null); } });
Disable import/export of cell output.
export default { type: 'cell', tagName: 'div', matchElement: function (el) { return el.is('div[data-cell]') }, import: function (el, node) { const language = el.attr('data-language') if (language) { node.language = language } node.expression = el.attr('data-cell') let sourceCodeEl = el.find('pre[data-source]') if (sourceCodeEl) { node.sourceCode = sourceCodeEl.textContent } // TODO: discuss how we want to do this now: // let outputEl = el.find('pre[data-output]') // if (outputEl) { // node.value = JSON.parseoutputEl.textContent // } }, // TODO: This code has not yet been tested export: function (node, el, converter) { let $$ = converter.$$ el.attr('data-cell', node.expression) if (node.sourceCode) { el.attr('data-language', node.language) el.append( $$('pre').attr('data-source', '').text(node.sourceCode) ) } // TODO: discuss how we want to do this now: // to render in the same way as we do it in CellValueComponent // el.append( // $$('pre').attr('data-output', '').text(node.value) // ) } }
export default { type: 'cell', tagName: 'div', matchElement: function (el) { return el.is('div[data-cell]') }, import: function (el, node) { const language = el.attr('data-language') if (language) { node.language = language } node.expression = el.attr('data-cell') let sourceCodeEl = el.find('pre[data-source]') if (sourceCodeEl) { node.sourceCode = sourceCodeEl.textContent } let outputEl = el.find('pre[data-output]') if (outputEl) { node.value = outputEl.innerHTML } }, // TODO: This code has not yet been tested export: function (node, el, converter) { let $$ = converter.$$ el.attr('data-cell', node.expression) if (node.sourceCode) { el.attr('data-language', node.language) el.append( $$('pre').attr('data-source', '').text(node.sourceCode) ) } el.append( $$('pre').attr('data-output', '').text(node.value) ) } }
Make aggregation script compatible with python 3
#!/usr/bin/env python from csv import reader with open("data/public/labos.departements.csv") as f: data = list(reader(f)) output = {} keys = data.pop(0) keys.remove("LABO") keys.remove("DEPARTEMENT") for row in data: if not row[0]: continue if row[0] not in output: output[row[0]] = dict({k: 0 for k in keys}) for i, k in enumerate(keys): output[row[0]][k] += float(row[2+i]) if row[2+i] else 0 print("LABO,"+",".join(keys)) for labo in sorted(output.keys(), key=lambda x: -output[x]["MONTANT AVANTAGES"]): print(labo+","+",".join([str(output[labo][k]) for k in keys]))
#!/usr/bin/env python from csv import reader with open("data/public/labos.departements.csv") as f: data = list(reader(f)) output = {} keys = data.pop(0) keys.remove("LABO") keys.remove("DEPARTEMENT") for row in data: if not row[0]: continue if row[0] not in output: output[row[0]] = dict({k: 0 for k in keys}) for i, k in enumerate(keys): output[row[0]][k] += float(row[2+i]) if row[2+i] else 0 print "LABO,"+",".join(keys) for labo in sorted(output.keys(), key=lambda x: -output[x]["MONTANT AVANTAGES"]): print labo+","+",".join([str(output[labo][k]) for k in keys])
Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
from django.db import models class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration): try: return cls.objects.get(app_name=migration.app_label(), migration=migration.name()) except cls.DoesNotExist: return cls(app_name=migration.app_label(), migration=migration.name()) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration)
from django.db import models class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) class Meta: unique_together = (('app_name', 'migration'),) @classmethod def for_migration(cls, migration): try: return cls.objects.get(app_name=migration.app_label(), migration=migration.name()) except cls.DoesNotExist: return cls(app_name=migration.app_label(), migration=migration.name()) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration)
Use log to show messages, not System out.
package org.dummy.load; import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger; /** * Created by baardl on 26.07.15. */ public class LoadThread implements Runnable { private static final Logger log = getLogger(LoadThread.class); private final int sleepMillis; public LoadThread(int sleepMillis) { this.sleepMillis = sleepMillis; } @Override public void run() { do { performVisibleLoad(); try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { //sleep interupted } } while (true); } public void performVisibleLoad() { log.trace("Hello You at " + System.currentTimeMillis()); } }
package org.dummy.load; /** * Created by baardl on 26.07.15. */ public class LoadThread implements Runnable { private final int sleepMillis; public LoadThread(int sleepMillis) { this.sleepMillis = sleepMillis; } @Override public void run() { do { performVisibleLoad(); try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { //sleep interupted } } while (true); } public void performVisibleLoad() { System.out.println("Hello You at " + System.currentTimeMillis()); } }
Replace method of struct with function.
package markdown import ( "io/ioutil" "path" "strings" "testing" ) func TestParse(t *testing.T) { files, _ := ioutil.ReadDir("./data") for _, f := range files { fileName := f.Name() filePath := path.Join("./data/", fileName) fileExt := path.Ext(filePath) if ".md" != fileExt { continue } markdown, _ := ioutil.ReadFile(filePath) input := string(markdown) basename := strings.Replace(fileName, fileExt, "", 1) htmlPath := strings.Join([]string{"./data/", basename, ".html"}, "") html, _ := ioutil.ReadFile(htmlPath) expected := string(html) result := parse(input) if result != expected { t.Errorf("'%s' expected but was '%s'.", expected, result) } } }
package markdown import ( "io/ioutil" "path" "strings" "testing" ) func TestParse(t *testing.T) { m := new(Markdown) files, _ := ioutil.ReadDir("./data") for _, f := range files { fileName := f.Name() filePath := path.Join("./data/", fileName) fileExt := path.Ext(filePath) if ".md" != fileExt { continue } markdown, _ := ioutil.ReadFile(filePath) input := string(markdown) basename := strings.Replace(fileName, fileExt, "", 1) htmlPath := strings.Join([]string{"./data/", basename, ".html"}, "") html, _ := ioutil.ReadFile(htmlPath) expected := string(html) result := m.parse(input) if result != expected { t.Errorf("'%s' expected but was '%s'.", expected, result) } } }
Add missing return types to scope factory methods
""" byceps.services.snippet.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from enum import Enum from typing import NewType from uuid import UUID from attr import attrib, attrs from ...site.transfer.models import SiteID from ....typing import BrandID @attrs(frozen=True, slots=True) class Scope: type_ = attrib(type=str) name = attrib(type=str) @classmethod def for_brand(cls, brand_id: BrandID) -> 'Scope': return cls('brand', str(brand_id)) @classmethod def for_site(cls, site_id: SiteID) -> 'Scope': return cls('site', str(site_id)) SnippetID = NewType('SnippetID', UUID) SnippetType = Enum('SnippetType', ['document', 'fragment']) SnippetVersionID = NewType('SnippetVersionID', UUID) MountpointID = NewType('MountpointID', UUID)
""" byceps.services.snippet.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from enum import Enum from typing import NewType from uuid import UUID from attr import attrib, attrs from ...site.transfer.models import SiteID from ....typing import BrandID @attrs(frozen=True, slots=True) class Scope: type_ = attrib(type=str) name = attrib(type=str) @classmethod def for_brand(cls, brand_id: BrandID): return cls('brand', str(brand_id)) @classmethod def for_site(cls, site_id: SiteID): return cls('site', str(site_id)) SnippetID = NewType('SnippetID', UUID) SnippetType = Enum('SnippetType', ['document', 'fragment']) SnippetVersionID = NewType('SnippetVersionID', UUID) MountpointID = NewType('MountpointID', UUID)
Update storage strategies to inclue new atomicSet and atomicSetArray
<?php namespace CImrie\ODM\Mapping\Traits; trait StorageStrategies { public function useAddToSetStorageStrategy() { $this->useStorageStrategy('addToSet'); return $this; } public function usePushAllStorageStrategy() { $this->useStorageStrategy('pushAll'); return $this; } public function useSetStorageStrategy() { $this->useStorageStrategy('set'); return $this; } public function useSetArrayStorageStrategy() { $this->useStorageStrategy('setArray'); return $this; } public function useAtomicSetStorageStrategy() { $this->useStorageStrategy('atomicSet'); return $this; } public function useAtomicSetArrayStorageStrategy() { $this->useStorageStrategy('atomicSetArray'); return $this; } protected function useStorageStrategy($strategy) { $this->mapping['strategy'] = $strategy; return $this; } }
<?php namespace CImrie\ODM\Mapping\Traits; trait StorageStrategies { public function useAddToSetStorageStrategy() { $this->useStorageStrategy('addToSet'); return $this; } public function usePushAllStorageStrategy() { $this->useStorageStrategy('pushAll'); return $this; } public function useSetStorageStrategy() { $this->useStorageStrategy('set'); return $this; } public function useSetArrayStorageStrategy() { $this->useStorageStrategy('setArray'); return $this; } protected function useStorageStrategy($strategy) { $this->mapping['strategy'] = $strategy; return $this; } }
Use strict with single quote
/*global define*/ define([ '../Scene/decompressOpen3DGC', './createTaskProcessorWorker' ], function( decompressOpen3DGC, createTaskProcessorWorker) { 'use strict'; function decompressOpen3DGCWorker(parameters, transferableObjects) { var decompressedByteLength = parameters.decompressedByteLength; var compressedBuffer = parameters.compressedBuffer; var decompressedArrayBuffer = decompressOpen3DGC(decompressedByteLength, compressedBuffer); transferableObjects.push(decompressedArrayBuffer); return { decompressedArrayBuffer : decompressedArrayBuffer }; } return createTaskProcessorWorker(decompressOpen3DGCWorker); });
/*global define*/ define([ '../Scene/decompressOpen3DGC', './createTaskProcessorWorker' ], function( decompressOpen3DGC, createTaskProcessorWorker) { "use strict"; function decompressOpen3DGCWorker(parameters, transferableObjects) { var decompressedByteLength = parameters.decompressedByteLength; var compressedBuffer = parameters.compressedBuffer; var decompressedArrayBuffer = decompressOpen3DGC(decompressedByteLength, compressedBuffer); transferableObjects.push(decompressedArrayBuffer); return { decompressedArrayBuffer : decompressedArrayBuffer }; } return createTaskProcessorWorker(decompressOpen3DGCWorker); });
Fix image download path, thanks @cmrn
#!/usr/bin/env python3 import requests from bs4 import BeautifulSoup from urllib.parse import urlparse import urllib.request import os def save_file(url, filename): if (os.path.exists(filename)): print(filename + ' already exists locally') pass urllib.request.urlretrieve(url, filename) def get_filename(url): relpath = urlparse(url).path return os.path.split(relpath)[-1] url = 'http://www.data.act.gov.au/resource/j746-krni.json' data = requests.get(url).json() filedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../govhack2014/static/art_images')) if not os.path.exists(filedir): os.makedirs(filedir) download_list = [] for item in data: title = item['title'] page = item['url_1']['url'] pic = item['url_2']['url'] filename = get_filename(pic) download_list.append({'title': title, 'page': page, 'file': filename}) for item in download_list: retry = requests.get(item['page']).text data = BeautifulSoup(retry) imageurl = data.find_all('div', {'id': 'artinfo'})[0].find_all('img')[0]['src'] save_file(imageurl, os.path.join(filedir, item['file']))
#!/usr/bin/env python3 import requests from bs4 import BeautifulSoup from urllib.parse import urlparse import urllib.request import os def save_file(url, filename): if (os.path.exists(filename)): print(filename + ' already exists locally') pass urllib.request.urlretrieve(url, filename) def get_filename(url): relpath = urlparse(url).path return os.path.split(relpath)[-1] url = 'http://www.data.act.gov.au/resource/j746-krni.json' data = requests.get(url).json() filedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/images')) if not os.path.exists(filedir): os.makedirs(filedir) download_list = [] for item in data: title = item['title'] page = item['url_1']['url'] pic = item['url_2']['url'] filename = get_filename(pic) download_list.append({'title': title, 'page': page, 'file': filename}) for item in download_list: retry = requests.get(item['page']).text data = BeautifulSoup(retry) imageurl = data.find_all('div', {'id': 'artinfo'})[0].find_all('img')[0]['src'] save_file(imageurl, os.path.join(filedir, item['file']))
Remove test_single_gene_deletion (renamed in cobra=0.4.0b1)
# Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU. # # 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 types from cobra.test import create_test_model from cobra.test.unit_tests import CobraTestCase, TestReactions from cobra.test.flux_analysis import TestCobraFluxAnalysis from cameo.core.solver_based_model import to_solver_based_model, SolverBasedModel def setUp(self): # Make Model pickable and then load a solver based version of test_pickle self.model = to_solver_based_model(create_test_model()) self.model_class = SolverBasedModel for cls in (CobraTestCase, TestReactions, TestCobraFluxAnalysis): cls.setUp = types.MethodType(setUp, cls) del TestCobraFluxAnalysis.test_single_gene_deletion
# Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU. # # 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 types from cobra.test import create_test_model from cobra.test.unit_tests import CobraTestCase, TestReactions from cobra.test.flux_analysis import TestCobraFluxAnalysis from cameo.core.solver_based_model import to_solver_based_model, SolverBasedModel def setUp(self): # Make Model pickable and then load a solver based version of test_pickle self.model = to_solver_based_model(create_test_model()) self.model_class = SolverBasedModel for cls in (CobraTestCase, TestReactions, TestCobraFluxAnalysis): cls.setUp = types.MethodType(setUp, cls) del TestCobraFluxAnalysis.test_single_deletion
Fix typo in method name
<?php /** * A singleton handle on the application configuration file. * * @author Saul Johnson * @since 09/07/2015 */ class Configuration { private static $instance; private $config; private function __construct($path) { $this->config = Spyc::YAMLLoad($path); } public function getRootPath() { return $this->config['root_path']; } public function getDeployConfigName() { return $this->config['deploy_config_name']; } public function getAdminEmail() { return $this->config['admin_email']; } public function getAdminPasswordHash() { return $this->config['admin_password_hash']; } public function getSecretKey() { return $this->config['secret_key']; } public static function get() { if (self::$instance == null) { self::$instance = new Configuration('config.yml'); } return self::$instance; } }
<?php /** * A singleton handle on the application configuration file. * * @author Saul Johnson * @since 09/07/2015 */ class Configuration { private static $instance; private $config; private function __construct($path) { $this->config = Spyc::YAMLLoad($path); } public function getRootPath() { return $this->config['root_path']; } public function getDeployonfigName() { return $this->config['deploy_config_name']; } public function getAdminEmail() { return $this->config['admin_email']; } public function getAdminPasswordHash() { return $this->config['admin_password_hash']; } public function getSecretKey() { return $this->config['secret_key']; } public static function get() { if (self::$instance == null) { self::$instance = new Configuration('config.yml'); } return self::$instance; } }
Use SortDir.DESCENDING for default sort direction Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
from girder.constants import SortDir def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', SortDir.DESCENDING)] return limit, offset, sort def parse_pagination_params(params): """Parse params and get (limit, offset, sort) The defaults will be returned if not found in params. """ # Defaults limit, offset, sort = default_pagination_params() if params: if 'limit' in params: limit = int(params['limit']) if 'offset' in params: offset = int(params['offset']) if 'sort' in params and 'sortdir' in params: sort = [(params['sort'], int(params['sortdir']))] return limit, offset, sort def search_results_dict(results, limit, offset, sort): """This is for consistent search results""" ret = { 'matches': len(results), 'limit': limit, 'offset': offset, 'results': results } return ret
def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', -1)] return limit, offset, sort def parse_pagination_params(params): """Parse params and get (limit, offset, sort) The defaults will be returned if not found in params. """ # Defaults limit, offset, sort = default_pagination_params() if params: if 'limit' in params: limit = int(params['limit']) if 'offset' in params: offset = int(params['offset']) if 'sort' in params and 'sortdir' in params: sort = [(params['sort'], int(params['sortdir']))] return limit, offset, sort def search_results_dict(results, limit, offset, sort): """This is for consistent search results""" ret = { 'matches': len(results), 'limit': limit, 'offset': offset, 'results': results } return ret
Adjust test to be specific to mbc-logging-processor
<?php use DoSomething\MBC_LoggingGateway\MBC_LoggingGateway; // Including that file will also return the autoloader instance, so you can store // the return value of the include call in a variable and add more namespaces. // This can be useful for autoloading classes in a test suite, for example. // https://getcomposer.org/doc/01-basic-usage.md $loader = require_once __DIR__ . '/../vendor/autoload.php'; class MBC_LoggingProcessoryTest extends PHPUnit_Framework_TestCase { public function setUp(){ } public function tearDown(){ } public function testProcessLoggedEvents() { date_default_timezone_set('America/New_York'); // Load Message Broker settings used mb mbp-user-import.php define('CONFIG_PATH', __DIR__ . '/../messagebroker-config'); require_once __DIR__ . '/../mbc-logging-processor.config.inc'; // Create MBP_UserImport object to access findNextTargetFile() method for testing $messageBroker = new MessageBroker($credentials, $config); $mbcLoggingGateway = new MBC_LoggingProcessor($messageBroker, $settings); $this->assertTrue(TRUE); } }
<?php use DoSomething\MBC_LoggingGateway\MBC_LoggingGateway; // Including that file will also return the autoloader instance, so you can store // the return value of the include call in a variable and add more namespaces. // This can be useful for autoloading classes in a test suite, for example. // https://getcomposer.org/doc/01-basic-usage.md $loader = require_once __DIR__ . '/../vendor/autoload.php'; class MBC_LoggingGatewayTest extends PHPUnit_Framework_TestCase { public function setUp(){ } public function tearDown(){ } public function testLogUserImportFile() { date_default_timezone_set('America/New_York'); // Load Message Broker settings used mb mbp-user-import.php define('CONFIG_PATH', __DIR__ . '/../messagebroker-config'); require_once __DIR__ . '/../mbc-logging-gateway.config.inc'; // Create MBP_UserImport object to access findNextTargetFile() method for testing $messageBroker = new MessageBroker($credentials, $config); $mbcLoggingGateway = new MBC_LoggingGateway($messageBroker, $settings); list($endpoint, $cURLparameters, $post) = $mbcLoggingGateway->logUserImportFile($payloadDetails, $post); echo PHP_EOL . PHP_EOL; echo 'endpoint: ' . $endpoint, PHP_EOL; echo 'cURLparameters: ' . print_r($cURLparameters, TRUE), PHP_EOL; echo 'post: ' . print_r($post, TRUE), PHP_EOL; $this->assertTrue(TRUE); } }
Add view manager on test server
/** * Created by Omnius on 18/07/2016. */ 'use strict'; const Hapi = require('hapi'); const HapiAuthBasic = require('hapi-auth-basic'); const HapiAuthHawk = require('hapi-auth-hawk'); const Inert = require('inert'); const Handlebars = require('handlebars'); const Vision = require('vision'); const Visionary = require('visionary'); module.exports = function () { const server = new Hapi.Server(); server.connection({ host: '127.0.0.1', port: '9001' }); server.state('Hawk-Session-Token', { ttl: 24 * 60 * 60 * 1000, path: '/', isSecure: false, isHttpOnly: false, encoding: 'base64json', clearInvalid: true }); server.register([ HapiAuthBasic, HapiAuthHawk, Inert, Vision, Visionary ], (err) => { if (err) { throw err; } }); server.views({ path: 'views/layouts', partialsPath: 'views/layouts/partials', engines: {mustache: Handlebars} }); return server; };
/** * Created by Omnius on 18/07/2016. */ 'use strict'; const Hapi = require('hapi'); const HapiAuthBasic = require('hapi-auth-basic'); const HapiAuthHawk = require('hapi-auth-hawk'); const Inert = require('inert'); module.exports = function () { const server = new Hapi.Server(); server.connection({ host: '127.0.0.1', port: '9001' }); server.state('Hawk-Session-Token', { ttl: 24 * 60 * 60 * 1000, path: '/', isSecure: false, isHttpOnly: false, encoding: 'base64json', clearInvalid: true }); server.register([ Inert, HapiAuthBasic, HapiAuthHawk ], (err) => { if (err) { throw err; } }); return server; };
Tweak icon button forms to avoid trailing question mark in URLs
<?php declare(strict_types = 1); namespace Pages\Components\Forms; use Pages\IViewable; final class IconButtonFormComponent implements IViewable{ private string $url; private string $icon; private ?string $color = null; public function __construct(string $url, string $icon){ $this->url = $url; $this->icon = $icon; } public function color(string $color): self{ $this->color = $color; return $this; } /** @noinspection JSUnresolvedVariable */ public function echoBody(): void{ $color_class = $this->color === null ? '' : ' icon-color-'.$this->color; echo <<<HTML <form action="$this->url" method="get" onsubmit="window.location=this.action;return false"> <button type="submit" class="icon"> <span class="icon icon-$this->icon$color_class"></span> </button> </form> HTML; } } ?>
<?php declare(strict_types = 1); namespace Pages\Components\Forms; use Pages\IViewable; final class IconButtonFormComponent implements IViewable{ private string $url; private string $icon; private ?string $color = null; public function __construct(string $url, string $icon){ $this->url = $url; $this->icon = $icon; } public function color(string $color): self{ $this->color = $color; return $this; } public function echoBody(): void{ $color_class = $this->color === null ? '' : ' icon-color-'.$this->color; echo <<<HTML <form action="$this->url"> <button type="submit" class="icon"> <span class="icon icon-$this->icon$color_class"></span> </button> </form> HTML; } } ?>
Correct passing of state to state mutators
import React from 'react'; import {render} from 'react-dom'; import Rx from 'rx'; import {actionIs} from './utils.js'; /* update is an Array of trios: [actionName, actionHandler, effect] */ export default function(model, update, View, container) { let eventStream = new Rx.Subject(); let dispatcherArray = update.map(([actionName, actionHandler]) => eventStream.filter(actionIs(actionName)).map(actionHandler)) return Rx.Observable .merge(...dispatcherArray) .scan((([state, _], action) => action(state)), [model]) .startWith([model]) .do(([state, _]) => render(<View {...state} eventStream={eventStream} />, container)) .flatMap(([state, effect]) => effect ? effect(state, eventStream) : Rx.Observable.empty() ) .subscribe( function(){}, console.error.bind(console) ); }
import React from 'react'; import {render} from 'react-dom'; import Rx from 'rx'; import {actionIs} from './utils.js'; /* update is an Array of trios: [actionName, actionHandler, effect] */ export default function(model, update, View, container) { let eventStream = new Rx.Subject(); let dispatcherArray = update.map(([actionName, actionHandler]) => eventStream.filter(actionIs(actionName)).map(actionHandler)) return Rx.Observable .merge(...dispatcherArray) .scan(((state, action) => action(state)), model) .startWith([model]) .do(([state, _]) => render(<View {...state} eventStream={eventStream} />, container)) .flatMap(([state, effect]) => effect ? effect(state, eventStream) : Rx.Observable.empty() ) .subscribe( function(){}, console.error.bind(console) ); }
Call done() only when really done.
/** * Module Dependencies. */ var debug = require('debug')('metalsmith-static'); var ncp = require('ncp').ncp; var path = require('path'); var fsextra = require('fs-extra'); /** * Module Exports */ module.exports = function(assets) { assets = assets || [{}]; assets = !Array.isArray(assets) ? [ assets ] : assets; return function(files, metalsmith, done) { assets.forEach(function(opts) { var relSrc = opts.src || 'public'; var relDest = opts.dest || 'public'; var createDest = opts.createDest || true; var src = path.join(metalsmith.dir, relSrc); var dst = path.join(metalsmith.dir, metalsmith._dest, relDest); if (createDest) { var dir = path.dirname(dst); debug('creating: %s', dir); fsextra.mkdirpSync(dir); } ncp(src, dst, function(err) { if (err) return done(err); }); }); done(); }; };
/** * Module Dependencies. */ var debug = require('debug')('metalsmith-static'); var ncp = require('ncp').ncp; var path = require('path'); var fsextra = require('fs-extra'); /** * Module Exports */ module.exports = function(assets) { assets = assets || [{}]; assets = !Array.isArray(assets) ? [ assets ] : assets; return function(files, metalsmith, done) { assets.forEach(function(opts) { var relSrc = opts.src || 'public'; var relDest = opts.dest || 'public'; var createDest = opts.createDest || true; var src = path.join(metalsmith.dir, relSrc); var dst = path.join(metalsmith.dir, metalsmith._dest, relDest); if (createDest) { var dir = path.dirname(dst); debug('creating: %s', dir); fsextra.mkdirpSync(dir); } ncp(src, dst, function(err) { if (err) return done(err); done(); }); }); }; };
Make the registration process not to proceed after validation fails
const userModel = require('../../models/users') const validator = require('./registerValidation') const { buildResponse } = require('../../utils/responseService') module.exports = (req, res) => { const {error, value} = validator.validate(req.body) if (error) { return buildResponse(res, 400, { message: error.details[0].message }) } userModel.findOne(value.username) .then(user => { if (user) { buildResponse(res, 403, { message: 'user already exists' }) } else { userModel.createUser(value) .then(user => { buildResponse(res, 200, { message: 'successfully created user.', user }) }) .catch(error => { buildResponse(res, 500, { message: 'something happened', error }) }) } }) }
const userModel = require('../../models/users') const validator = require('./registerValidation') const { buildResponse } = require('../../utils/responseService') module.exports = (req, res) => { const {error, value} = validator.validate(req.body) if (error) { buildResponse(res, 400, { message: error.details[0].message }) } userModel.findOne(value.username) .then(user => { if (user) { buildResponse(res, 403, { message: 'user already exists' }) } else { userModel.createUser(value) .then(user => { buildResponse(res, 200, { message: 'successfully created user.', user }) }) .catch(error => { buildResponse(res, 500, { message: 'something happened', error }) }) } }) }
Fix file path in coverage reports
/* globals blanket, module */ var options = { modulePrefix: 'ember-g-map', filter: '//.*ember-g-map/.*/', antifilter: '//.*(tests|template).*/', loaderExclusions: [], enableCoverage: true, cliOptions: { reporters: ['lcov'], autostart: true, lcovOptions: { outputFile: 'lcov.dat', renamer: function(moduleName){ var expression = /^ember-g-map/; return moduleName.replace(expression, 'addon') + '.js'; } } } }; if (typeof exports === 'undefined') { blanket.options(options); } else { module.exports = options; }
/* globals blanket, module */ var options = { modulePrefix: 'ember-g-map', filter: '//.*ember-g-map/.*/', antifilter: '//.*(tests|template).*/', loaderExclusions: [], enableCoverage: true, cliOptions: { reporters: ['lcov'], autostart: true, lcovOptions: { outputFile: 'lcov.dat', renamer: function(moduleName){ var expression = /^ember-g-map/; return moduleName.replace(expression, 'app') + '.js'; } } } }; if (typeof exports === 'undefined') { blanket.options(options); } else { module.exports = options; }
Fix build when included in an addon When this addon is deeply nested this.app does not exist so it is necessary to walk up the addon tree to find the top level app where configuration resided.
/* eslint-env node */ 'use strict'; module.exports = { name: require('./package').name, included(app) { this._super.included.apply(this, arguments); let current = this; //Get the top most application where config will reside //ref: _findHost https://git.io/Jvi0N do { app = current.app || app; } while (current.parent.parent && (current = current.parent)); const addonOptions = (app.options && app.options.emberPikaday) || {}; const dependencies = Object.keys(this.project.dependencies()); const hasFastboot = dependencies.includes('ember-cli-fastboot'); const importOptions = {}; if (hasFastboot) { importOptions.using = [{ transformation: 'fastbootShim' }]; } this.import('node_modules/pikaday/pikaday.js', importOptions); if (!addonOptions.excludePikadayAssets) { this.import('node_modules/pikaday/css/pikaday.css'); } } };
/* eslint-env node */ 'use strict'; module.exports = { name: require('./package').name, included() { this._super.included.apply(this, arguments); const addonOptions = (this.app.options && this.app.options.emberPikaday) || {}; const dependencies = Object.keys(this.project.dependencies()); const hasFastboot = dependencies.includes('ember-cli-fastboot'); const importOptions = {}; if (hasFastboot) { importOptions.using = [{ transformation: 'fastbootShim' }]; } this.import('node_modules/pikaday/pikaday.js', importOptions); if (!addonOptions.excludePikadayAssets) { this.import('node_modules/pikaday/css/pikaday.css'); } } };
Fix gulp not copying resources initially
var gulp = require("gulp"); var browserify = require("browserify"); var source = require("vinyl-source-stream"); var watchify = require("watchify"); var tsify = require("tsify"); var gutil = require("gulp-util"); var sourcemaps = require("gulp-sourcemaps"); var buffer = require("vinyl-buffer"); var watch = require("gulp-watch"); var resourcesGlob = "resources/*" var watchedBrowserify = watchify(browserify({ basedir: ".", debug: true, entries: ["src/main.ts"], cache: {}, packageCache: {}, }) .plugin(tsify) .transform("babelify", {presets: ["es2015"], sourcemaps: true})); gulp.task("copy-resources", function () { return gulp.src(resourcesGlob) .pipe(gulp.dest("build")); }); gulp.task("watch-resources", function() { gulp.watch(resourcesGlob, ["copy-resources"]); }); function bundle() { return watchedBrowserify .bundle() .pipe(source("bundle.js")) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(sourcemaps.write("./")) .pipe(gulp.dest("build")); } gulp.task("compile-and-watch", function() { return bundle(); }); gulp.task("default", ["copy-resources", "watch-resources", "compile-and-watch"]); watchedBrowserify.on("update", bundle); watchedBrowserify.on("log", gutil.log);
var gulp = require("gulp"); var browserify = require("browserify"); var source = require("vinyl-source-stream"); var watchify = require("watchify"); var tsify = require("tsify"); var gutil = require("gulp-util"); var sourcemaps = require("gulp-sourcemaps"); var buffer = require("vinyl-buffer"); var watch = require("gulp-watch"); var resourcesGlob = "resources/*" var watchedBrowserify = watchify(browserify({ basedir: ".", debug: true, entries: ["src/main.ts"], cache: {}, packageCache: {}, }) .plugin(tsify) .transform("babelify", {presets: ["es2015"], sourcemaps: true})); gulp.task("copy-resources", function () { return gulp.src(resourcesGlob) .pipe(gulp.dest("build")); }); gulp.task("watch-resources", function() { gulp.watch(resourcesGlob, ["copy-resources"]); }); function bundle() { return watchedBrowserify .bundle() .pipe(source("bundle.js")) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(sourcemaps.write("./")) .pipe(gulp.dest("build")); } gulp.task("watch-and-compile", function() { return bundle(); }); gulp.task("default", ["watch-resources", "watch-and-compile"]); watchedBrowserify.on("update", bundle); watchedBrowserify.on("log", gutil.log);
Solve bug when creating new pages Former-commit-id: 99f6349b33753887e39e44262e4259a3f209d4d1
function loadCreator (collectionId) { var pageType, releaseDate; getCollection(collectionId, success = function (response) { if (!response.publishDate) { releaseDate = null; } else { releaseDate = response.publishDate; } }, error = function (response) { handleApiError(response); } ); $('select').off().change(function () { pageType = $(this).val(); //var parentUrl = localStorage.getItem("pageurl"); var parentUrl = Florence.globalVars.pagePath; $('.edition').empty(); if (pageType === 'bulletin' || pageType === 'article') { loadT4Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType.match(/compendium_.+/)) { loadT6Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType.match(/static_.+/)) { loadT7Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType === 'reference_tables' || pageType === 'dataset') { loadT8Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType === 'release') { loadT16Creator(collectionId, releaseDate, pageType, parentUrl); } }); }
function loadCreator (collectionId) { var pageType, releaseDate; getCollection(collectionId, success = function (response) { if (!response.publishDate) { releaseDate = null; } else { releaseDate = response.publishDate; } }, error = function (response) { handleApiError(response); } ); $('select').off().change(function () { pageType = $(this).val(); //var parentUrl = localStorage.getItem("pageurl"); var parentUrl = Florence.globalVars.pagePath; if (pageType === 'bulletin' || pageType === 'article') { $('.edition').empty(); loadT4Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType.match(/compendium_.+/)) { $('.edition').empty(); loadT6Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType.match(/static_.+/)) { $('.edition').empty(); loadT7Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType === 'reference_tables' || pageType === 'dataset') { $('.edition').empty(); loadT8Creator(collectionId, releaseDate, pageType, parentUrl); } else if (pageType === 'release') { $('.edition').empty(); loadT16Creator(collectionId, releaseDate, pageType, parentUrl); } }); }
Install the demos directory in /usr/local/share/ as well. (imported from commit 7516e5318f9e30544f53703ead4bca60f2dd7828)
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=["bin/humbug-send"], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os.path from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*") ], scripts=["bin/humbug-send"], )
Clarify language to avoid confusing between form accepted charset and form encoding type
package com.vtence.molecule.testing; import com.vtence.molecule.helpers.Charsets; import com.vtence.molecule.helpers.Joiner; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HtmlForm { private final Map<String, String> data = new HashMap<String, String>(); private Charset charset = Charsets.UTF_8; public String contentType() { return "application/x-www-form-urlencoded"; } public HtmlForm charset(String charsetName) { return charset(Charset.forName(charsetName)); } public HtmlForm charset(Charset charset) { this.charset = charset; return this; } public HtmlForm set(String name, String value) { data.put(name, value); return this; } public String encode() { List<String> pairs = new ArrayList<String>(); URLEscaper escaper = URLEscaper.to(charset); for (String name : data.keySet()) { pairs.add(escaper.escape(name) + "=" + escaper.escape(data.get(name))); } return Joiner.on("&").join(pairs); } }
package com.vtence.molecule.testing; import com.vtence.molecule.helpers.Charsets; import com.vtence.molecule.helpers.Joiner; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HtmlForm { private final Map<String, String> data = new HashMap<String, String>(); private Charset charset = Charsets.UTF_8; public String contentType() { return "application/x-www-form-urlencoded"; } public HtmlForm encoding(String charsetName) { return encoding(Charset.forName(charsetName)); } public HtmlForm encoding(Charset charset) { this.charset = charset; return this; } public HtmlForm set(String name, String value) { data.put(name, value); return this; } public String encode() { List<String> pairs = new ArrayList<String>(); URLEscaper escaper = URLEscaper.to(charset); for (String name : data.keySet()) { pairs.add(escaper.escape(name) + "=" + escaper.escape(data.get(name))); } return Joiner.on("&").join(pairs); } }
Update publications for the home page
// Publication who send back everything, use it carrefully Meteor.publish('games', function() { return Games.find(); }); // Publication who send back the last 3 live games Meteor.publish('last3LiveGames', function() { return Games.find({ gameState: { $nin: ['gameEnded', 'notStarted'] }, privateGame: false }, { limit: 3, sort: { createdAt: -1 } }); }); // Publication who send back the last 3 ended games Meteor.publish('last3EndedGames', function() { return Games.find({ gameState: 'gameEnded', privateGame: false }, { limit: 3, sort: { createdAt: -1 } }); }); // Send back one game Meteor.publish('oneGame', function(gameId) { return Games.find({ _id: gameId }); }); // Send back only the user's games Meteor.publish('myGames', function(userId) { return Games.find({ userId: userId }); }); // Send back only the games that have been created less than 7 days ago Meteor.publish('liveGames', function() { return Games.find({ privateGame: false, state: { $nin: ['notStarted'] } }); });
// Publication who send back everything, use it carrefully Meteor.publish('games', function() { return Games.find(); }); // Publication who send back the last 3 live games Meteor.publish('last3LiveGames', function() { return Games.find({ state: { $nin: ['gameEnded', 'notStarted'] }, privateGame: false }, { limit: 3 }); }); // Publication who send back the last 3 ended games Meteor.publish('last3EndedGames', function() { return Games.find({ state: 'gameEnded', privateGame: false }, { limit: 3 }); }); // Send back one game Meteor.publish('oneGame', function(gameId) { return Games.find({ _id: gameId }); }); // Send back only the user's games Meteor.publish('myGames', function(userId) { return Games.find({ userId: userId }); }); // Send back only the games that have been created less than 7 days ago Meteor.publish('liveGames', function() { return Games.find({ privateGame: false, state: { $nin: ['notStarted'] } }); });
Fix removal of q (2)
/*! * thought <https://github.com/nknapp/thought> * * Copyright (c) 2015 Nils Knappmeier. * Released under the MIT license. */ var exec = require('./utils/exeq') var semver = require('semver') module.exports = function () { return exec('npm', ['--version']) .then(function (stdio) { if (semver.lt(stdio[0], '2.13.0')) { throw new Error('npm<2.13.0 will not execute the `version`-script in your package.json.\n' + 'Please upgrade to at least 2.13.0.') } else { // eslint-disable-next-line no-console console.log('npm@' + stdio[0].trim() + ': OK') } }) }
/*! * thought <https://github.com/nknapp/thought> * * Copyright (c) 2015 Nils Knappmeier. * Released under the MIT license. */ var exec = require('./utils/exeq') var semver = require('semver') module.exports = function () { return exec('npm', ['--version']) .then(function (stdio) { if (semver.lt(stdio[0], '2.13.0')) { throw new Error('npm<2.13.0 will not execute the `version`-script in your package.json.\n' + 'Please upgrade to at least 2.13.0.') } else { // eslint-disable-next-line no-console console.log('npm@' + stdio.trim() + ': OK') } }) }
Add method to remove all access tokens from a user.
<?php namespace CatLab\OAuth2\Mappers; use Neuron\DB\Query; use Neuron\Interfaces\Models\User; /** * Class AccessTokenMapper * @package CatLab\OAuth2\Mappers */ class AccessTokenMapper { /** * @param $token * @return null|int */ public function getUserIdFromAccessToken ($token) { $data = Query::select ( 'oauth2_access_tokens', array ( 'user_id' ), array ( 'access_token' => $token ) )->execute (); if ($data) { return intval ($data[0]['user_id']); } return null; } /** * @param User $user */ public function deleteFromUser(User $user) { Query::delete('oauth2_access_tokens', [ 'user_id' => $user->getId() ])->execute(); } }
<?php /** * Created by PhpStorm. * User: daedeloth * Date: 25/12/14 * Time: 15:55 */ namespace CatLab\OAuth2\Mappers; use CatLab\Accounts\Models\User; use Neuron\DB\Query; class AccessTokenMapper { /** * @param $token * @return null|int */ public function getUserIdFromAccessToken ($token) { $data = Query::select ( 'oauth2_access_tokens', array ( 'user_id' ), array ( 'access_token' => $token ) )->execute (); if ($data) { return intval ($data[0]['user_id']); } return null; } /** * @param User $user */ public function deleteFromUser(User $user) { Query::delete('oauth2_access_tokens', [ 'user_id' => $user->getId() ])->execute(); } }