text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add class, remove edit and delete links
<?php # Copyright © 2012 Martin Ueding <dev@martin-ueding.de> class BookmarkHelper extends AppHelper { var $helpers = array('Html'); function print_bookmark($that, $bookmark) { #echo '<img width="16" height="16" src="'.$that->Html->url(array('controller' => 'bookmarks', 'action' => 'favicon', $bookmark['id'])).'" />'; #echo ' '; echo $that->Html->link($bookmark['title'], array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']), array('class' => 'bookmark_link', 'title' => $bookmark['url'])); echo ' '; echo $that->Html->link(__('View', true), array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']), array('class' => 'edit_option')); echo ' '; } }
<?php # Copyright © 2012 Martin Ueding <dev@martin-ueding.de> class BookmarkHelper extends AppHelper { var $helpers = array('Html'); function print_bookmark($that, $bookmark) { #echo '<img width="16" height="16" src="'.$that->Html->url(array('controller' => 'bookmarks', 'action' => 'favicon', $bookmark['id'])).'" />'; #echo ' '; echo $that->Html->link($bookmark['title'], array('controller' => 'bookmarks', 'action' => 'visit', $bookmark['id']), array('title' => $bookmark['url'])); echo ' '; echo $that->Html->link(__('View', true), array('controller' => 'bookmarks', 'action' => 'view', $bookmark['id']), array('class' => 'edit_option')); echo ' '; echo $that->Html->link(__('Edit', true), array('controller' => 'bookmarks', 'action' => 'edit', $bookmark['id']), array('class' => 'edit_option')); echo ' '; echo $that->Html->link(__('Delete', true), array('controller' => 'bookmarks', 'action' => 'delete', $bookmark['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $bookmark['id']), array('class' => 'edit_option')); } }
Disable Extension class prospector error
from abc import ABCMeta, abstractmethod from pylease.logger import LOGME as logme # noqa class Extension(object): # pylint: disable=abstract-class-not-used __metaclass__ = ABCMeta _IGNORE_ME_VAR_NAME = 'ignore_me' ignore_me = False def __init__(self, lizy): super(Extension, self).__init__() logme.debug("Initializing {}".format(self.__class__.__name__)) self._lizy = lizy self.load() @abstractmethod def load(self): pass # pragma: no cover @classmethod def init_all(cls, lizy): extensions = cls.__subclasses__() for extension in extensions: extension.init_all(lizy) if not getattr(extension, cls._IGNORE_ME_VAR_NAME): extension(lizy)
from abc import ABCMeta, abstractmethod from pylease.logger import LOGME as logme # noqa class Extension(object): __metaclass__ = ABCMeta _IGNORE_ME_VAR_NAME = 'ignore_me' ignore_me = False def __init__(self, lizy): super(Extension, self).__init__() logme.debug("Initializing {}".format(self.__class__.__name__)) self._lizy = lizy self.load() @abstractmethod def load(self): pass # pragma: no cover @classmethod def init_all(cls, lizy): extensions = cls.__subclasses__() for extension in extensions: extension.init_all(lizy) if not getattr(extension, cls._IGNORE_ME_VAR_NAME): extension(lizy)
Load all CSS before JavaScript
<?php function print_header( $embed = false ) { ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>IsValid | Quantify the results of A/B tests</title> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Bootstrap --> <link href="css/bootstrap-compiled.min.css" rel="stylesheet"> <!-- Local --> <link href="css/isvalid.css" rel="stylesheet"> <script src="static/scripts.min.js"></script> <!-- Fonts --> <script type="text/javascript" src="//use.typekit.net/ivm8epx.js"></script> <script type="text/javascript">try{Typekit.load();}catch(e){}</script> <?php if ( $embed ): ?> <link href="css/embed.css" rel="stylesheet"> <?php endif; ?> </head> <?php }
<?php function print_header( $embed = false ) { ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>IsValid | Quantify the results of A/B tests</title> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Fonts --> <script type="text/javascript" src="//use.typekit.net/ivm8epx.js"></script> <script type="text/javascript">try{Typekit.load();}catch(e){}</script> <!-- Bootstrap --> <link href="css/bootstrap-compiled.min.css" rel="stylesheet"> <!-- Local --> <script src="static/scripts.min.js"></script> <link href="css/isvalid.css" rel="stylesheet"> <?php if ( $embed ): ?> <link href="css/embed.css" rel="stylesheet"> <?php endif; ?> </head> <?php }
Add styles for buttonview view
import { StyleSheet, Dimensions } from 'react-native'; export default StyleSheet.create({ mainContainer: { // flex: 3, width: Dimensions.get('window').width * .97, height: Dimensions.get('window').height * .95, marginLeft: Dimensions.get('window').width / 60, marginTop: Dimensions.get('window').width / 20, }, actor_image: { borderWidth:1, borderColor:'#c0c0c0', alignItems:'center', justifyContent:'center', width: 140, height: 140, backgroundColor:'white', borderRadius: 70, resizeMode: 'cover' }, startingActorView: { flex: 1.2, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, endingActorView: { flex: 1.2, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, pathsView: { flex: 3, justifyContent: 'center', // borderWidth: 1, // left: 0, }, path: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', padding: 35, // alignItems: 'flex-start', }, endingPaths: { marginTop: Dimensions.get('window').height / 2, }, buttonView: { flex: .11, flexDirection: 'row', justifyContent: 'space-between', } })
import { StyleSheet, Dimensions } from 'react-native'; export default StyleSheet.create({ mainContainer: { // flex: 3, width: Dimensions.get('window').width * .97, height: Dimensions.get('window').height * .95, marginLeft: Dimensions.get('window').width / 60, marginTop: Dimensions.get('window').width / 20, }, actor_image: { borderWidth:1, borderColor:'#c0c0c0', alignItems:'center', justifyContent:'center', width: 140, height: 140, backgroundColor:'white', borderRadius: 70, resizeMode: 'cover' }, startingActorView: { flex: 1.2, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, endingActorView: { flex: 1.2, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', // borderWidth: 1, }, pathsView: { flex: 3, justifyContent: 'center', // borderWidth: 1, // left: 0, }, path: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', padding: 35, // alignItems: 'flex-start', }, endingPaths: { marginTop: Dimensions.get('window').height / 2, } })
Stop printing logs while running dashboard tests in catapult. Some of the dashboard tests invoke functions which log errors, but these are not interesting or indicative of actual errors when running the test. By setting the logging level in run_tests.py, this makes it so no log messages are printed when run_tests.py is run, so the output is a bit cleaner. Review URL: https://codereview.chromium.org/1180363002
#!/usr/bin/python """Runs the unit test suite for perf dashboard.""" import argparse import dev_appserver import logging import os import sys import unittest _DASHBOARD_PARENT = os.path.join(os.path.dirname(__file__)) _DASHBOARD = os.path.join(_DASHBOARD_PARENT, 'dashboard') def _GetTests(args): loader = unittest.TestLoader() if args.tests: return loader.loadTestsFromNames(args.tests) return loader.discover(_DASHBOARD, pattern='*_test.py') def _FixPath(): dev_appserver.fix_sys_path() sys.path.append(os.path.dirname(__file__)) # The __init__.py in the dashboard package should add third party # libraries to the path. import dashboard # pylint: disable=unused-variable def main(): _FixPath() parser = argparse.ArgumentParser(description='Run the test suite.') parser.add_argument( 'tests', nargs='*', help='Fully-qualified names of tests to run.') args = parser.parse_args() runner = unittest.TextTestRunner(verbosity=1) logging.basicConfig(level=logging.CRITICAL) result = runner.run(_GetTests(args)) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) if __name__ == '__main__': main()
#!/usr/bin/python """Runs the unit test suite for perf dashboard.""" import argparse import dev_appserver import os import sys import unittest _DASHBOARD_PARENT = os.path.join(os.path.dirname(__file__)) _DASHBOARD = os.path.join(_DASHBOARD_PARENT, 'dashboard') def _GetTests(args): loader = unittest.TestLoader() if args.tests: return loader.loadTestsFromNames(args.tests) return loader.discover(_DASHBOARD, pattern='*_test.py') def _FixPath(): dev_appserver.fix_sys_path() sys.path.append(os.path.dirname(__file__)) # The __init__.py in the dashboard package should add third party # libraries to the path. import dashboard # pylint: disable=unused-variable def main(): _FixPath() parser = argparse.ArgumentParser(description='Run the test suite.') parser.add_argument( 'tests', nargs='*', help='Fully-qualified names of tests to run.') args = parser.parse_args() runner = unittest.TextTestRunner(verbosity=1) result = runner.run(_GetTests(args)) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) if __name__ == '__main__': main()
Create functions getmail and getschool so they can be used in both sites user and settings
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.models import User from cronos.announcements.models import Id def getmail(request): if request.user.email[-21:] == 'notapplicablemail.com': mail = 'unset' elif request.user.get_profile().webmail_username: mail = webmail_username + '@teilar.gr' else: '' return mail def getschool(request): for item in Id.objects.filter(urlid__exact = request.user.get_profile().school): school = str(item.name) return school @login_required def user(request): return render_to_response('user.html', { 'mail': getmail(request), }, context_instance = RequestContext(request)) @login_required def user_settings(request): return render_to_response('settings.html', { 'school': getschool(request), 'mail': getmail(request), }, context_instance = RequestContext(request))
# -*- coding: utf-8 -*- from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.models import User from cronos.announcements.models import Id if request.user.email[-21:] == 'notapplicablemail.com': mail = 'unset' elif request.user.get_profile().webmail_username: mail = webmail_username + '@teilar.gr' else: '' for item in Id.objects.filter(urlid__exact = request.user.get_profile().school): school = str(item.name) @login_required def user(request): return render_to_response('user.html', { 'mail': mail, }, context_instance = RequestContext(request)) @login_required def user_settings(request): return render_to_response('settings.html', { 'school': school, 'mail': mail, }, context_instance = RequestContext(request))
flask/views: Use current_app in Blueprint module
import os.path from flask import Blueprint, render_template, current_app from flask.ext.babel import _ from skylines.lib.helpers import markdown about_blueprint = Blueprint('about', 'skylines') @about_blueprint.route('/') def about(): return render_template('about.jinja') @about_blueprint.route('/imprint') def imprint(): content = current_app.config.get( 'SKYLINES_IMPRINT', 'Please set the SKYLINES_IMPRINT variable in the config file.') return render_template( 'generic/page-FLASK.jinja', title=_('Imprint'), content=content) @about_blueprint.route('/team') def skylines_team(): path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'AUTHORS.md') with open(path) as f: content = f.read().decode('utf-8') content = content.replace('Developers', _('Developers')) content = content.replace('Translators', _('Translators')) content = markdown.convert(content) return render_template('generic/page-FLASK.jinja', title=_('The SkyLines Team'), content=content)
import os.path from flask import Blueprint, render_template from flask.ext.babel import _ from skylines import app from skylines.lib.helpers import markdown about_blueprint = Blueprint('about', 'skylines') @about_blueprint.route('/') def about(): return render_template('about.jinja') @about_blueprint.route('/imprint') def imprint(): content = app.config.get( 'SKYLINES_IMPRINT', 'Please set the SKYLINES_IMPRINT variable in the config file.') return render_template( 'generic/page-FLASK.jinja', title=_('Imprint'), content=content) @about_blueprint.route('/team') def skylines_team(): path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'AUTHORS.md') with open(path) as f: content = f.read().decode('utf-8') content = content.replace('Developers', _('Developers')) content = content.replace('Translators', _('Translators')) content = markdown.convert(content) return render_template('generic/page-FLASK.jinja', title=_('The SkyLines Team'), content=content)
Fix bootstrap still being ignored
<?php namespace OckCyp\CoversValidator\Handler; use OckCyp\CoversValidator\Loader\ConfigLoader; use OckCyp\CoversValidator\Loader\FileLoader; use OckCyp\CoversValidator\Locator\ConfigLocator; use Symfony\Component\Console\Input\InputInterface; use PHPUnit_Util_Configuration as Configuration; class InputHandler { /** * Handle console input * * @param InputInterface $input * @return Configuration */ public static function handleInput(InputInterface $input) { $configOption = $input->getOption('configuration'); $configFile = ConfigLocator::locate($configOption); $configuration = ConfigLoader::loadConfig($configFile); $phpunit = $configuration->getPHPUnitConfiguration(); if (null !== $input->getOption('bootstrap')) { $phpunit['bootstrap'] = $input->getOption('bootstrap'); } if (isset($phpunit['bootstrap'])) { FileLoader::loadFile($phpunit['bootstrap']); } return $configuration; } }
<?php namespace OckCyp\CoversValidator\Handler; use OckCyp\CoversValidator\Loader\ConfigLoader; use OckCyp\CoversValidator\Loader\FileLoader; use OckCyp\CoversValidator\Locator\ConfigLocator; use Symfony\Component\Console\Input\InputInterface; use PHPUnit_Util_Configuration as Configuration; class InputHandler { /** * Handle console input * * @param InputInterface $input * @return Configuration */ public static function handleInput(InputInterface $input) { $configOption = $input->getOption('configuration'); $configFile = ConfigLocator::locate($configOption); $configuration = ConfigLoader::loadConfig($configFile); $phpunit = $configuration->getPHPUnitConfiguration(); if ($input->hasOption('bootstrap')) { $phpunit['bootstrap'] = $input->getOption('bootstrap'); } if (isset($phpunit['bootstrap'])) { FileLoader::loadFile($phpunit['bootstrap']); } return $configuration; } }
Print char repersentation of data
import matplotlib.pyplot as plt import scipy.signal import numpy as np import time from signal_functions import * match_filter = make_match_filter() signal_in = import_wav("rec.wav") # plot_waveform(match_filter, downsample=1, title="Match Filter", ax_labels=["Samples", "Magnitude"]) # plot_signal(signal_in, downsample=1) envelope, convolution = get_envelope(signal_in[:600000]) # plot_waveform(convolution[:350000], downsample=10, title="5kHz Signal after Convolution", ax_labels=["Samples", "Magnitude"]) # plot_waveform(envelope[:35000], downsample=1, title="5kHz Signal after Convolution", ax_labels=["Samples", "Magnitude"]) # plot_signal(convolution) interrupt_t, thresholds = find_intterupts(envelope) data, packet = extract_data(interrupt_t) plot_envelope_interrupts(envelope, interrupt_t, thresholds) print("Packet:", packet, "Bits:", len(packet) + 1) print("Data:", chr(data)) while True: time.sleep(10)
import matplotlib.pyplot as plt import scipy.signal import numpy as np import time from signal_functions import * match_filter = make_match_filter() signal_in = import_wav("rec.wav") # plot_waveform(match_filter, downsample=1, title="Match Filter", ax_labels=["Samples", "Magnitude"]) # plot_signal(signal_in, downsample=1) envelope, convolution = get_envelope(signal_in[:600000]) # plot_waveform(convolution[:350000], downsample=10, title="5kHz Signal after Convolution", ax_labels=["Samples", "Magnitude"]) # plot_waveform(envelope[:35000], downsample=1, title="5kHz Signal after Convolution", ax_labels=["Samples", "Magnitude"]) # plot_signal(convolution) interrupt_t, thresholds = find_intterupts(envelope) data, packet = extract_data(interrupt_t) plot_envelope_interrupts(envelope, interrupt_t, thresholds) print("Packet:", packet, "Bits:", len(packet) + 1) print("Data:", data) while True: time.sleep(10)
Fix random code coverage decreases
<?php namespace PhpWorkshop\PhpWorkshopTest\Exercise; use PHPUnit_Framework_TestCase; use PhpWorkshop\PhpWorkshop\Exercise\BabySteps; /** * Class BabyStepsTest * @package PhpWorkshop\PhpWorkshopTest\Exercise * @author Aydin Hassan <aydin@hotmail.co.uk> */ class BabyStepsTest extends PHPUnit_Framework_TestCase { public function testHelloWorldExercise() { $e = new BabySteps; $this->assertEquals('Baby Steps', $e->getName()); $this->assertEquals('Simple Addition', $e->getDescription()); //sometime we don't get any args as number of args is random //we need some args for code-coverage, so just try again do { $args = $e->getArgs(); } while (empty($args)); foreach ($args as $arg) { $this->assertInternalType('int', $arg); } $this->assertFileExists(realpath($e->getSolution())); $this->assertFileExists(realpath($e->getProblem())); $this->assertNull($e->tearDown()); } }
<?php namespace PhpWorkshop\PhpWorkshopTest\Exercise; use PHPUnit_Framework_TestCase; use PhpWorkshop\PhpWorkshop\Exercise\BabySteps; /** * Class BabyStepsTest * @package PhpWorkshop\PhpWorkshopTest\Exercise * @author Aydin Hassan <aydin@hotmail.co.uk> */ class BabyStepsTest extends PHPUnit_Framework_TestCase { public function testHelloWorldExercise() { $e = new BabySteps; $this->assertEquals('Baby Steps', $e->getName()); $this->assertEquals('Simple Addition', $e->getDescription()); $args = $e->getArgs(); foreach ($args as $arg) { $this->assertInternalType('int', $arg); } $this->assertFileExists(realpath($e->getSolution())); $this->assertFileExists(realpath($e->getProblem())); $this->assertNull($e->tearDown()); } }
Make it an ES6 class and remove usage of self.
export class KeyPressEmulation { constructor(keyboardEventUtil, sinon) { this._keyDownListeners = []; this._keyUpListeners = []; sinon.stub(keyboardEventUtil, 'addKeyDownListener', (fn) => this._keyDownListeners.push(fn)); sinon.stub(keyboardEventUtil, 'addKeyUpListener', (fn) => this._keyUpListeners.push(fn)); } keyDownByKeyName(keyName) { this._keyDownListeners[0](keyName); } keyUpByKeyName(keyName) { this._keyUpListeners[0](keyName); } keyDownByKeyNames(keyNames) { keyNames.forEach((...args) => { this.keyDownByKeyName(...args)}); } keyUpByKeyNames(keyNames) { keyNames.forEach((...args) => { this.keyUpByKeyName(...args)}); } pressByKeyNames(keyNames) { // The first key is (normally) the Meta key, don't fire keyUp yet, // fire it only at the end of it all. var firstKeyName = keyNames[0]; this._keyDownListeners[0](firstKeyName); // Fire all keyDowns and keyUps. keyNames.slice(1).forEach((key) => { this._keyDownListeners[0](key); this._keyUpListeners[0](key); }); this.keyUpByKeyName(firstKeyName); } }
function KeyPressEmulation(keyboardEventUtil, sinon) { this._keyDownListeners = []; this._keyUpListeners = []; var self = this; sinon.stub(keyboardEventUtil, 'addKeyDownListener', function(fn) { self._keyDownListeners.push(fn); }); sinon.stub(keyboardEventUtil, 'addKeyUpListener', function(fn) { self._keyUpListeners.push(fn); }); } KeyPressEmulation.prototype = { keyDownByKeyName: function(keyName) { this._keyDownListeners[0](keyName); }, keyUpByKeyName: function(keyName) { this._keyUpListeners[0](keyName); }, keyDownByKeyNames: function(keyNames) { keyNames.forEach(this.keyDownByKeyName.bind(this)); }, keyUpByKeyNames: function(keyNames) { keyNames.forEach(this.keyUpByKeyName.bind(this)); }, pressByKeyNames: function(keyNames) { // The first key is (normally) the Meta key, don't fire keyUp yet, // fire it only at the end of it all. var firstKeyName = keyNames[0]; this._keyDownListeners[0](firstKeyName); // Fire all keyDowns and keyUps. var self = this; keyNames.slice(1).forEach(function(key) { self._keyDownListeners[0](key); self._keyUpListeners[0](key); }); this.keyUpByKeyName(firstKeyName); } }; module.exports = { KeyPressEmulation: KeyPressEmulation };
Maintain focus in change theme list view
'use babel'; import { SelectListView } from 'atom-space-pen-views'; export default class ChangeThemeView extends SelectListView { constructor(themeManager) { super(); this.modal = atom.workspace.addModalPanel({ item: this, visible: false }); this.addClass('overlay from-top'); this.list.addClass('mark-active'); this.themeManager = themeManager; } changeTheme() { this.setItems(this.themeManager.getThemeNames()); this.modal.show(); this.focusFilterEditor(); } viewForItem(theme) { let el = document.createElement('li'); el.textContent = theme; return el; } confirmed(theme) { this.themeManager.loadTheme(theme); this.modal.hide(); } cancel() { super.cancel(); this.modal.hide(); } destroy() { this.modal.destroy(); } }
'use babel'; import { SelectListView } from 'atom-space-pen-views'; export default class ChangeThemeView extends SelectListView { constructor(themeManager) { super(); this.modal = atom.workspace.addModalPanel({ item: this, visible: false }); this.addClass('overlay from-top'); this.list.addClass('mark-active'); this.themeManager = themeManager; } changeTheme() { this.setItems(this.themeManager.getThemeNames()); this.modal.show(); this.focus(); } viewForItem(theme) { let el = document.createElement('li'); el.textContent = theme; return el; } confirmed(theme) { this.themeManager.loadTheme(theme); this.modal.hide(); } cancel() { super.cancel(); this.modal.hide(); } destroy() { this.modal.destroy(); } }
chore: Add component name for LoadingBar plugin
import Vue from 'vue' import { isSSR } from './platform.js' import QAjaxBar from '../components/ajax-bar/QAjaxBar.js' export default { start () {}, stop () {}, increment () {}, install ({ $q, cfg }) { if (isSSR) { $q.loadingBar = this return } const bar = $q.loadingBar = new Vue({ name: 'LoadingBar', render: h => h(QAjaxBar, { ref: 'bar', props: cfg.loadingBar }) }).$mount().$refs.bar Object.assign(this, { start: bar.start, stop: bar.stop, increment: bar.increment }) document.body.appendChild($q.loadingBar.$parent.$el) } }
import Vue from 'vue' import { isSSR } from './platform.js' import QAjaxBar from '../components/ajax-bar/QAjaxBar.js' export default { start () {}, stop () {}, increment () {}, install ({ $q, cfg }) { if (isSSR) { $q.loadingBar = this return } const bar = $q.loadingBar = new Vue({ render: h => h(QAjaxBar, { ref: 'bar', props: cfg.loadingBar }) }).$mount().$refs.bar Object.assign(this, { start: bar.start, stop: bar.stop, increment: bar.increment }) document.body.appendChild($q.loadingBar.$parent.$el) } }
Add matplotlib as a dependency
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'Description': 'A simple Finite Element Modeling (FEM) library', 'author': 'Greg Hamel (MrJarv1s)', 'url': 'https://github.com/MrJarv1s/FEMur', 'download_url': 'https://github.com/MrJarv1s/FEMur', 'author_email': 'hamegreg@gmail.com', 'version': '0.1', 'install_requires': ['nose', 'numpy', 'scipy', 'sympy', 'matplotlib'], 'packages': ['FEMur'], 'scripts': [], 'name': 'FEMur', 'classifiers': [ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering" ] } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'Description': 'A simple Finite Element Modeling (FEM) library', 'author': 'Greg Hamel (MrJarv1s)', 'url': 'https://github.com/MrJarv1s/FEMur', 'download_url': 'https://github.com/MrJarv1s/FEMur', 'author_email': 'hamegreg@gmail.com', 'version': '0.1', 'install_requires': ['nose', 'numpy', 'scipy', 'sympy'], 'packages': ['FEMur'], 'scripts': [], 'name': 'FEMur', 'classifiers': [ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering" ] } setup(**config)
Add a missing build constraint.
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. // +build go1.3 package lxdclient import ( "github.com/juju/errors" ) type rawProfileClient interface { ProfileCreate(name string) error ListProfiles() ([]string, error) SetProfileConfigItem(name, key, value string) error } type profileClient struct { raw rawProfileClient } // CreateProfile attempts to create a new lxc profile and set the given config. func (p profileClient) CreateProfile(name string, config map[string]string) error { if err := p.raw.ProfileCreate(name); err != nil { //TODO(wwitzel3) use HasProfile to generate a more useful AlreadyExists error return errors.Trace(err) } for k, v := range config { if err := p.raw.SetProfileConfigItem(name, k, v); err != nil { return errors.Trace(err) } } return nil } // HasProfile returns true/false if the profile exists. func (p profileClient) HasProfile(name string) (bool, error) { profiles, err := p.raw.ListProfiles() if err != nil { return false, errors.Trace(err) } for _, profile := range profiles { if profile == name { return true, nil } } return false, nil }
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package lxdclient import ( "github.com/juju/errors" ) type rawProfileClient interface { ProfileCreate(name string) error ListProfiles() ([]string, error) SetProfileConfigItem(name, key, value string) error } type profileClient struct { raw rawProfileClient } // CreateProfile attempts to create a new lxc profile and set the given config. func (p profileClient) CreateProfile(name string, config map[string]string) error { if err := p.raw.ProfileCreate(name); err != nil { //TODO(wwitzel3) use HasProfile to generate a more useful AlreadyExists error return errors.Trace(err) } for k, v := range config { if err := p.raw.SetProfileConfigItem(name, k, v); err != nil { return errors.Trace(err) } } return nil } // HasProfile returns true/false if the profile exists. func (p profileClient) HasProfile(name string) (bool, error) { profiles, err := p.raw.ListProfiles() if err != nil { return false, errors.Trace(err) } for _, profile := range profiles { if profile == name { return true, nil } } return false, nil }
Replace array of glyphs with a single string and split
package com.aragaer.jtt; public class JTTHour { public static final String Glyphs[] = "酉戌亥子丑寅卯辰巳午未申".split("(?!^)"); public static final int ticks = 6; public static final int subs = 100; public boolean isNight; public int num; // 0 to 11, where 0 is hour of Cock and 11 is hour of Monkey public int strikes; public int fraction; // 0 to 99 private static final int num_to_strikes(int num) { return 9 - ((num - 3) % ticks); } public JTTHour(int num) { this(num, 0); } public JTTHour(int n, int f) { this.setTo(n, f); } // Instead of reallocation, reuse existing object public void setTo(int n, int f) { num = n; isNight = n < ticks; strikes = num_to_strikes(n); fraction = f; } }
package com.aragaer.jtt; public class JTTHour { public static final String Glyphs[] = { "酉", "戌", "亥", "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申" }; public static final int ticks = 6; public static final int subs = 100; public boolean isNight; public int num; // 0 to 11, where 0 is hour of Cock and 11 is hour of Monkey public int strikes; public int fraction; // 0 to 99 private static final int num_to_strikes(int num) { return 9 - ((num - 3) % ticks); } public JTTHour(int num) { this(num, 0); } public JTTHour(int n, int f) { this.setTo(n, f); } // Instead of reallocation, reuse existing object public void setTo(int n, int f) { num = n; isNight = n < ticks; strikes = num_to_strikes(n); fraction = f; } }
Add missing Router use statement
<?php namespace TeamTeaTime\Filer; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; class FilerServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/../config/filer.php', 'filer'); } /** * Bootstrap the application events. * * @param Router $router * @return void */ public function boot(Router $router) { // Publish migrations and config $this->publishes([ __DIR__.'/../migrations/' => base_path('/database/migrations') ], 'migrations'); $this->publishes([ __DIR__.'/../config/filer.php' => config_path('filer.php') ], 'config'); // Routes $router->group(['namespace' => 'TeamTeaTime\Filer\Controllers', 'prefix' => 'files'], function ($router) { $router->get('{id}/download', [ 'as' => 'filer.file.download', 'uses' => 'LocalFileController@download' ]); }); } }
<?php namespace TeamTeaTime\Filer; use Illuminate\Support\ServiceProvider; class FilerServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/../config/filer.php', 'filer'); } /** * Bootstrap the application events. * * @param Router $router * @return void */ public function boot(Router $router) { // Publish migrations and config $this->publishes([ __DIR__.'/../migrations/' => base_path('/database/migrations') ], 'migrations'); $this->publishes([ __DIR__.'/../config/filer.php' => config_path('filer.php') ], 'config'); // Routes $router->group(['namespace' => 'TeamTeaTime\Filer\Controllers', 'prefix' => 'files'], function ($router) { $router->get('{id}/download', [ 'as' => 'filer.file.download', 'uses' => 'LocalFileController@download' ]); }); } }
Make it not too boring.
// 21: spread - with-strings // To do: make all tests pass, leave the assert lines unchanged! describe('spread with strings', () => { it('simply spread each char of a string', function() { const [b, a] = [...'ab']; assert.equal(a, 'a'); assert.equal(b, 'b'); }); it('extracts each array item', function() { const [a, b] = ['a', ...'12']; assert.equal(a, 1); assert.equal(b, 2); }); it('works anywhere inside an array (must not be last)', function() { const letters = ['a', 'bcd', 'e', 'f']; assert.equal(letters.length, 6); }); it('dont confuse with the rest operator', function() { const [...rest] = ['1234', ...'5']; assert.deepEqual(rest, [1, 2, 3, 4, 5]); }); it('passed as function parameter', function() { const max = Math.max(12345); assert.deepEqual(max, 5); }); });
// 21: spread - with-strings // To do: make all tests pass, leave the assert lines unchanged! describe('spread with strings', () => { it('simply spread each char of a string', function() { const [b, a] = [...'ab']; assert.equal(a, 'a'); assert.equal(b, 'b'); }); it('extracts each array item', function() { const [a, b] = ['a', ...'12']; assert.equal(a, 1); assert.equal(b, 2); }); it('works anywhere inside an array (must not be last)', function() { const letters = ['a', 'bcd', 'e', 'f']; assert.equal(letters.length, 6); }); it('dont confuse with the rest operator', function() { const [...rest] = ['12345']; assert.deepEqual(rest, [1, 2, 3, 4, 5]); }); it('passed as function parameter', function() { const max = Math.max('12345'); assert.deepEqual(max, 5); }); });
Set a minimum DRF version for the next release
#!/usr/bin/env python import os from setuptools import setup, find_packages def get_readme(): return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() setup( name='rest_framework_ember', version='1.0.3', description="Make EmberJS and Django Rest Framework play nice together.", long_description=get_readme(), author="nGen Works", author_email='tech@ngenworks.com', url='https://github.com/ngenworks/rest_framework_ember', license='BSD', keywords="EmberJS Django REST", packages=find_packages(), install_requires=['django', 'djangorestframework >= 3.0.0', 'inflection' ], platforms=['any'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Environment :: Web Environment', 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python import os from setuptools import setup, find_packages def get_readme(): return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() setup( name='rest_framework_ember', version='1.0.3', description="Make EmberJS and Django Rest Framework play nice together.", long_description=get_readme(), author="nGen Works", author_email='tech@ngenworks.com', url='https://github.com/ngenworks/rest_framework_ember', license='BSD', keywords="EmberJS Django REST", packages=find_packages(), install_requires=['django', 'djangorestframework', 'inflection' ], platforms=['any'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Environment :: Web Environment', 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Convert institutions users to pytest
import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import ( InstitutionFactory, UserFactory, ) @pytest.mark.django_db class TestInstitutionUsersList: @pytest.fixture() def institution(self): return InstitutionFactory() @pytest.fixture() def user_one(self, institution): user_one = UserFactory() user_one.affiliated_institutions.add(institution) user_one.save() return user_one @pytest.fixture() def user_two(self, institution): user_two = UserFactory() user_two.affiliated_institutions.add(institution) user_two.save() return user_two @pytest.fixture() def url_institution_user(self, institution): return '/{0}institutions/{1}/users/'.format(API_BASE, institution._id) def test_return_all_users(self, app, institution, user_one, user_two, url_institution_user): res = app.get(url_institution_user) assert res.status_code == 200 ids = [each['id'] for each in res.json['data']] assert len(res.json['data']) == 2 assert user_one._id in ids assert user_two._id in ids
from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from osf_tests.factories import InstitutionFactory, UserFactory from api.base.settings.defaults import API_BASE class TestInstitutionUsersList(ApiTestCase): def setUp(self): super(TestInstitutionUsersList, self).setUp() self.institution = InstitutionFactory() self.user1 = UserFactory() self.user1.affiliated_institutions.add(self.institution) self.user1.save() self.user2 = UserFactory() self.user2.affiliated_institutions.add(self.institution) self.user2.save() self.institution_user_url = '/{0}institutions/{1}/users/'.format(API_BASE, self.institution._id) def test_return_all_users(self): res = self.app.get(self.institution_user_url) assert_equal(res.status_code, 200) ids = [each['id'] for each in res.json['data']] assert_equal(len(res.json['data']), 2) assert_in(self.user1._id, ids) assert_in(self.user2._id, ids)
Add comment to justify separate JSON file existence
import tornado.ioloop import tornado.web import requests host = 'localhost' waybackPort = '8080' # Use a separate JSON file that only queries the local WAIL instance for MemGator archiveConfigFile = '/Applications/WAIL.app/config/archive.json' class MainHandler(tornado.web.RequestHandler): def get(self): iwa = isWaybackAccessible() print iwa self.write(iwa) def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) def isWaybackAccessible(): try: r = requests.get('http://' + host + ':' + waybackPort) with open(archiveConfigFile, 'r') as myfile: data=myfile.read() return data except requests.exceptions.ConnectionError as e: return '' if __name__ == "__main__": app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start()
import tornado.ioloop import tornado.web import requests host = 'localhost' waybackPort = '8080' archiveConfigFile = '/Applications/WAIL.app/config/archive.json' class MainHandler(tornado.web.RequestHandler): def get(self): iwa = isWaybackAccessible() print iwa self.write(iwa) def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) def isWaybackAccessible(): try: r = requests.get('http://' + host + ':' + waybackPort) with open(archiveConfigFile, 'r') as myfile: data=myfile.read() return data except requests.exceptions.ConnectionError as e: return '' if __name__ == "__main__": app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start()
Handle document.head not being ready yet.
// ==UserScript== // @name Hide offline presence dot on old reddit // @namespace https://mathemaniac.org // @version 1.0.2 // @description Hides the offline presence dot from old reddit. Only hides offline presence, so you notice if you're displayed as online. https://old.reddit.com/r/changelog/comments/lx08r2/announcing_online_presence_indicators/ // @author Sebastian Paaske Tørholm // @match https://old.reddit.com/* // @icon https://www.google.com/s2/favicons?domain=reddit.com // @grant none // @run-at document-start // ==/UserScript== (function() { 'use strict'; function removeDot() { if (! document.head) { setTimeout(removeDot, 50); return; } document.head.insertAdjacentHTML('beforeend', ` <style>#header-bottom-right .presence_circle.offline { display: none !important; }</style> `); } removeDot(); })();
// ==UserScript== // @name Hide offline presence dot on old reddit // @namespace https://mathemaniac.org // @version 1.0.1 // @description Hides the offline presence dot from old reddit. Only hides offline presence, so you notice if you're displayed as online. https://old.reddit.com/r/changelog/comments/lx08r2/announcing_online_presence_indicators/ // @author Sebastian Paaske Tørholm // @match https://old.reddit.com/* // @icon https://www.google.com/s2/favicons?domain=reddit.com // @grant none // @run-at document-start // ==/UserScript== (function() { 'use strict'; document.head.insertAdjacentHTML('beforeend', ` <style>#header-bottom-right .presence_circle.offline { display: none !important; }</style> `); })();
Clean up names of commands Remove the hyphen, this is horrible to read in the web UI. Rename "Repo Download" to "repo", matching the old style used before these were ejected to a plugin. Change-Id: I1a4a02b0ab39e8249f3d3dc3d42b88fe893a93f4
// Copyright (C) 2013 The Android Open Source Project // // 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 com.googlesource.gerrit.plugins.download.command; import com.google.gerrit.extensions.annotations.Exports; import com.google.gerrit.extensions.config.DownloadCommand; import com.google.inject.AbstractModule; public class DownloadCommandsModule extends AbstractModule { @Override protected void configure() { bind(DownloadCommand.class) .annotatedWith(Exports.named("Checkout")) .to(CheckoutCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("Cherry Pick")) .to(CherryPickCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("Format Patch")) .to(FormatPatchCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("Pull")) .to(PullCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("repo")) .to(RepoCommand.class); } }
// Copyright (C) 2013 The Android Open Source Project // // 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 com.googlesource.gerrit.plugins.download.command; import com.google.gerrit.extensions.annotations.Exports; import com.google.gerrit.extensions.config.DownloadCommand; import com.google.inject.AbstractModule; public class DownloadCommandsModule extends AbstractModule { @Override protected void configure() { bind(DownloadCommand.class) .annotatedWith(Exports.named("Checkout")) .to(CheckoutCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("Cherry-Pick")) .to(CherryPickCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("Format-Patch")) .to(FormatPatchCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("Pull")) .to(PullCommand.class); bind(DownloadCommand.class) .annotatedWith(Exports.named("Repo-Download")) .to(RepoCommand.class); } }
Make sure the package data is actually installed from a source distribution. This is additionally to the manifest template. Also don't install the "example" module.
import os from setuptools import setup, find_packages from relationships import VERSION f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() setup( name='django-relationships', version=".".join(map(str, VERSION)), description='descriptive relationships between auth.User', long_description=readme, author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/django-relationships/tree/master', packages=find_packages(exclude=['example']), package_data = { 'relationships': [ 'fixtures/*.json', 'templates/*.html', 'templates/*/*.html', 'locale/*/LC_MESSAGES/*', ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
import os from setuptools import setup, find_packages from relationships import VERSION f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() setup( name='django-relationships', version=".".join(map(str, VERSION)), description='descriptive relationships between auth.User', long_description=readme, author='Charles Leifer', author_email='coleifer@gmail.com', url='http://github.com/coleifer/django-relationships/tree/master', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
Fix typo on fs variable name
var path = require('path'); var findParentDir = require('find-parent-dir'); var fs = require('fs'); function resolve(targetUrl, source) { var packageRoot = findParentDir.sync(source, 'node_modules'); if (!packageRoot) { return null; } var filePath = path.resolve(packageRoot, 'node_modules', targetUrl); var isPotentiallyDirectory = !path.extname(filePath); if (isPotentiallyDirectory) { if (fs.existsSync(filePath + '.scss')) { return path.resolve(filePath, 'index'); } if (fs.existsSync(filePath)) { return path.resolve(filePath, 'index'); } } if (fs.existsSync(path.dirname(filePath))) { return filePath; } return resolve(targetUrl, path.dirname(packageRoot)); } module.exports = function importer (url, prev, done) { return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null; };
var path = require('path'); var findParentDir = require('find-parent-dir'); var fs = require('fs'); function resolve(targetUrl, source) { var packageRoot = findParentDir.sync(source, 'node_modules'); if (!packageRoot) { return null; } var filePath = path.resolve(packageRoot, 'node_modules', targetUrl); var isPotentiallyDirectory = !path.extname(filePath); if (isPotentiallyDirectory) { if (s.existsSync(filePath + '.scss')) { return path.resolve(filePath, 'index'); } if (fs.existsSync(filePath)) { return path.resolve(filePath, 'index'); } } if (fs.existsSync(path.dirname(filePath))) { return filePath; } return resolve(targetUrl, path.dirname(packageRoot)); } module.exports = function importer (url, prev, done) { return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null; };
Refactor parser tests to split out checks
<?php /** * PHP Version 5.3 * * @copyright (c) 2014-2015 brian ridley * @author brian ridley <ptlis@ptlis.net> * @license http://opensource.org/licenses/MIT MIT * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ptlis\SemanticVersion\Test\Parse; use ptlis\SemanticVersion\Parse\VersionParser; use ptlis\SemanticVersion\Version\Label\LabelBuilder; class ParseRangeTest extends TestDataProvider { /** * @dataProvider tokenProvider */ public function testParseRange($version, $tokenList, $expectedRange, $expectedSerialization) { $parser = new VersionParser(new LabelBuilder()); $range = $parser->parseRange($tokenList); $this->assertEquals( $expectedRange, $range ); $this->assertEquals( $expectedSerialization, strval($range) ); } /** * @dataProvider tokenProvider */ public function testSerializeRange($version, $tokenList, $expectedRange, $expectedSerialization) { $this->assertEquals( $expectedSerialization, strval($expectedRange) ); } }
<?php /** * PHP Version 5.3 * * @copyright (c) 2014-2015 brian ridley * @author brian ridley <ptlis@ptlis.net> * @license http://opensource.org/licenses/MIT MIT * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ptlis\SemanticVersion\Test\Parse; use ptlis\SemanticVersion\Parse\Token; use ptlis\SemanticVersion\Parse\VersionParser; use ptlis\SemanticVersion\Version\Label\LabelBuilder; class ParseRangeTest extends TestDataProvider { /** * @dataProvider tokenProvider * * @param string $version * @param Token[] $tokenList * @param array $expectedValueList */ public function testParseRange($version, $tokenList, $expectedValueList, $expectedSerialization) { $parser = new VersionParser(new LabelBuilder()); $range = $parser->parseRange($tokenList); $this->assertEquals( $expectedValueList, $range ); $this->assertEquals( $expectedSerialization, strval($range) ); } }
Update extension to support new YouTube redesign
// Define search and replace terms for image src link var search = /s[0-9]+/g; var replace = 's512'; function getProfileImageContainer() { // Get profile image containers return $('#channel-header-container'); } function getProfileImage(container) { // Get profile image tag return container.find('img'); } function wrapEnlargeLink() { // Get profile image link var imageContainer = getProfileImageContainer(); // No image? if (!imageContainer.length) { return; } // Get img tag nested within container var imageTag = getProfileImage(imageContainer); // No tag? if (!imageTag.length) { return; } // Get image src URL var src = imageTag.attr('src'); // Replace image pixel value in URL for a larger 512px image src = src.replace(search, replace); // Wrap image tag with a link that points to the larger image $( imageTag ).wrap( "<a href='" + src + "' target='_blank'></a>" ); } // One-time injection wrapEnlargeLink();
// Define search and replace terms for image src link var search = "s100"; var replace = "s512"; function getProfileImageContainer() { // Get profile image containers return $(".channel-header-profile-image-container"); } function getProfileImage(container) { // Get profile image tag return container.find("img"); } function injectEnlargeLink() { // Get profile image link var imageContainer = getProfileImageContainer(); // No image? if (!imageContainer.length) { return; } // Get img tag var imageTag = getProfileImage(imageContainer); // No tag? if (!imageTag.length) { return; } // Get image src var src = imageTag.attr('src'); // Replace image pixel value in URL src = src.replace(search, replace); // Set link to point to the larger image imageContainer.attr('href', src); // Open in a new tab imageContainer.attr('target', '_blank'); } // One-time injection injectEnlargeLink();
Check for local additional fields as well
<?php assert($this instanceof sfDoctrineRestGenerator); ?> <?php $global_additional_fields = $this->configuration->getValue('get.global_additional_fields', []); ?> <?php $object_additional_fields = $this->configuration->getValue('get.object_additional_fields', []); ?> <?php if ($global_additional_fields !== [] || $object_additional_fields !== []): ?> protected function parsePayload(?string $payload, bool $force = false): array { if ($force || !isset($this->_payload_array)) { $payload_array = parent::parsePayload($payload, $force); $filter_params = <?php var_export(array_flip(array_merge($global_additional_fields, $object_additional_fields))) ?>; $this->_payload_array = array_diff_key($payload_array, $filter_params); } return $this->_payload_array; } <?php endif; ?>
<?php assert($this instanceof sfDoctrineRestGenerator); ?> <?php $global_additional_fields = $this->configuration->getValue('get.global_additional_fields', []); ?> <?php $object_additional_fields = $this->configuration->getValue('get.global_additional_fields', []); ?> <?php if ($global_additional_fields !== [] || $object_additional_fields !== []): ?> protected function parsePayload(?string $payload, bool $force = false): array { if ($force || !isset($this->_payload_array)) { $payload_array = parent::parsePayload($payload, $force); $filter_params = <?php var_export(array_flip(array_merge($global_additional_fields, $object_additional_fields))) ?>; $this->_payload_array = array_diff_key($payload_array, $filter_params); } return $this->_payload_array; } <?php endif; ?>
Fix session being sought on res
var r = require('rethinkdb'); var redditBot = require('../reddit/contexts/bot.js'); module.exports = function authBotCtor(cfg, env) { var botAuthReddit = redditBot(cfg); return function authBot(req, res, next) { botAuthReddit.auth(req.query.code).then(function (refreshToken) { return botAuthReddit.deauth() .then(function(){ return r.table('users').get(cfg.botName) .update({refreshToken: refreshToken}).run(env.conn); }) .then(function () { // "log out" and redirect to the index // so we can log in as ourselves delete req.session.username; delete req.session.bot; res.redirect('/'); },next); }); }; };
var r = require('rethinkdb'); var redditBot = require('../reddit/contexts/bot.js'); module.exports = function authBotCtor(cfg, env) { var botAuthReddit = redditBot(cfg); return function authBot(req, res, next) { botAuthReddit.auth(req.query.code).then(function (refreshToken) { return botAuthReddit.deauth() .then(function(){ return r.table('users').get(cfg.botName) .update({refreshToken: refreshToken}).run(env.conn); }) .then(function () { // "log out" and redirect to the index // so we can log in as ourselves delete res.session.username; delete res.session.bot; res.redirect('/'); },next); }); }; };
Add Models and Collections to the window app namespace to persist data between routes.
module.exports = (function() { var Router = require('router'), Connection = require('lib/connection'); // App namespace. window.Boards = { Models: {}, Collections: {} }; // Load helpers. require('lib/helpers'); // Register Swag Helpers. Swag.registerHelpers(); // Initialize Router. Boards.Router = new Router(); // Create a Connection object to communicate with the server through web sockets. // The `connection` object will be added to the `Application` object so it's available through // `window.Application.connection`. Boards.Connection = new Connection({ type: APPLICATION_CONNECTION, httpUrl: APPLICATION_HTTP_URL, socketUrl: APPLICATION_WEBSOCKET_URL }); // Connect to the server. Boards.Connection.create().done(function() { Boards.Router.start(); }).fail(function() { console.log('Connection Error', arguments); }); })();
module.exports = (function() { var Router = require('router'), Connection = require('lib/connection'); // App namespace. window.Boards = {}; // Load helpers. require('lib/helpers'); // Register Swag Helpers. Swag.registerHelpers(); // Initialize Router. Boards.Router = new Router(); // Create a Connection object to communicate with the server through web sockets. // The `connection` object will be added to the `Application` object so it's available through // `window.Application.connection`. Boards.Connection = new Connection({ type: APPLICATION_CONNECTION, httpUrl: APPLICATION_HTTP_URL, socketUrl: APPLICATION_WEBSOCKET_URL }); // Connect to the server. Boards.Connection.create().done(function() { Boards.Router.start(); }).fail(function() { console.log('Connection Error', arguments); }); })();
Define AO_VERSION before require process-request
/*! * AllOrigins * written by Gabriel Nunes <gabriel@multiverso.me> * http://github.com/gnuns */ const express = require('express') const {version} = require('./package.json') // yep, global. it's ok // https://softwareengineering.stackexchange.com/a/47926/289420 global.AO_VERSION = version const processRequest = require('./app/process-request') const app = express() app.set('case sensitive routing', false) app.disable('x-powered-by') app.use(enableCORS) app.all('/:format', processRequest) function enableCORS (req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin || '*') res.header('Access-Control-Allow-Credentials', true) res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PATCH, PUT, DELETE') res.header('Via', `allOrigins v${version}`) next() } module.exports = app
/*! * AllOrigins * written by Gabriel Nunes <gabriel@multiverso.me> * http://github.com/gnuns */ const express = require('express') const {version} = require('./package.json') const processRequest = require('./app/process-request') // yep, global. it's ok // https://softwareengineering.stackexchange.com/a/47926/289420 global.AO_VERSION = version const app = express() app.set('case sensitive routing', false) app.disable('x-powered-by') app.use(enableCORS) app.all('/:format', processRequest) function enableCORS (req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin || '*') res.header('Access-Control-Allow-Credentials', true) res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PATCH, PUT, DELETE') res.header('Via', `allOrigins v${version}`) next() } module.exports = app
Add a comment for the title hack.
"use strict"; // Blank the document so the 404 page doesn't show up visibly. document.documentElement.style.display = 'none'; // Can't use DOMContentLoaded, calling document.write or document.close inside it from // inside an extension causes a crash. window.addEventListener("load", function() { function resolveUrl(name) { if (!chrome || !chrome.extension) return name; return chrome.extension.getURL(name); } // FIXME: Work around http://crbug.com/411111 where the title won't dynamically // update anymore in Chrome 37 unless we reuse the same <title> element. var title = document.querySelector("title"); title.textContent = "Chromium Code Review"; document.write( "<!DOCTYPE html>" + "<meta name=viewport content='initial-scale=1, maximum-scale=1, user-scalable=no'>" + "<script src='" + resolveUrl("bower_components/platform/platform.js") + "'></script>" + "<script>EXTENSION_URL = '" + resolveUrl("") + "';</script>" + "<link rel='import' href='" + resolveUrl("ui/components/cr-app.html") + "'>" + "<link rel='stylesheet' href='" + resolveUrl("ui/style.css") + "'>" + "<cr-app></cr-app>" ); document.close(); document.head.appendChild(title); document.documentElement.style.display = ''; });
"use strict"; // Blank the document so the 404 page doesn't show up visibly. document.documentElement.style.display = 'none'; // Can't use DOMContentLoaded, calling document.write or document.close inside it from // inside an extension causes a crash. window.addEventListener("load", function() { function resolveUrl(name) { if (!chrome || !chrome.extension) return name; return chrome.extension.getURL(name); } var title = document.querySelector("title"); title.textContent = "Chromium Code Review"; document.write( "<!DOCTYPE html>" + "<meta name=viewport content='initial-scale=1, maximum-scale=1, user-scalable=no'>" + "<script src='" + resolveUrl("bower_components/platform/platform.js") + "'></script>" + "<script>EXTENSION_URL = '" + resolveUrl("") + "';</script>" + "<link rel='import' href='" + resolveUrl("ui/components/cr-app.html") + "'>" + "<link rel='stylesheet' href='" + resolveUrl("ui/style.css") + "'>" + "<cr-app></cr-app>" ); document.close(); document.head.appendChild(title); document.documentElement.style.display = ''; });
Add comment describing dpi conversion
package com.googlecode.pngtastic.core; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Usage: * <code> * byte[] bytes = new PngChunkInserter().insert(image, PngChunkInserter.dpi300Chunk); * final File exported = image.export(toDir + "/name.png", bytes); * </code> * * @author ray */ public class PngChunkInserter { /** * Conversion note: one inch is equal to exactly 0.0254 meters. * 300dpi = 300 / 0.0254 = 11,811.023622 = 11811 = 0x2E23 = new byte[] { 0, 0, 46, 35 } * http://comments.gmane.org/gmane.comp.graphics.png.general/2425 */ private static final byte[] dpi300 = new byte[] { 0, 0, 46, 35, 0, 0, 46, 35, 1 }; public static final PngChunk dpi300Chunk = new PngChunk(PngChunk.PHYSICAL_PIXEL_DIMENSIONS.getBytes(), dpi300); public byte[] insert(PngImage image, PngChunk chunk) throws IOException { // add it after the header chunk image.getChunks().add(1, chunk); final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); image.writeDataOutputStream(outputBytes); return outputBytes.toByteArray(); } }
package com.googlecode.pngtastic.core; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Usage: * <code> * byte[] bytes = new PngChunkInserter().insert(image, PngChunkInserter.dpi300Chunk); * final File exported = image.export(toDir + "/name.png", bytes); * </code> * * @author ray */ public class PngChunkInserter { private static final byte[] dpi300 = new byte[] { 0, 0, 46, 35, 0, 0, 46, 35, 1 }; public static final PngChunk dpi300Chunk = new PngChunk(PngChunk.PHYSICAL_PIXEL_DIMENSIONS.getBytes(), dpi300); public byte[] insert(PngImage image, PngChunk chunk) throws IOException { // add it after the header chunk image.getChunks().add(1, chunk); final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); image.writeDataOutputStream(outputBytes); return outputBytes.toByteArray(); } }
refactor: Use domain to catch async exception
const vm = require('vm'); const request = require('request'); const iconv = require('iconv-lite'); const ws = require('ws'); /* eslint-disable no-console */ const TIMEOUT = 600; exports.getScript = (code, name) => { code = code && code.trim(); if (!code) { return; } code = `const d = require('domain').create(); d.on('error', console.error); d.run(() => { ${code} });`; try { return new vm.Script(code, { filename: name, timeout: TIMEOUT }); } catch (err) { console.error(err); } }; exports.execScript = (script) => { if (!script) { return; } const ctx = Object.create(global); ctx.require = require; ctx.request = request; ctx.iconv = iconv; ctx.ws = ws; ctx.module = {}; ctx.exports = ctx.module.exports = {}; try { script.runInNewContext(ctx); } catch (err) { console.error(err); return; } return ctx.module.exports; };
const vm = require('vm'); const request = require('request'); const iconv = require('iconv-lite'); const ws = require('ws'); /* eslint-disable no-console */ const TIMEOUT = 600; exports.getScript = (code, name) => { code = code && code.trim(); if (!code) { return; } try { return new vm.Script(code, { filename: name, timeout: TIMEOUT }); } catch (err) { console.error(err); } }; exports.execScript = (script) => { if (!script) { return; } const ctx = Object.create(global); ctx.require = require; ctx.request = request; ctx.iconv = iconv; ctx.ws = ws; ctx.module = {}; ctx.exports = ctx.module.exports = {}; try { script.runInNewContext(ctx); } catch (err) { console.error(err); return; } return ctx.module.exports; };
Update @ Mon Mar 13 2017 11:13:52 GMT+0800 (CST)
process.env.NODE_ENV = process.env.NODE_ENV || 'production' const ora = require('ora') const rm = require('rimraf') const chalk = require('chalk') const webpack = require('webpack') const config = require('../config') const webpackConfig = require('../config/webpack') const spinner = ora(`Building for env:${process.env.NODE_ENV}...`) spinner.start() module.exports = () => rm(config.paths.output, err => { if (err) throw err webpack(webpackConfig, (err, stats) => { spinner.stop() if (err) throw err console.log(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false })) console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) }) }) // Execute when root if (!module.parent) { module.exports() }
process.env.NODE_ENV = process.env.NODE_ENV || 'production' const ora = require('ora') const rm = require('rimraf') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const config = require('../config') const webpackConfig = require('../config/webpack') const spinner = ora(`Building for env:${process.env.NODE_ENV}...`) spinner.start() module.exports = () => rm(path.join(config.paths.output, config.paths.assets), err => { if (err) throw err webpack(webpackConfig, (err, stats) => { spinner.stop() if (err) throw err console.log(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false })) console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) }) }) // Execute when root if (!module.parent) { module.exports() }
Fix snackbar in production, where the error name was being minimized Squashed commit of the following: commit e0b1b02001d138441bb40a432b412043ab83bc62 Author: Jesse Smith <sosaucily@gmail.com> Date: Tue Apr 25 11:46:24 2017 +0200 add some logging
import { showMessageBarMessage } from 'containers/MessageBar/actions'; // Works with redux-api-middleware, taking action when requests fail const apiErrorHandlingMidddlware = (store) => (next) => (action) => { const message = action.payload ? fetchError(action.payload) || false : false; if (message) { store.dispatch(showMessageBarMessage(message)); } return next(action); }; function fetchError(payload) { let response = ''; const errorData = payload.errors ? payload.errors : payload.response; if (errorData && errorData.status) { if (errorData.status === 403) { response = 'Invalid request - 403'; } else if (errorData.status === 401) { response = 'Unauthorized, please try your request again - 401'; } else if (errorData.status === 404) { response = 'Error reaching server - 404'; } else if (errorData.status === 500) { response = errorData.message; } } return response; } export default apiErrorHandlingMidddlware;
import { showMessageBarMessage } from 'containers/MessageBar/actions'; // Works with redux-api-middleware, taking action when requests fail const apiErrorHandlingMidddlware = (store) => (next) => (action) => { const message = action.payload ? fetchError(action.payload) || false : false; if (message) { store.dispatch(showMessageBarMessage(message)); } return next(action); }; function fetchError(payload) { let response = ''; if (payload.name === 'ApiError' || payload.name === 'SubmissionError') { const errorData = payload.errors ? payload.errors : payload.response; if (errorData.status === 403) { response = 'Invalid request - 403'; } else if (errorData.status === 401) { response = 'Unauthorized, please try your request again - 401'; } else if (errorData.status === 404) { response = 'Error reaching server - 404'; } else if (errorData.status === 500) { response = errorData.message; } } return response; } export default apiErrorHandlingMidddlware;
Add most desired maintenance intervals: 14 days and 30 days
// @flow export const Maintenances = { off: "off", quarterHour: "quarterHour", oneHour: "oneHour", threeHours: "threeHours", sixHours: "sixHours", oneDay: "oneDay", oneWeek: "oneWeek", twoWeeks: "twoWeeks", oneMonth: "oneMonth", }; export const MaintenanceTimes = { off: 0, quarterHour: 15, oneHour: 60, threeHours: 180, sixHours: 360, oneDay: 1440, oneWeek: 10080, twoWeeks: 20160, oneMonth: 43200, }; export const MaintenanceCaptions = { off: "Off", quarterHour: "15 min", oneHour: "1 hour", threeHours: "3 hours", sixHours: "6 hours", oneDay: "1 day", oneWeek: "1 week", twoWeeks: "2 weeks", oneMonth: "1 month", }; export type Maintenance = $Keys<typeof Maintenances>; export function getMaintenanceCaption(maintenance: Maintenance): string { return MaintenanceCaptions[maintenance]; } export function getMaintenanceTime(maintenance: Maintenance): number { return MaintenanceTimes[maintenance]; }
// @flow export const Maintenances = { off: "off", quarterHour: "quarterHour", oneHour: "oneHour", threeHours: "threeHours", sixHours: "sixHours", oneDay: "oneDay", oneWeek: "oneWeek", }; export const MaintenanceTimes = { off: 0, quarterHour: 15, oneHour: 60, threeHours: 180, sixHours: 360, oneDay: 1440, oneWeek: 10080, }; export const MaintenanceCaptions = { off: "Off", quarterHour: "15 min", oneHour: "1 hour", threeHours: "3 hours", sixHours: "6 hours", oneDay: "1 day", oneWeek: "1 week", }; export type Maintenance = $Keys<typeof Maintenances>; export function getMaintenanceCaption(maintenance: Maintenance): string { return MaintenanceCaptions[maintenance]; } export function getMaintenanceTime(maintenance: Maintenance): number { return MaintenanceTimes[maintenance]; }
Fix delayed stream test to always check
var common = require('../common'); var assert = common.assert; var CombinedStream = common.CombinedStream; var fs = require('fs'); var FILE1 = common.dir.fixture + '/file1.txt'; var FILE2 = common.dir.fixture + '/file2.txt'; var EXPECTED = fs.readFileSync(FILE1) + fs.readFileSync(FILE2); var GOT; (function testDelayedStreams() { var combinedStream = CombinedStream.create(); combinedStream.append(fs.createReadStream(FILE1)); combinedStream.append(fs.createReadStream(FILE2)); var stream1 = combinedStream._streams[0]; var stream2 = combinedStream._streams[1]; stream1.on('end', function() { assert.equal(stream2.dataSize, 0); }); var tmpFile = common.dir.tmp + '/combined.txt'; var dest = fs.createWriteStream(tmpFile); combinedStream.pipe(dest); dest.on('end', function() { GOT = fs.readFileSync(tmpFile, 'utf8'); }); })(); process.on('exit', function() { assert.strictEqual(GOT, EXPECTED); });
var common = require('../common'); var assert = common.assert; var CombinedStream = common.CombinedStream; var fs = require('fs'); var FILE1 = common.dir.fixture + '/file1.txt'; var FILE2 = common.dir.fixture + '/file2.txt'; var EXPECTED = fs.readFileSync(FILE1) + fs.readFileSync(FILE2); (function testDelayedStreams() { var combinedStream = CombinedStream.create(); combinedStream.append(fs.createReadStream(FILE1)); combinedStream.append(fs.createReadStream(FILE2)); var stream1 = combinedStream._streams[0]; var stream2 = combinedStream._streams[1]; stream1.on('end', function() { assert.equal(stream2.dataSize, 0); }); var tmpFile = common.dir.tmp + '/combined.txt'; var dest = fs.createWriteStream(tmpFile); combinedStream.pipe(dest); dest.on('end', function() { var written = fs.readFileSync(tmpFile, 'utf8'); assert.strictEqual(written, EXPECTED); }); })();
Change algorithms to accept array of weights
<?php namespace Cs278\BankModulus; final class ModulusAlgorithm { public static function mod10($input, array $weights) { // var_dump($input, $weights); return self::calculateMod($input, $weights) % 10; } public static function mod11($input, array $weights) { return self::calculateMod($input, $weights) % 11; } public static function dblAl($input, array $weights) { return self::calculateDblAl($input, $weights) % 10; } public static function calculateMod($input, array $weights) { $checksum = self::applyWeights($input, $weights); return array_sum($checksum); } public static function calculateDblAl($input, array $weights) { $checksum = self::applyWeights($input, $weights); // Sum individual digits. $checksum = array_reduce($checksum, function ($carry, $value) { return $carry + array_sum(str_split($value)); }, 0); return $checksum % 10; } private static function applyWeights($input, array $weights) { return array_map(function ($a, $b) { return $a * $b; }, str_split($input), $weights); } }
<?php namespace Cs278\BankModulus; final class ModulusAlgorithm { public static function mod10($input, $weights) { // var_dump($input, $weights); return self::calculateMod($input, $weights) % 10; } public static function mod11($input, $weights) { return self::calculateMod($input, $weights) % 11; } public static function dblAl($input, $weights) { return self::calculateDblAl($input, $weights) % 10; } public static function calculateMod($input, $weights) { $checksum = self::applyWeights($input, $weights); return array_sum($checksum); } public static function calculateDblAl($input, $weights) { $checksum = self::applyWeights($input, $weights); // Sum individual digits. $checksum = array_reduce($checksum, function ($carry, $value) { return $carry + array_sum(str_split($value)); }, 0); return $checksum % 10; } private static function applyWeights($input, $weights) { return array_map(function ($a, $b) { return $a * $b; }, str_split($input), str_split($weights)); } }
Add class when an input receives focus
import Ember from 'ember'; const FormControl = Ember.Component.extend({ intl: Ember.inject.service(), classNames: "form-field", classNameBindings: ['hasErrors:has-errors', 'focused'], showErrors: false, focusIn() { this.set('focused', true); }, focusOut() { this.set('focused', false); }, inputId: Ember.computed("elementId", { get() { return `${this.get("elementId")}-input`; } }), label: Ember.computed("data", "field", { get() { let modelName = this.get("data.content.constructor.modelName") || this.get("data.constructor.modelName"); if (!modelName) { return; } let fieldName = this.get("field"); if (!fieldName) { return; } modelName = Ember.String.underscore(modelName); fieldName = Ember.String.underscore(fieldName); return this.get("intl").t( `models.attributes.${modelName}.${fieldName}`); } }), init() { this._super(...arguments); this.hasErrors = Ember.computed.notEmpty( `data.validations.attrs.${this.get('field')}.errors`); } }); FormControl.reopenClass({ positionalParams: ["field"] }); export default FormControl;
import Ember from 'ember'; const FormControl = Ember.Component.extend({ intl: Ember.inject.service(), showErrors: false, classNames: "form-field", classNameBindings: ['hasErrors:has-errors'], inputId: Ember.computed("elementId", { get() { return `${this.get("elementId")}-input`; } }), label: Ember.computed("data", "field", { get() { let modelName = this.get("data.content.constructor.modelName") || this.get("data.constructor.modelName"); if (!modelName) { return; } let fieldName = this.get("field"); if (!fieldName) { return; } modelName = Ember.String.underscore(modelName); fieldName = Ember.String.underscore(fieldName); return this.get("intl").t( `models.attributes.${modelName}.${fieldName}`); } }), init() { this._super(...arguments); this.hasErrors = Ember.computed.notEmpty( `data.validations.attrs.${this.get('field')}.errors`); } }); FormControl.reopenClass({ positionalParams: ["field"] }); export default FormControl;
Remove fake-unsafeWindow because it's too buggy.
(function (<bridge>) { with ({ document: window.document, location: window.location, }) { // define GM functions var GM_log = function (s) { window.console.log('GM_log: ' + s); return <bridge>.gmLog_(s); }; var GM_getValue = function (k, d) { return <bridge>.gmValueForKey_defaultValue_scriptName_namespace_(k, d, "<name>", "<namespace>"); }; var GM_setValue = function (k, v) { return <bridge>.gmSetValue_forKey_scriptName_namespace_(v, k, "<name>", "<namespace>"); }; /* Not implemented yet var GM_registerMenuCommand = function (t, c) { <bridge>.gmRegisterMenuCommand_callback_(t, c); } */ var GM_xmlhttpRequest = function (d) { return <bridge>.gmXmlhttpRequest_(d); }; <body>; } });
(function (<bridge>) { // unsafeWindow with ({ unsafeWindow: window, document: window.document, location: window.location, window: undefined }) { // define GM functions var GM_log = function (s) { unsafeWindow.console.log('GM_log: ' + s); return <bridge>.gmLog_(s); }; var GM_getValue = function (k, d) { return <bridge>.gmValueForKey_defaultValue_scriptName_namespace_(k, d, "<name>", "<namespace>"); }; var GM_setValue = function (k, v) { return <bridge>.gmSetValue_forKey_scriptName_namespace_(v, k, "<name>", "<namespace>"); }; /* Not implemented yet var GM_registerMenuCommand = function (t, c) { <bridge>.gmRegisterMenuCommand_callback_(t, c); } */ var GM_xmlhttpRequest = function (d) { return <bridge>.gmXmlhttpRequest_(d); }; <body>; } });
Fix typo from previous commit
/* * Title module displaying title tag based on current view */ var EngineJS_titleManager = { content: {}, titleDefault: "", titleSuffix: "", init: function(content, titleDefault, titleSuffix) { this.content = content; this.titleDefault = titleDefault; this.titleSuffix = titleSuffix; }, change: function(view) { var contentPageKey = view.replace(/\//g, '-'); var title = this.content[contentPageKey]; if(title === undefined) { title = this.titleDefault; } else { title += ' - ' + this.titleSuffix; } document.title = title; } };
/* * Title module displaying title tag based on current view */ var EngineJS_titleManager = { content: {}, titleDefault: "", titleSuffix: "", init: function(content, titleDefault, titleSuffix) { this.content = content; this.titleDefault = titleDefault; this.titleSuffix = titleSuffix; }, change: function(view) { var contentPageKey = view.replace(/\//g, '-'); var title = this.content[contentPageKey]; if(title === undefined) { title = this.titleDefault; } else { title + ' - ' + this.titleSuffix; } document.title = title; } };
Modify the function signature to cover the other changes made to file locations Signed-off-by: Kevin Kirsche <18695bc9b6a48cd25cda049e45c04495c905a059@gmail.com>
package nessusExporter import ( "database/sql" "fmt" "net/http" "github.com/kkirsche/nessusControl/api" ) // NewExporter returns a new exporter instance for use in exporting scan results func NewExporter(apiClient *nessusAPI.Client, httpClient *http.Client, sqliteDB *sql.DB, baseDirectory string, debug bool) *Exporter { return &Exporter{ apiClient: apiClient, sqliteDB: sqliteDB, httpClient: httpClient, fileLocations: NewFileLocations(baseDirectory), debug: debug, } } // NewFileLocations returns a new fileLocations struct for use in an exporter. func NewFileLocations(baseDirectory string) FileLocations { return FileLocations{ baseDirectory: baseDirectory, resultsDirectory: fmt.Sprintf("%s/results", baseDirectory), } }
package nessusExporter import ( "database/sql" "github.com/kkirsche/nessusControl/api" "net/http" ) // NewExporter returns a new exporter instance for use in exporting scan results func NewExporter(apiClient *nessusAPI.Client, httpClient *http.Client, sqliteDB *sql.DB, fileLocations fileLocations, debug bool) *Exporter { return &Exporter{ apiClient: apiClient, sqliteDB: sqliteDB, httpClient: httpClient, fileLocations: NewFileLocations(baseDirectory), debug: debug, } } // NewFileLocations returns a new fileLocations struct for use in an exporter. func NewFileLocations(baseDirectory string) FileLocations { return FileLocations{ baseDirectory: baseDirectory, resultsDirectory: fmt.Sprintf("%s/results", baseDirectory), } }
Add support for linux with File.separator
package org.apache.maven.siteindexer.mojo; import java.io.IOException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.siteindexer.Indexer; /** * This goal will build the index. * * @goal index * @aggregator * */ public class IndexerMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { Indexer indexer = new Indexer(getLog()); try { getLog().info("Maven Site Index"); getLog().info("------------------------------"); getLog().info("building index.js..."); indexer.buildIndex( "target"+ File.separator +"site"+ File.separator, "target" + File.separator + "site" + File.separator + "js" + File.separator + "index.js"); getLog().info("done."); } catch (IOException e) { getLog().error(e); } } }
package org.apache.maven.siteindexer.mojo; import java.io.IOException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.siteindexer.Indexer; /** * This goal will build the index. * * @goal index * @aggregator * */ public class IndexerMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { Indexer indexer = new Indexer(getLog()); try { getLog().info("Maven Site Index"); getLog().info("------------------------------"); getLog().info("building index.js..."); indexer.buildIndex( "target\\site\\", "target\\site\\js\\index.js"); getLog().info("done."); } catch (IOException e) { getLog().error(e); } } }
Add test case for no key in "property"
import { strictEqual } from 'assert' import { property } from '../src' describe('property', () => { it('should generate a named property accessor for the provided string key', () => { const o = { a: 1, b: 2 } strictEqual(property('a')(o), 1) strictEqual(property('b')(o), 2) }) it('should generate a property accessor that will return undefined for undefined properties', () => { const o = { a: 1, b: 2 } strictEqual(property('c')(o), undefined) }) it('should generate a property accessor that will return undefined if call on an undefined object', () => { strictEqual(property('c')(undefined), undefined) }) it('should generate property accessors that support dot notation for subproperties', () => { const o = { a: { aa: { aaa: 1 }, ab: 2 } } strictEqual(property('a.aa.aaa')(o), 1) strictEqual(property('a.ab')(o), 2) }) it('should generate property accessors that return undefined if the accessor path is broken', () => { const o = { a: 1 } strictEqual(property('b.c.e')(o), undefined) }) it('should return the full object if key is not provided', () => { const o = { a: 1 } strictEqual(property()(o), o) strictEqual(property(null)(o), o) }) })
import { strictEqual } from 'assert' import { property } from '../src' describe('property', () => { it('should generate a named property accessor for the provided string key', () => { const o = { a: 1, b: 2 } strictEqual(property('a')(o), 1) strictEqual(property('b')(o), 2) }) it('should generate a property accessor that will return undefined for undefined properties', () => { const o = { a: 1, b: 2 } strictEqual(property('c')(o), undefined) }) it('should generate a property accessor that will return undefined if call on an undefined object', () => { strictEqual(property('c')(undefined), undefined) }) it('should generate property accessors that support dot notation for subproperties', () => { const o = { a: { aa: { aaa: 1 }, ab: 2 } } strictEqual(property('a.aa.aaa')(o), 1) strictEqual(property('a.ab')(o), 2) }) it('should generate property accessors that return undefined if the accessor path is broken', () => { const o = { a: 1 } strictEqual(property('b.c.e')(o), undefined) }) })
Remove the query key from hashHistory
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, useRouterHistory } from 'react-router' import { createHashHistory } from 'history' window.$ = require('jquery'); import Case from './components/Case.js' import CaseReader from './components/CaseReader.js' import {CaseOverview} from './components/CaseOverview.js' import EdgenoteGallery from './components/EdgenoteGallery.js' import Modal from './components/Modal.js' window.i18n = {} window.i18n.locale = 'ja' const appHistory = useRouterHistory(createHashHistory)({ queryKey: false }) render(( <Router history={appHistory}> <Route path="/" component={Case}> <IndexRoute component={CaseOverview} /> <Route onEnter={() => window.scrollTo(0, 0)} path="edgenotes" component={EdgenoteGallery}> <Route path=":edgenoteID" component={Modal} /> </Route> <Route onEnter={() => window.scrollTo(0, 0)} path=":chapter" component={CaseReader}> <Route path="edgenotes/:edgenoteID" component={Modal} /> </Route> </Route> </Router> ), document.getElementById('container'))
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, hashHistory } from 'react-router' window.$ = require('jquery'); import Case from './components/Case.js' import CaseReader from './components/CaseReader.js' import {CaseOverview} from './components/CaseOverview.js' import EdgenoteGallery from './components/EdgenoteGallery.js' import Modal from './components/Modal.js' window.i18n = {} window.i18n.locale = 'ja' render(( <Router history={hashHistory}> <Route path="/" component={Case}> <IndexRoute component={CaseOverview} /> <Route onEnter={() => window.scrollTo(0, 0)} path="edgenotes" component={EdgenoteGallery}> <Route path=":edgenoteID" component={Modal} /> </Route> <Route onEnter={() => window.scrollTo(0, 0)} path=":chapter" component={CaseReader}> <Route path="edgenotes/:edgenoteID" component={Modal} /> </Route> </Route> </Router> ), document.getElementById('container'))
Tweak to error message propagation
package uk.ac.ebi.biosamples.neo; import java.util.Collection; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer; import uk.ac.ebi.biosamples.neo.model.NeoSample; import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository; @Component public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> { private Logger log = LoggerFactory.getLogger(this.getClass()); private Random random = new Random(); public NeoMessageBuffer(NeoSampleRepository repository) { super(repository); } @Override protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) { int retryCount = 0; while (retryCount < 100) { try { //this will have its own transaction repository.save(samples); return; } catch (ConcurrencyFailureException e) { retryCount += 1 ; log.warn("Retrying due to transient exception. Attempt number "+retryCount); try { Thread.sleep(random.nextInt(400)+100); } catch (InterruptedException e1) { //do nothing } } } throw new RuntimeException("Unable to save within "+retryCount+" retries"); } }
package uk.ac.ebi.biosamples.neo; import java.util.Collection; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Component; import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer; import uk.ac.ebi.biosamples.neo.model.NeoSample; import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository; @Component public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> { private Logger log = LoggerFactory.getLogger(this.getClass()); private Random random = new Random(); public NeoMessageBuffer(NeoSampleRepository repository) { super(repository); } @Override protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) { int retryCount = 0; while (retryCount < 100) { try { //this will have its own transaction repository.save(samples); return; } catch (ConcurrencyFailureException e) { retryCount += 1 ; log.info("Retrying due to transient exception. Attempt number "+retryCount); try { Thread.sleep(random.nextInt(400)+100); } catch (InterruptedException e1) { //do nothing } } } log.warn("Unable to save within "+retryCount+" retries"); } }
Return json error response for ALL api errors HTML responses were being returned for non-existent endpoints. This was resulting on some uncaught exceptions.
import os import sys from aiohttp import web from mako.template import Template from virtool.utils import get_static_hash from virtool.handlers.utils import json_response @web.middleware async def middleware(req, handler): is_api_call = req.path.startswith("/api") try: response = await handler(req) if not is_api_call and response.status == 404: return handle_404(req.app["client_path"]) return response except web.HTTPException as ex: if is_api_call: return json_response({ "id": "not_found", "message": "Not found" }) if ex.status == 404: return handle_404(req.app["client_path"]) raise def handle_404(client_path): path = os.path.join(sys.path[0], "templates", "error_404.html") html = Template(filename=path).render(hash=get_static_hash(client_path)) return web.Response(body=html, content_type="text/html", status=404)
import os import sys from aiohttp import web from mako.template import Template from virtool.utils import get_static_hash @web.middleware async def middleware(req, handler): is_api_call = req.path.startswith("/api") try: response = await handler(req) if not is_api_call and response.status == 404: return handle_404(req.app["client_path"]) return response except web.HTTPException as ex: if ex.status == 404: return handle_404(req.app["client_path"]) raise def handle_404(client_path): path = os.path.join(sys.path[0], "templates", "error_404.html") html = Template(filename=path).render(hash=get_static_hash(client_path)) return web.Response(body=html, content_type="text/html", status=404)
Remove old, now irrelevant comment
<?php namespace Brick\App\View\Helper; use Brick\Di\Injector; use Brick\App\View\View; /** * This view helper allows to render a View from within another View (referred to as a partial view). */ trait PartialViewHelper { /** * @var \Brick\Di\Injector|null */ private $injector; /** * @Brick\Di\Annotation\Inject * * @param \Brick\Di\Injector $injector * * @return void */ final public function setInjector(Injector $injector) { $this->injector = $injector; } /** * Renders a partial View. * * @param \Brick\App\View\View $view The View object to render. * * @return string The rendered View. */ final public function partial(View $view) { if ($this->injector) { $this->injector->inject($view); } return $view->render(); } }
<?php namespace Brick\App\View\Helper; use Brick\Di\Injector; use Brick\App\View\View; /** * This view helper allows to render a View from within another View (referred to as a partial view). * The rendering of the partial view is done wia a ViewRenderer, which allows to inject dependencies into it. */ trait PartialViewHelper { /** * @var \Brick\Di\Injector|null */ private $injector; /** * @Brick\Di\Annotation\Inject * * @param \Brick\Di\Injector $injector * * @return void */ final public function setInjector(Injector $injector) { $this->injector = $injector; } /** * Renders a partial View. * * @param \Brick\App\View\View $view The View object to render. * * @return string The rendered View. */ final public function partial(View $view) { if ($this->injector) { $this->injector->inject($view); } return $view->render(); } }
Move variables to their relevant scope
'use strict'; var nouns = [ 'cat', 'dog', 'mouse', 'house' ]; // Returns a random integer between min (included) and max (excluded) // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function generateMetaphor(nouns) { var firstNoun = ''; var secondNoun = ''; var metaphor = ''; var numberOfNouns = nouns.length; var nounIndex1 = 0; var nounIndex2 = 0; nounIndex1 = getRandomInt(0, numberOfNouns); nounIndex2 = getRandomInt(0, numberOfNouns); firstNoun = capitalizeFirstLetter(nouns[nounIndex1]); secondNoun = nouns[nounIndex2]; metaphor = firstNoun + ' is a ' + secondNoun + '.'; console.log(metaphor); } generateMetaphor(nouns);
'use strict'; var nouns = [ 'cat', 'dog', 'mouse', 'house' ]; var firstNoun = ''; var secondNoun = ''; var metaphor = ''; var numberOfNouns = nouns.length; var nounIndex1 = 0; var nounIndex2 = 0; // Returns a random integer between min (included) and max (excluded) // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function generateMetaphor(nouns) { nounIndex1 = getRandomInt(0, numberOfNouns); nounIndex2 = getRandomInt(0, numberOfNouns); firstNoun = capitalizeFirstLetter(nouns[nounIndex1]); secondNoun = nouns[nounIndex2]; metaphor = firstNoun + ' is a ' + secondNoun + '.'; console.log(metaphor); } generateMetaphor(nouns);
Use kwargs to fix Plugin2 BS configure ordering
from __future__ import absolute_import from django.core.urlresolvers import reverse from django.http import HttpResponse from sentry.plugins import plugins from sentry.web.frontend.base import ProjectView class ProjectPluginConfigureView(ProjectView): required_scope = 'project:write' def handle(self, request, organization, team, project, slug): try: plugin = plugins.get(slug) except KeyError: return self.redirect(reverse('sentry-manage-project', args=[project.organization.slug, project.slug])) if not plugin.can_configure_for_project(project): return self.redirect(reverse('sentry-manage-project', args=[project.organization.slug, project.slug])) view = plugin.configure(request=request, project=project) if isinstance(view, HttpResponse): return view context = { 'page': 'plugin', 'title': plugin.get_title(), 'view': view, 'plugin': plugin, 'plugin_is_enabled': plugin.is_enabled(project), } return self.respond('sentry/projects/plugins/configure.html', context)
from __future__ import absolute_import from django.core.urlresolvers import reverse from django.http import HttpResponse from sentry.plugins import plugins from sentry.web.frontend.base import ProjectView class ProjectPluginConfigureView(ProjectView): required_scope = 'project:write' def handle(self, request, organization, team, project, slug): try: plugin = plugins.get(slug) except KeyError: return self.redirect(reverse('sentry-manage-project', args=[project.organization.slug, project.slug])) if not plugin.can_configure_for_project(project): return self.redirect(reverse('sentry-manage-project', args=[project.organization.slug, project.slug])) view = plugin.configure(request, project=project) if isinstance(view, HttpResponse): return view context = { 'page': 'plugin', 'title': plugin.get_title(), 'view': view, 'plugin': plugin, 'plugin_is_enabled': plugin.is_enabled(project), } return self.respond('sentry/projects/plugins/configure.html', context)
Fix service edit javascript bug The value that was set was overwritten directly.
'use strict'; $(document).ready(function() { function enableOrDisableAttributeField() { var rows = $(this) .parents('.attribute-row-wrapper') .find('.form-row'); if ($(this).is(':checked')) { rows.removeClass('disabled'); var motivation = rows.find('input.motivation'); motivation.removeAttr('disabled'); if (motivation.data('old-value')) { motivation.val(motivation.data('old-value')); } } else { rows.addClass('disabled'); rows.find('input.motivation').attr('disabled', 'disabled'); var motivation = rows.find('input.motivation'); motivation.data('old-value', motivation.val()); motivation.val(''); } } $('input.requested').each(enableOrDisableAttributeField); $('input.requested').on('change', enableOrDisableAttributeField); });
'use strict'; $(document).ready(function() { function enableOrDisableAttributeField() { var rows = $(this) .parents('.attribute-row-wrapper') .find('.form-row'); if ($(this).is(':checked')) { rows.removeClass('disabled'); var motivation = rows.find('input.motivation'); motivation.removeAttr('disabled'); motivation.val(motivation.data('old-value')); } else { rows.addClass('disabled'); rows.find('input.motivation').attr('disabled', 'disabled'); var motivation = rows.find('input.motivation'); motivation.data('old-value', motivation.val()); motivation.val(''); } } $('input.requested').each(enableOrDisableAttributeField); $('input.requested').on('change', enableOrDisableAttributeField); });
Fix object crawl breaking on magic methods.
<?php function ex($object, $coords, $default = null) { if (!is_array($object) and !is_object($object)) { return $default; } $keys = explode('.', $coords); foreach ($keys as $key) { if (is_array($object)) { if (isset($object[$key])) { $object = $object[$key]; } else { return $default; } } elseif (is_object($object)) { $test = $object->$key; if ($test) { $object = $test; } else { return $default; } } else { return $default; } } return $object ? $object : $default; }
<?php function ex($object, $coords, $default = null) { if (!is_array($object) and !is_object($object)) { return $default; } $keys = explode('.', $coords); foreach ($keys as $key) { if (is_array($object)) { if (isset($object[$key])) { $object = $object[$key]; } else { return $default; } } elseif (is_object($object)) { if (property_exists($object, $key)) { $object = $object->$key; } else { return $default; } } else { return $default; } } return $object ? $object : $default; }
Adjust to return Response object
<?php namespace Core\LayoutBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { public function indexAction() { return $this->render('CoreLayoutBundle:Default:index.html.twig'); } public function getUrlAction() { $urlHelper = $this->container->get('url_helper'); $url = $this->container->get('request_stack')->getMasterRequest()->get('url'); $result = $urlHelper->getContentUrl($url); $response = new Response(); if (array_key_exists('error', $result) && $result['error']) { $response->setContent($result['error']); } else { $response->setContent($result['content']); if (array_key_exists('header', $result) && is_array($result['header']) && !empty($result['header']) ) { $response->headers->add($result['header']); } } return $response; } }
<?php namespace Core\LayoutBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction() { return $this->render('CoreLayoutBundle:Default:index.html.twig'); } public function getUrlAction() { $urlHelper = $this->container->get('url_helper'); $url = $this->container->get('request_stack')->getMasterRequest()->get('url'); $result = $urlHelper->getContentUrl($url); if (array_key_exists('error', $result) && $result['error']) { print($result['error']); exit(); } if (array_key_exists('header', $result) && is_array($result['header']) && !empty($result['header']) ) { foreach ($result['header'] as $header) { header($header); } } print($result['content']); exit(); } }
Extend decision response with new fields
<?php namespace Covery\Client; class ResultBaseField { const REQUEST_ID = 'requestId'; const TYPE = 'type'; const CREATED_AT = 'createdAt'; const SEQUENCE_ID = 'sequenceId'; const MERCHANT_USER_ID = 'merchantUserId'; const SCORE = 'score'; const ACCEPT = 'accept'; const REJECT = 'reject'; const MANUAL = 'manual'; const REASON = 'reason'; const ACTION = 'action'; public static function getAll() { return [ self::REQUEST_ID, self::TYPE, self::CREATED_AT, self::SEQUENCE_ID, self::MERCHANT_USER_ID, self::SCORE, self::ACCEPT, self::REJECT, self::MANUAL, self::REASON, self::ACTION ]; } }
<?php namespace Covery\Client; class ResultBaseField { const REQUEST_ID = 'requestId'; const TYPE = 'type'; const CREATED_AT = 'createdAt'; const SEQUENCE_ID = 'sequenceId'; const MERCHANT_USER_ID = 'merchantUserId'; const SCORE = 'score'; const ACCEPT = 'accept'; const REJECT = 'reject'; const MANUAL = 'manual'; const REASON = 'reason'; const ACTION = 'action'; public static function getAll() { return [ self::REQUEST_ID, self::TYPE, self::CREATED_AT, self::SEQUENCE_ID, self::MERCHANT_USER_ID, self::SCORE, self::ACCEPT, self::REJECT, self::MANUAL, self::REASON, self::ACTION ]; } }
Fix a typo in function call
/** * A rate-limiting Throttle model, by IP address * */ var mongoose = require('mongoose') var ipRegex = require('ip-regex') var Schema = mongoose.Schema mongoose.Promise = global.Promise /** * Register the Throttle model * * @access public * @param {object} defaults * @return {object} Mongoose Model */ module.exports = function createThrottle (defaults) { var Throttle = new Schema({ createdAt: { type: Date, required: true, default: Date.now, expires: defaults.rateLimit.ttl }, ip: { type: String, required: true, trim: true, match: ipRegex() }, hits: { type: Number, default: 1, required: true, max: defaults.rateLimit.max, min: 0 } }) Throttle.index( { createdAt: 1 }, { expireAfterSeconds: defaults.rateLimit.ttl } ) return mongoose.model('Throttle', Throttle) }
/** * A rate-limiting Throttle model, by IP address * */ var mongoose = require('mongoose') var ipRegex = require('ip-regex') var Schema = mongoose.Schema mongoose.Promise = global.Promise /** * Register the Throttle model * * @access public * @param {object} defaults * @return {object} Mongoose Model */ module.exports = function createThrottle (defaults) { var Throttle = new Schema({ createdAt: { type: Date, required: true, default: Date.now, expires: defaults.rateLimit.ttl }, ip: { type: String, required: true, trim: true, match: ipRegex }, hits: { type: Number, default: 1, required: true, max: defaults.rateLimit.max, min: 0 } }) Throttle.index( { createdAt: 1 }, { expireAfterSeconds: defaults.rateLimit.ttl } ) return mongoose.model('Throttle', Throttle) }
Fix tests by constructing a new server and connection in setup
package com.proxerme.library.util; import android.support.test.InstrumentationRegistry; import com.proxerme.library.connection.ProxerConnection; import org.junit.After; import org.junit.Before; import java.io.IOException; import okhttp3.mockwebserver.MockWebServer; /** * Base class for all {@link com.proxerme.library.connection.ProxerRequest} subclass tests. * * @author Ruben Gees */ public class RequestTest { protected MockWebServer server; protected ProxerConnection connection; protected RequestTest() { } @Before public void setUp() throws IOException { server = new MockWebServer(); connection = new ProxerConnection.Builder("test", InstrumentationRegistry.getContext()).build(); server.start(); } @After public void tearDown() throws IOException { server.shutdown(); } }
package com.proxerme.library.util; import android.support.test.InstrumentationRegistry; import com.proxerme.library.connection.ProxerConnection; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.IOException; import okhttp3.mockwebserver.MockWebServer; /** * Base class for all {@link com.proxerme.library.connection.ProxerRequest} subclass tests. * * @author Ruben Gees */ public class RequestTest { protected static MockWebServer server = new MockWebServer(); protected static ProxerConnection connection = new ProxerConnection.Builder("test", InstrumentationRegistry.getContext()).build(); protected RequestTest() { } @BeforeClass public static void setUpServer() throws IOException { server.start(); } @AfterClass public static void tearDownServer() throws IOException { server.shutdown(); } }
Revert "fix: initialize PFL control properly"
/* @flow */ import type { LaunchpadDevice, MidiMessage } from '../../' import type { ChannelControl, ControlMessage } from '@mixxx-launchpad/mixxx' import { modes } from '../ModifierSidebar' import type { Modifier } from '../ModifierSidebar' export default (gridPosition: [number, number]) => (deck: ChannelControl) => (modifier: Modifier) => (device: LaunchpadDevice) => (device: LaunchpadDevice) => { return { bindings: { pfl: { type: 'control', target: deck.pfl, update: ({ value }: ControlMessage, { bindings }: Object) => value ? bindings.button.button.sendColor(device.colors.hi_green) : bindings.button.button.sendColor(device.colors.black) }, button: { type: 'button', target: gridPosition, attack: (message: MidiMessage, { bindings }: Object) => modes(modifier.getState(), () => bindings.pfl.setValue(Number(!bindings.pfl.getValue()))) } } } }
/* @flow */ import type { LaunchpadDevice, MidiMessage } from '../../' import type { ChannelControl, ControlMessage } from '@mixxx-launchpad/mixxx' import { modes } from '../ModifierSidebar' import type { Modifier } from '../ModifierSidebar' export default (gridPosition: [number, number]) => (deck: ChannelControl) => (modifier: Modifier) => (device: LaunchpadDevice) => { return { bindings: { pfl: { type: 'control', target: deck.pfl, update: ({ value }: ControlMessage, { bindings }: Object) => value ? bindings.button.button.sendColor(device.colors.hi_green) : bindings.button.button.sendColor(device.colors.black) }, button: { type: 'button', target: gridPosition, attack: (message: MidiMessage, { bindings }: Object) => modes(modifier.getState(), () => bindings.pfl.setValue(Number(!bindings.pfl.getValue()))) } } } }
Use promise all at the right place in the server connecting action
import { sqlectron } from '../../browser/remote'; export const CONNECTION_REQUEST = 'CONNECTION_REQUEST'; export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS'; export const CONNECTION_FAILURE = 'CONNECTION_FAILURE'; export const dbSession = sqlectron.db.createSession(); export function connect (id, database) { return async (dispatch, getState) => { const { servers } = getState(); const server = servers.items.find(srv => srv.id === id); dispatch({ type: CONNECTION_REQUEST, server, database }); try { const [, config ] = await Promise.all([ dbSession.connect(server, database), sqlectron.config.get(), ]); dispatch({ type: CONNECTION_SUCCESS, server, database, config }); } catch (error) { dispatch({ type: CONNECTION_FAILURE, server, database, error }); } }; }
import { sqlectron } from '../../browser/remote'; export const CONNECTION_REQUEST = 'CONNECTION_REQUEST'; export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS'; export const CONNECTION_FAILURE = 'CONNECTION_FAILURE'; export const dbSession = sqlectron.db.createSession(); export function connect (id, database) { return async (dispatch, getState) => { const { servers } = getState(); const [ server, config ] = await* [ servers.items.find(srv => srv.id === id), sqlectron.config.get(), ]; dispatch({ type: CONNECTION_REQUEST, server, database }); try { await dbSession.connect(server, database); dispatch({ type: CONNECTION_SUCCESS, server, database, config }); } catch (error) { dispatch({ type: CONNECTION_FAILURE, server, database, error }); } }; }
Use json (from stdlib) instead of simplejson from django utils
# -*- coding: utf-8 -*- __author__ = 'sandlbn' import json from django.db.models.query import QuerySet def event_serializer(events): """ serialize event model """ objects_body = [] if isinstance(events, QuerySet): for event in events: field = { "id": event.pk, "title": event.title, "url": event.url, "class": event.css_class, "start": event.start_timestamp, "end": event.end_timestamp } objects_body.append(field) objects_head = {"success": 1} objects_head["result"] = objects_body return json.dumps(objects_head)
# -*- coding: utf-8 -*- __author__ = 'sandlbn' from django.utils import simplejson from django.db.models.query import QuerySet def event_serializer(events): """ serialize event model """ objects_body = [] if isinstance(events, QuerySet): for event in events: field = { "id": event.pk, "title": event.title, "url": event.url, "class": event.css_class, "start": event.start_timestamp, "end": event.end_timestamp } objects_body.append(field) objects_head = {"success": 1} objects_head["result"] = objects_body return simplejson.dumps(objects_head, encoding='utf-8')
Fix bug where there was an empty report
from jinja2 import Environment, PackageLoader from qanta import qlogging log = qlogging.get(__name__) class ReportGenerator: def __init__(self, template): self.template = template def create(self, variables, md_output, pdf_output): env = Environment(loader=PackageLoader('qanta', 'reporting/templates')) template = env.get_template(self.template) markdown = template.render(variables) if md_output is not None: with open(md_output, 'w') as f: f.write(markdown) try: import pypandoc pypandoc.convert_text( markdown, 'pdf', format='md', outputfile=pdf_output, extra_args=['-V', 'geometry:margin=.75in'] ) except Exception as e: log.warn('Pandoc was not installed or there was an error calling it, omitting PDF report') log.warn(str(e))
from jinja2 import Environment, PackageLoader from qanta import qlogging log = qlogging.get(__name__) class ReportGenerator: def __init__(self, template): self.template = template def create(self, variables, md_output, pdf_output): env = Environment(loader=PackageLoader('qanta', 'reporting/templates')) template = env.get_template(self.template) markdown = template.render(variables) if md_output is not None: with open(md_output, 'w') as f: f.write(md_output) try: import pypandoc pypandoc.convert_text( markdown, 'pdf', format='md', outputfile=pdf_output, extra_args=['-V', 'geometry:margin=.75in'] ) except Exception as e: log.warn('Pandoc was not installed or there was an error calling it, omitting PDF report') log.warn(str(e))
Read port and log level from environment
import deviceMiddleware from 'express-device'; import express from 'express'; import bodyParser from 'body-parser'; import winston from 'winston'; import routerRender from './middleware/routerRender'; import errorRender from './middleware/errorRender'; import staticMiddleware from './middleware/static'; const defaultConfig = { logLevel: process.env.NODE_LOGLEVEL || 'info', port: process.env.NODE_PORT || 3000, }; export default function server(userConfig = {}) { const app = express(); const config = { ...defaultConfig, ...userConfig }; winston.level = config.logLevel; app.use('/static', staticMiddleware); if (process.env.NODE_ENV === 'production') { app.use('/assets', express.static('dist/frontend')); } app.use(deviceMiddleware.capture()); app.use(bodyParser.json()); app.use(bodyParser.json({ type: 'application/json' })); if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') { // eslint-disable-next-line global-require app.use(require('./middleware/dev').default); } app.use(routerRender); app.use(errorRender); app.ready = new Promise((resolve) => { app.server = app.listen(config.port, () => { winston.log('info', `Started server on port ${config.port}`); resolve(); }); }); return app; }
import deviceMiddleware from 'express-device'; import express from 'express'; import bodyParser from 'body-parser'; import winston from 'winston'; import routerRender from './middleware/routerRender'; import errorRender from './middleware/errorRender'; import staticMiddleware from './middleware/static'; const defaultConfig = { logLevel: 'info', port: 3000, }; export default function server(userConfig = {}) { const app = express(); const config = { ...defaultConfig, ...userConfig }; winston.level = config.logLevel; app.use('/static', staticMiddleware); if (process.env.NODE_ENV === 'production') { app.use('/assets', express.static('dist/frontend')); } app.use(deviceMiddleware.capture()); app.use(bodyParser.json()); app.use(bodyParser.json({ type: 'application/json' })); if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') { // eslint-disable-next-line global-require app.use(require('./middleware/dev').default); } app.use(routerRender); app.use(errorRender); app.ready = new Promise((resolve) => { app.server = app.listen(config.port, () => { winston.log('info', `Started server on port ${config.port}`); resolve(); }); }); return app; }
Set LMS_BASE setting for Studio This allows previews in LMS to work properly. ECOM-6634
""" Overrides for Docker-based devstack. """ from .devstack import * # pylint: disable=wildcard-import, unused-wildcard-import # Docker does not support the syslog socket at /dev/log. Rely on the console. LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = { 'class': 'logging.NullHandler', } LOGGING['loggers']['tracking']['handlers'] = ['console'] HOST = 'edx.devstack.edxapp:18000' SITE_NAME = HOST LMS_ROOT_URL = 'http://{}:18000'.format(HOST) # This is the public-facing host used for previews LMS_BASE = 'localhost:18000' OAUTH_OIDC_ISSUER = '{}/oauth2'.format(LMS_ROOT_URL) JWT_AUTH.update({ 'JWT_SECRET_KEY': 'lms-secret', 'JWT_ISSUER': OAUTH_OIDC_ISSUER, 'JWT_AUDIENCE': 'lms-key', })
""" Overrides for Docker-based devstack. """ from .devstack import * # pylint: disable=wildcard-import, unused-wildcard-import # Docker does not support the syslog socket at /dev/log. Rely on the console. LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = { 'class': 'logging.NullHandler', } LOGGING['loggers']['tracking']['handlers'] = ['console'] HOST = 'edx.devstack.edxapp:18000' SITE_NAME = HOST LMS_ROOT_URL = 'http://{}:18000'.format(HOST) OAUTH_OIDC_ISSUER = '{}/oauth2'.format(LMS_ROOT_URL) JWT_AUTH.update({ 'JWT_SECRET_KEY': 'lms-secret', 'JWT_ISSUER': OAUTH_OIDC_ISSUER, 'JWT_AUDIENCE': 'lms-key', })
Add date min-max filtering to API
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from rest_framework import viewsets import django_filters from core.models import Timesheet, Task, Entry from .serializers import (UserSerializer, TimesheetSerializer, TaskSerializer, EntrySerializer) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class TimesheetViewSet(viewsets.ModelViewSet): queryset = Timesheet.objects.all() serializer_class = TimesheetSerializer filter_fields = ('id',) class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('id', 'timesheet',) class EntryFilter(django_filters.rest_framework.FilterSet): min_date = django_filters.DateFilter(name="date", lookup_expr="gte") max_date = django_filters.DateFilter(name="date", lookup_expr="lte") class Meta: model = Entry fields = ('id', 'date', 'user', 'task', 'task__timesheet',) class EntryViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer filter_class = EntryFilter
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from rest_framework import viewsets from core.models import Timesheet, Task, Entry from .serializers import (UserSerializer, TimesheetSerializer, TaskSerializer, EntrySerializer) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class TimesheetViewSet(viewsets.ModelViewSet): queryset = Timesheet.objects.all() serializer_class = TimesheetSerializer filter_fields = ('id',) class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('id', 'timesheet',) class EntryViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer filter_fields = ('id', 'user', 'task', 'task__timesheet',)
Fix - Removed obsolete code
/* global Backbone */ /* global $ */ /* global _ */ (function(){ "use strict"; var app = app || {}; $(document).ready(function() { var myData = { type : 'confirm', height : '400px', width : '500px', template : $('#my-modal-template').html(), // Customizable template // function must be defined here only. // It does not support functions declared outside events: property. events : { 'click .confirm' : function(ev) { console.log('Clicked on Confirm', ev); }, 'modal-open' : function (ev) { console.log('Modal is opened', ev); }, 'modal-close' : function(ev) { console.log('Modal is closed', ev); } }, }; app.myModal = new Backbone.Modal(myData); $('#btn-open').on('click', function() { app.myModal.show(); }); $('#btn-close').on('click', function() { app.myModal.hide(); }); }); })();
/* global Backbone */ /* global $ */ /* global _ */ (function(){ "use strict"; var app = app || {}; $(document).ready(function() { var myData = { type : 'confirm', height : '400px', width : '500px', template : $('#my-modal-template').html(), // Customizable template // function must be defined here only. // It does not support functions declared outside events: property. events : { 'click .confirm' : function(ev) { console.log('Clicked on Confirm', ev); }, 'modal-open' : function (ev) { console.log('Modal is opened', ev); }, 'modal-close' : function(ev) { console.log('Modal is closed', ev); } }, }; app.myModal = new Backbone.Modal(myData); $('#btn-open').on('click', function() { app.myModal.show(); }); $('#btn-close').on('click', function() { app.myModal.hide(); }); $('#btn-log').on('click', function() { console.log(myData, app.myModal, $('#bbm-here').html()); }); }); })();
Use zap.Any for handling interface{} -> zap.Field conversion zap.Any falls back to zap.Reflect, but is better for this case, because it first checks for the types that zap handles specially. For example, time.Duration, or error, which zap.Reflect will just treat as untyped int64 or struct objects, but zap.Any is able to detect these types and print them properly.
// Package zapadapter provides a logger that writes to a go.uber.org/zap.Logger. package zapadapter import ( "github.com/jackc/pgx" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) type Logger struct { logger *zap.Logger } func NewLogger(logger *zap.Logger) *Logger { return &Logger{logger: logger.WithOptions(zap.AddCallerSkip(1))} } func (pl *Logger) Log(level pgx.LogLevel, msg string, data map[string]interface{}) { fields := make([]zapcore.Field, len(data)) i := 0 for k, v := range data { fields[i] = zap.Any(k, v) i++ } switch level { case pgx.LogLevelTrace: pl.logger.Debug(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...) case pgx.LogLevelDebug: pl.logger.Debug(msg, fields...) case pgx.LogLevelInfo: pl.logger.Info(msg, fields...) case pgx.LogLevelWarn: pl.logger.Warn(msg, fields...) case pgx.LogLevelError: pl.logger.Error(msg, fields...) default: pl.logger.Error(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...) } }
// Package zapadapter provides a logger that writes to a go.uber.org/zap.Logger. package zapadapter import ( "github.com/jackc/pgx" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) type Logger struct { logger *zap.Logger } func NewLogger(logger *zap.Logger) *Logger { return &Logger{logger: logger.WithOptions(zap.AddCallerSkip(1))} } func (pl *Logger) Log(level pgx.LogLevel, msg string, data map[string]interface{}) { fields := make([]zapcore.Field, len(data)) i := 0 for k, v := range data { fields[i] = zap.Reflect(k, v) i++ } switch level { case pgx.LogLevelTrace: pl.logger.Debug(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...) case pgx.LogLevelDebug: pl.logger.Debug(msg, fields...) case pgx.LogLevelInfo: pl.logger.Info(msg, fields...) case pgx.LogLevelWarn: pl.logger.Warn(msg, fields...) case pgx.LogLevelError: pl.logger.Error(msg, fields...) default: pl.logger.Error(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...) } }
Remove reference to email from short description
import os from setuptools import setup, find_packages os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' setup( name="django-nopassword", version='1.1.0', url='http://github.com/relekang/django-nopassword', author='Rolf Erik Lekang', author_email='me@rolflekang.com', description='Authentication backend for django that uses a one time code instead of passwords', packages=find_packages(exclude='tests'), tests_require=[ 'django>=1.4', 'twilio>=3.6.8', 'mock>=1.0' ], license='MIT', test_suite='runtests.runtests', include_package_data=True, classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Operating System :: OS Independent", "Natural Language :: English", ] )
import os from setuptools import setup, find_packages os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' setup( name="django-nopassword", version='1.1.0', url='http://github.com/relekang/django-nopassword', author='Rolf Erik Lekang', author_email='me@rolflekang.com', description='Authentication backend for django that uses ' 'email verification instead of passwords', packages=find_packages(exclude='tests'), tests_require=[ 'django>=1.4', 'twilio>=3.6.8', 'mock>=1.0' ], license='MIT', test_suite='runtests.runtests', include_package_data=True, classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Operating System :: OS Independent", "Natural Language :: English", ] )
Change slug format in Post model
import {DataTypes as t} from "sequelize" import format from "date-fns/format" import createSlug from "lib/helper/util/createSlug" /** * @const schema * * @type {import("sequelize").ModelAttributes} */ const schema = { id: { type: t.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }, userId: { type: t.INTEGER.UNSIGNED, allowNull: false }, title: { type: t.STRING, allowNull: false, /** * @param {string} value */ set(value) { this.setDataValue("title", value) this.setDataValue( "slug", `${format(Date.now(), "YYYY-MM-dd")}/${createSlug(value)}}` ) } }, slug: { type: t.STRING, allowNull: false, unique: true }, text: { type: t.TEXT({length: "medium"}), allowNull: false }, isDraft: { type: t.BOOLEAN, allowNull: false, defaultValue: true } } export default schema
import {DataTypes as t} from "sequelize" import format from "date-fns/format" import createSlug from "lib/helper/util/createSlug" /** * @const schema * * @type {import("sequelize").ModelAttributes} */ const schema = { id: { type: t.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }, userId: { type: t.INTEGER.UNSIGNED, allowNull: false }, title: { type: t.STRING, allowNull: false, /** * @param {string} value */ set(value) { this.setDataValue("title", value) this.setDataValue( "slug", `${createSlug(value)}-${format(Date.now(), "YYYY-MM-dd")}` ) } }, slug: { type: t.STRING, allowNull: false, unique: true }, text: { type: t.TEXT({length: "medium"}), allowNull: false }, isDraft: { type: t.BOOLEAN, allowNull: false, defaultValue: true } } export default schema
Fix read middleware to align with proper endpoint
'use strict'; const validator = require('../util/validator'); const serverErrors = require('../util/server-errors'); const sendJson = require('../util/send-json'); module.exports = function({version, resource, controller}) { const {validations, plural_form, actions} = resource; const notAllowedMiddleware = [(req, res) => { res.status(serverErrors.notAllowed.code); sendJson(res, serverErrors.notAllowed.body()); }]; const postMiddleware = !actions.create ? notAllowedMiddleware : [ validator(validations.create), controller.create ]; const getManyMiddleware = !actions.readMany ? notAllowedMiddleware : [ validator(validations.readMany), controller.read ]; const getOneMiddleware = !actions.readOne ? notAllowedMiddleware : [ validator(validations.readOne), controller.read ]; const patchMiddleware = !actions.update ? notAllowedMiddleware : [ validator(validations.update), controller.update ]; const deleteMiddleware = !actions.delete ? notAllowedMiddleware : [ validator(validations.delete), controller.delete ]; return { // The root location of this resource location: `/v${version}/${plural_form}`, // Four routes for the four CRUD ops routes: { post: {'/': postMiddleware}, get: { '/': getManyMiddleware, '/:id': getOneMiddleware }, patch: {'/:id': patchMiddleware}, delete: {'/:id': deleteMiddleware} } }; };
'use strict'; const validator = require('../util/validator'); const serverErrors = require('../util/server-errors'); const sendJson = require('../util/send-json'); module.exports = function({version, resource, controller}) { const {validations, plural_form, actions} = resource; const notAllowedMiddleware = [(req, res) => { res.status(serverErrors.notAllowed.code); sendJson(res, serverErrors.notAllowed.body()); }]; const postMiddleware = !actions.create ? notAllowedMiddleware : [ validator(validations.create), controller.create ]; const getManyMiddleware = !actions.readMany ? notAllowedMiddleware : [ validator(validations.readMany), controller.read ]; const getOneMiddleware = !actions.readOne ? notAllowedMiddleware : [ validator(validations.readOne), controller.read ]; const patchMiddleware = !actions.update ? notAllowedMiddleware : [ validator(validations.update), controller.update ]; const deleteMiddleware = !actions.delete ? notAllowedMiddleware : [ validator(validations.delete), controller.delete ]; return { // The root location of this resource location: `/v${version}/${plural_form}`, // Four routes for the four CRUD ops routes: { post: {'/': postMiddleware}, get: { '/': getOneMiddleware, '/:id': getManyMiddleware }, patch: {'/:id': patchMiddleware}, delete: {'/:id': deleteMiddleware} } }; };
Remove local vars path & path_plugin
<?php /** *@file * Contains \Drupal\AppConsole\Generator\CommandGenerator. */ namespace Drupal\AppConsole\Generator; class CommandGenerator extends Generator { /** * Generator Plugin Block * @param string $module Module name * @param string $command Command name * @param string $class_name class name for plugin block * @param array $container Access to container class */ public function generate($module, $command, $class_name, $container) { $parameters = [ 'module_name' => $module, 'command' => $command, 'name' => [ 'class' => $class_name, ], 'container' => $container, ]; $this->renderFile( 'module/command.php.twig', $path_plugin . '/'. $class_name .'.php', $parameters ); } }
<?php /** *@file * Contains \Drupal\AppConsole\Generator\CommandGenerator. */ namespace Drupal\AppConsole\Generator; class CommandGenerator extends Generator { /** * Generator Plugin Block * @param string $module Module name * @param string $command Command name * @param string $class_name class name for plugin block * @param array $container Access to container class */ public function generate($module, $command, $class_name, $container) { $path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module); $path_plugin = $path . '/src/Command'; $parameters = [ 'module_name' => $module, 'command' => $command, 'name' => [ 'class' => $class_name, ], 'container' => $container, ]; $this->renderFile( 'module/command.php.twig', $path_plugin . '/'. $class_name .'.php', $parameters ); } }
Fix adding missing helper library
<?php /** * Yii2 FancyBox Extension * @author Paul P <bigpaulie25ro@yahoo.com> * @license MIT */ namespace bigpaulie\fancybox; use yii\web\AssetBundle; class FancyBoxAsset extends AssetBundle{ public $sourcePath = '@bower/fancybox'; public $css = [ 'source/jquery.fancybox.css', 'source/helpers/jquery.fancybox-buttons.css', 'source/helpers/jquery.fancybox-thumbs.css', ]; public $js = [ 'source/jquery.fancybox.js', 'lib/jquery.mousewheel-3.0.6.pack.js', 'source/helpers/jquery.fancybox-buttons.js', 'source/helpers/jquery.fancybox-thumbs.js', 'source/helpers/jquery.fancybox-media.js', ]; public $depends = [ 'yii\web\JqueryAsset', ]; }
<?php /** * Yii2 FancyBox Extension * @author Paul P <bigpaulie25ro@yahoo.com> * @license MIT */ namespace bigpaulie\fancybox; use yii\web\AssetBundle; class FancyBoxAsset extends AssetBundle{ public $sourcePath = '@bower/fancybox'; public $css = [ 'source/jquery.fancybox.css', 'source/helpers/jquery.fancybox-buttons.css', 'source/helpers/jquery.fancybox-thumbs.css', ]; public $js = [ 'source/jquery.fancybox.js', 'lib/jquery.mousewheel-3.0.6.pack.js', 'source/helpers/jquery.fancybox-buttons.js', 'source/helpers/jquery.fancybox-thumbs.js', ]; public $depends = [ 'yii\web\JqueryAsset', ]; }
Fix logic and typo in sRPC
/* For license and copyright information please see LEGAL file in repository */ package srpc import "../syllab" /* ********************PAY ATTENTION:******************* We don't suggest use these 2 func instead use chaparkhane to autogenerate needed code before compile time and reduce runtime proccess to improve performance of the app and gain max performance from this protocol! */ // MarshalPacket use to encode automatically the value of s to the payload buffer. func MarshalPacket(id uint32, s interface{}) (p []byte, err error) { // encode s to p by syllab encoder p, err = syllab.Marshal(s, 4) // Set ServiceID to first of payload SetID(p, id) return } // UnMarshalPacket use to decode automatically payload and stores the result // in the value pointed to by s. func UnMarshalPacket(p []byte, expectedMinLen int, s interface{}) (id uint32, err error) { err = CheckPacket(p, expectedMinLen) if err != nil { return 0, err } // Get ErrorID from payload id = GetID(p) // decode payload to s by syllab encoder err = syllab.UnMarshal(p[4:], s) return }
/* For license and copyright information please see LEGAL file in repository */ package srpc import "../syllab" /* ********************PAY ATTENTION:******************* We don't suggest use these 2 func instead use chaparkhane to autogenerate needed code before compile time and reduce runtime proccess to improve performance of the app and gain max performance from this protocol! */ // MarshalPacket use to encode automatically the value of s to the payload buffer. func MarshalPacket(p []byte, id uint32, s interface{}) (err error) { // Set ServiceID to payload SetID(p, id) // encode s to p by syllab encoder err = syllab.MarshalSyllab(p[4:], s) return err } // UnMarshalPacket use to decode automatically payload and stores the result // in the value pointed to by s. func UnMarshalPacket(p []byte, expectedMinLen int, s interface{}) (id uint32, err error) { err = CheckPacket(p, expectedMinLen) if err != nil { return 0, err } // Get ErrorID from payload id = GetID(p) // decode payload to s by syllab encoder err = syllab.UnMarshalSyllab(p[4:], s) return id, err }
Fix to css causing unneeded scroll bar being visible.
import { injectGlobal } from 'styled-components'; /* eslint no-unused-expressions: 0 */ injectGlobal` html, body, #app { background-color: rgba(74, 74, 74, 0.5); } .cc-window { font-family: 'Lato', sans-serif !important; } .cc-compliance a, .cc-compliance a:link, .cc-compliance a:visited { transition: background-color 0.25s ease-in-out; color: #d3d3d3; } .cc-compliance a:hover, .cc-compliance a:active { cursor: pointer; background-color: #78c8b4 !important; } .cc-link, .cc-link:link, .cc-link:visited { transition: color 0.25s ease-in-out; cursor: pointer; color: #95a3b3 !important; } .cc-link:hover, .cc-link:active { color: #78c8b4 !important; } `;
import { injectGlobal } from 'styled-components'; /* eslint no-unused-expressions: 0 */ injectGlobal` html, body, #app { background-color: rgba(74, 74, 74, 0.5); } #app { overflow: scroll; } .cc-window { font-family: 'Lato', sans-serif !important; } .cc-compliance a, .cc-compliance a:link, .cc-compliance a:visited { transition: background-color 0.25s ease-in-out; color: #d3d3d3; } .cc-compliance a:hover, .cc-compliance a:active { cursor: pointer; background-color: #78c8b4 !important; } .cc-link, .cc-link:link, .cc-link:visited { transition: color 0.25s ease-in-out; cursor: pointer; color: #95a3b3 !important; } .cc-link:hover, .cc-link:active { color: #78c8b4 !important; } `;
Replace Japanese comment by English
<?php //URLの引数を見て、適切なphpコードを呼び出す。 //See URL Parameters and call appropriate code. if(isset($_GET['pid']) or isset($_GET['vid']) or isset($_GET['sid'])) { // Show object detail require_once('idetail.php'); } elseif(isset($_GET['aid'])) { // Show Album $_GET['id'] = $_GET['aid']; require_once('ialbum.php'); } elseif(isset($_GET['query'])) { // Search require_once('isearch.php'); } elseif(isset($_GET['type'])) { require_once('ialbum.php'); } elseif(isset($_GET['admin'])) { // Show Admin page require_once('psqlAlbum-admin/iadmin.php'); } elseif(isset($_GET['login'])) { // Show Login page require_once('psqlAlbum-admin/ilogin.php'); } elseif(isset($_GET['logout'])) { // Show Logout page require_once('psqlAlbum-admin/ilogout.php'); } elseif(empty($_GET)) { // Show album list (top page) require_once('iindex.php'); }
<?php //URLの引数を見て、適切なphpコードを呼び出す。 if(isset($_GET['pid']) or isset($_GET['vid']) or isset($_GET['sid'])) { //オブジェクト詳細表示 require_once('idetail.php'); } elseif(isset($_GET['aid'])) { //アルバム $_GET['id'] = $_GET['aid']; require_once('ialbum.php'); } elseif(isset($_GET['query'])) { //検索 require_once('isearch.php'); } elseif(isset($_GET['type'])) { require_once('ialbum.php'); } elseif(isset($_GET['admin'])) { // Show Admin page require_once('psqlAlbum-admin/iadmin.php'); } elseif(isset($_GET['login'])) { // Show Login page require_once('psqlAlbum-admin/ilogin.php'); } elseif(isset($_GET['logout'])) { // Show Logout page require_once('psqlAlbum-admin/ilogout.php'); } elseif(empty($_GET)) { //アルバム一覧(トップページ) require_once('iindex.php'); }
Add a List and Prop for better IFF compliance
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'List', 'Form', 'Prop'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class List(base.Chunk, encoding='ascii'): tag = fields.FixedString('LIST') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size) class Prop(base.Chunk, encoding='ascii'): tag = fields.FixedString('PROP') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
import collections import io from steel.fields.numbers import BigEndian from steel import fields from steel.chunks import base __all__ = ['Chunk', 'ChunkList', 'Form'] class Chunk(base.Chunk): id = fields.String(size=4, encoding='ascii') size = fields.Integer(size=4, endianness=BigEndian) payload = base.Payload(size=size) class ChunkList(base.ChunkList): def __init__(self, *args, **kwargs): # Just a simple override to default to a list of IFF chunks return super(ChunkList, self).__init__(Chunk, *args, **kwargs) class Form(base.Chunk, encoding='ascii'): tag = fields.FixedString('FORM') size = fields.Integer(size=4, endianness=BigEndian) id = fields.String(size=4) payload = base.Payload(size=size)
Fix master crash when concurrent read/write state
package http import ( "encoding/json" "log" "net/http" "github.com/leancloud/satori/master/g" "github.com/leancloud/satori/master/state" ) func addHandlers() { http.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) { state.StateLock.RLock() s, err := json.Marshal(state.State) state.StateLock.RUnlock() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Write(s) }) } func Start() { listen := g.Config().Http if listen == "" { return } addHandlers() s := &http.Server{ Addr: listen, MaxHeaderBytes: 1 << 30, } log.Println("starting REST API on", listen) log.Fatalln(s.ListenAndServe()) }
package http import ( "encoding/json" "log" "net/http" "github.com/leancloud/satori/master/g" "github.com/leancloud/satori/master/state" ) func addHandlers() { http.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) { s, err := json.Marshal(state.State) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Write(s) }) } func Start() { listen := g.Config().Http if listen == "" { return } addHandlers() s := &http.Server{ Addr: listen, MaxHeaderBytes: 1 << 30, } log.Println("starting REST API on", listen) log.Fatalln(s.ListenAndServe()) }
Improve error message for options validation
'use strict'; const { validate } = require('../validation'); // Validation for main options const validateOptions = function ({ options }) { const schema = { type: 'object', required: ['conf'], properties: { conf: { type: ['string', 'object'], }, onRequestError: { typeof: 'function', arity: 1, }, logger: { typeof: 'function', returnType: 'function', arity: 1, }, maxDataLength: { type: 'integer', minimum: 0, }, defaultPageSize: { type: 'integer', minimum: 0, }, maxPageSize: { type: 'integer', minimum: { $data: '1/defaultPageSize', }, }, }, additionalProperties: false, }; validate({ schema, data: options, reportInfo: { type: 'options', dataVar: 'options' } }); }; module.exports = { validateOptions, };
'use strict'; const { validate } = require('../validation'); // Validation for main options const validateOptions = function ({ options }) { const schema = { type: 'object', required: ['conf'], properties: { conf: { type: ['string', 'object'], }, onRequestError: { typeof: 'function', arity: 1, }, logger: { typeof: 'function', returnType: 'function', arity: 1, }, maxDataLength: { type: 'integer', minimum: 0, }, defaultPageSize: { type: 'integer', minimum: 0, }, maxPageSize: { type: 'integer', minimum: { $data: '1/defaultPageSize', }, }, }, additionalProperties: false, }; validate({ schema, data: options, reportInfo: { type: 'options' } }); }; module.exports = { validateOptions, };
Change level to log_level to be compatible with django
var winston = require('winston'); var moment = require('moment'); var getSecret = require('./docker-secrets').getDockerSecret; function getLogger(nconf) { var log_level = nconf.get('loglevel'); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ "log_level": log_level, "json": nconf.get('json'), "timestamp": function() { return moment(); } }) ] }); var logzio_token_file = nconf.get("LOGZIO_TOKEN_FILE"); if (logzio_token_file) { getSecret(logzio_token_file, (line) => { var logzioWinstonTransport = require('winston-logzio'); var loggerOptions = { token: line.trim(), host: 'listener.logz.io', }; logger.add(logzioWinstonTransport, loggerOptions); }) } return logger } module.exports.getLogger = getLogger;
var winston = require('winston'); var moment = require('moment'); var getSecret = require('./docker-secrets').getDockerSecret; function getLogger(nconf) { var log_level = nconf.get('loglevel'); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ "level": log_level, "json": nconf.get('json'), "timestamp": function() { return moment(); } }) ] }); var logzio_token_file = nconf.get("LOGZIO_TOKEN_FILE"); if (logzio_token_file) { getSecret(logzio_token_file, (line) => { var logzioWinstonTransport = require('winston-logzio'); var loggerOptions = { token: line.trim(), host: 'listener.logz.io', }; logger.add(logzioWinstonTransport, loggerOptions); }) } return logger } module.exports.getLogger = getLogger;
Use absolute paths for includes
<?php /** * metadata-validator * * @author Guy Halse http://orcid.org/0000-0002-9388-8592 * @copyright Copyright (c) 2016, SAFIRE - South African Identity Federation * @license https://github.com/safire-ac-za/metadata-validator/blob/master/LICENSE MIT License */ include_once(__DIR__ . '/ui/header.inc.php'); ?> <h2>SAML Metadata Validator</h2> <p>This validator applys very similar rules to SAFIRE's <a href="https://phph.<?php echo $domain ?>">metadata aggregator</a>. It is intended to allow people to check their own metadata before submitting it for inclusion in the federation registry. To test your metadata, copy-and-paste it into the box below (or upload your metadata file). Then click the [Validate!] button to begin.</p> <div id="validator"> <div id="metadata"></div> <div id="progress"></div> <div id="buttons"> <input id="validate" type="button" value="Validate!" class="button"> <div class="right"> <input id="mdurl" type="button" value="Fetch URL..." class="button"> <label for="mdfile">Upload file...</label> <input id="mdfile" type="file" multiple=""> </div> </div> <div id="results" class="hidden"></div> </div> <?php include_once(__DIR__ . '/ui/footer.inc.php'); ?>
<?php /** * metadata-validator * * @author Guy Halse http://orcid.org/0000-0002-9388-8592 * @copyright Copyright (c) 2016, SAFIRE - South African Identity Federation * @license https://github.com/safire-ac-za/metadata-validator/blob/master/LICENSE MIT License */ include_once('ui/header.inc.php'); ?> <h2>SAML Metadata Validator</h2> <p>This validator applys very similar rules to SAFIRE's <a href="https://phph.<?php echo $domain ?>">metadata aggregator</a>. It is intended to allow people to check their own metadata before submitting it for inclusion in the federation registry. To test your metadata, copy-and-paste it into the box below (or upload your metadata file). Then click the [Validate!] button to begin.</p> <div id="validator"> <div id="metadata"></div> <div id="progress"></div> <div id="buttons"> <input id="validate" type="button" value="Validate!" class="button"> <div class="right"> <input id="mdurl" type="button" value="Fetch URL..." class="button"> <label for="mdfile">Upload file...</label> <input id="mdfile" type="file" multiple=""> </div> </div> <div id="results" class="hidden"></div> </div> <?php include_once('ui/footer.inc.php'); ?>
Change image size limit down to 1mb per @ednapiranha
var bodyParser = require('body-parser') var dataUriToBuffer = require('data-uri-to-buffer') var express = require('express') var app = express() /** * This is your custom transform function * move it wherever, call it whatever */ var transform = require("./transformer") // Set up some Express settings app.use(bodyParser.json({ limit: '1mb' })) app.use(express.static(__dirname + '/public')) /** * Home route serves index.html file, and * responds with 200 by default for revisit */ app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html') }) /** * Service route is where the magic happens. */ app.post('/service', function(req, res) { var imgBuff = dataUriToBuffer(req.body.content.data) // Transform the image var transformed = transform(imgBuff) var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64') req.body.content.data = dataUri req.body.content.type = imgBuff.type res.json(req.body) }) var port = 8000 app.listen(port) console.log('server running on port: ', port)
var bodyParser = require('body-parser') var dataUriToBuffer = require('data-uri-to-buffer') var express = require('express') var app = express() var transform = require("./transformer") // Set up some Express settings app.use(bodyParser.json({ limit: '2mb' })) app.use(express.static(__dirname + '/public')) /** * Home route serves index.html file, and * responds with 200 by default for revisit */ app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html') }) /** * Service route is where the magic happens. */ app.post('/service', function(req, res) { var imgBuff = dataUriToBuffer(req.body.content.data) // Transform the image var transformed = transform(imgBuff) var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64') req.body.content.data = dataUri req.body.content.type = imgBuff.type res.json(req.body) }) var port = 8000 app.listen(port) console.log('server running on port: ', port)
Move syncthing config to version branch instead of master
'use strict'; module.exports = { SYNCTHING_BINARY: '0.11.25', SYNCTHING_IMAGE: '0.11.25', SYNCTHING_CONFIG: '0.10.3', SYNCTHING_DOWNLOAD_URL: { darwin: 'https://github.com/syncthing/syncthing/releases/download/' + 'v0.11.25/syncthing-macosx-amd64-v0.11.25.tar.gz', win32: 'https://github.com/syncthing/syncthing/releases/download/' + 'v0.11.25/syncthing-windows-amd64-v0.11.25.zip', linux: 'https://github.com/syncthing/syncthing/releases/download/' + 'v0.11.25/syncthing-linux-amd64-v0.11.25.tar.gz' }, SYNCTHING_CONFIG_URL: 'https://raw.githubusercontent.com/kalabox/' + 'kalabox/v0.10/dockerfiles/syncthing/config.xml' };
'use strict'; module.exports = { SYNCTHING_BINARY: '0.11.25', SYNCTHING_IMAGE: '0.11.25', SYNCTHING_CONFIG: '0.10.0', SYNCTHING_DOWNLOAD_URL: { darwin: 'https://github.com/syncthing/syncthing/releases/download/' + 'v0.11.25/syncthing-macosx-amd64-v0.11.25.tar.gz', win32: 'https://github.com/syncthing/syncthing/releases/download/' + 'v0.11.25/syncthing-windows-amd64-v0.11.25.zip', linux: 'https://github.com/syncthing/syncthing/releases/download/' + 'v0.11.25/syncthing-linux-amd64-v0.11.25.tar.gz' }, SYNCTHING_CONFIG_URL: 'https://raw.githubusercontent.com/kalabox/' + 'kalabox/master/dockerfiles/syncthing/config.xml' };
Set main log level when using only syslog
from logging.handlers import SysLogHandler import logging import sys syslogh = None def cleanup(): global syslogh if syslogh: syslogh.close() logging.shutdown() def get_logger(name, level=logging.INFO, verbose=False, debug=False, syslog=False): global syslogh log = logging.getLogger(name) if verbose or debug: log.setLevel(level if not debug else logging.DEBUG) channel = logging.StreamHandler(sys.stdout if debug else sys.stderr) channel.setFormatter(logging.Formatter('%(asctime)s - ' '%(levelname)s - %(message)s')) channel.setLevel(level if not debug else logging.DEBUG) log.addHandler(channel) if syslog: log.setLevel(level) syslogh = SysLogHandler(address='/dev/log') syslogh.setFormatter(logging.Formatter('%(message)s')) syslogh.setLevel(logging.INFO) log.addHandler(syslogh) return log
from logging.handlers import SysLogHandler import logging import sys syslogh = None def cleanup(): global syslogh if syslogh: syslogh.close() logging.shutdown() def get_logger(name, level=logging.INFO, verbose=False, debug=False, syslog=False): global syslogh log = logging.getLogger(name) if verbose or debug: log.setLevel(level if not debug else logging.DEBUG) channel = logging.StreamHandler(sys.stdout if debug else sys.stderr) channel.setFormatter(logging.Formatter('%(asctime)s - ' '%(levelname)s - %(message)s')) channel.setLevel(level if not debug else logging.DEBUG) log.addHandler(channel) if syslog: syslogh = SysLogHandler(address='/dev/log') syslogh.setFormatter(logging.Formatter('%(message)s')) syslogh.setLevel(logging.INFO) log.addHandler(syslogh) return log
Fix test detection for testSuite HTML runner This is a forgotten backport that should have belonged to ef0e7e49ac95f9b22cbdb9214d3032a69f23c720.
window.onload = function() { var framework = scala.scalajs.test.JasmineTestFramework(); framework.setTags("typedarray") // Load tests (we know we only export test modules, so we can use all exports) var testPackage = scala.scalajs.test; for (var pName in testPackage) { for (var testName in testPackage[pName]) { if (!(pName == "internal" && testName == "ConsoleTestOutput")) { var test = testPackage[pName][testName]; if (Object.getPrototypeOf(test.prototype) === Object.prototype) test(); } } } // Setup and run Jasmine var jasmineEnv = jasmine.getEnv(); var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function(spec) { return htmlReporter.specFilter(spec); }; jasmineEnv.execute(); framework.clearTags() };
window.onload = function() { var framework = scala.scalajs.test.JasmineTestFramework(); framework.setTags("typedarray") // Load tests (we know we only export test modules, so we can use all exports) var testPackage = scala.scalajs.test; for (var pName in testPackage) for (var testName in testPackage[pName]) if (!(pName == "internal" && testName == "ConsoleTestOutput")) testPackage[pName][testName](); // Setup and run Jasmine var jasmineEnv = jasmine.getEnv(); var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function(spec) { return htmlReporter.specFilter(spec); }; jasmineEnv.execute(); framework.clearTags() };
Fix destination paths for tests
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'dist/taggd.js', 'tests/functions.js', 'tests/units/*.js', 'tests/behavior/*.js', { pattern: 'tests/assets/**/*.jpg', watched: false, included: false, served: true, nocache: false, }, ], reporters: ['progress', 'coverage'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['PhantomJS'], singleRun: true, concurrency: Infinity, preprocessors: { 'dist/taggd.js': 'coverage', }, }); };
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'dest/taggd.js', 'tests/functions.js', 'tests/units/*.js', 'tests/behavior/*.js', { pattern: 'tests/assets/**/*.jpg', watched: false, included: false, served: true, nocache: false, }, ], reporters: ['progress', 'coverage'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['PhantomJS'], singleRun: true, concurrency: Infinity, preprocessors: { 'dest/taggd.js': 'coverage', }, }); };
Introduce format-string version for rethrow VE We currently have the ValidationException(String, Exception) constructor, which prevents us from overloading a format String version. This introduces a VE(Exception, String, args) so that VE(String, Exception) can be deprecated. Once gone, we'll introduce VE(String, args). PiperOrigin-RevId: 186782929 Change-Id: I851a2f84e3010db64da36b9533a629fe88a2793d
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.copybara; /** * Indicates that the configuration is wrong or some error attributable to the user happened. For * example wrong flag usage, errors in fields or errors that we discover during execution. */ public class ValidationException extends Exception { public ValidationException(String message) { super(message); } @Deprecated public ValidationException(String message, Throwable cause) { super(message, cause); } public ValidationException(Throwable cause, String message, Object... args) { super(String.format(message, args), cause); } public static void checkCondition(boolean condition, String format, Object... args) throws ValidationException { if (!condition) { throw new ValidationException(String.format(format, args)); } } }
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.copybara; /** * Indicates that the configuration is wrong or some error attributable to the user happened. For * example wrong flag usage, errors in fields or errors that we discover during execution. */ public class ValidationException extends Exception { public ValidationException(String message) { super(message); } public ValidationException(String message, Throwable cause) { super(message, cause); } public static void checkCondition(boolean condition, String format, Object... args) throws ValidationException { if (!condition) { throw new ValidationException(String.format(format, args)); } } }
Add API that allows users to retreive all recipes in the application
import userController from '../controllers/users'; import recipeController from '../controllers/recipes'; import Login from '../middleware/ensureLogin'; import User from '../middleware/isuser'; import recipeAdd from '../middleware/validateAddRecipe'; module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the lamest API for now', })); app.post('/api/v1/users/signup', userController.signUp); app.post('/api/v1/users/signin', userController.signIn); app.post('/api/v1/recipes/testAdd', Login.ensureLogin, User.isuser, recipeAdd, recipeController.addRecipe); app.put('/api/v1/recipe/:recipeId', Login.ensureLogin, User.isuser, recipeAdd, recipeController.modifyRecipe); app.get('/api/v1/recipes', recipeController.getRecipes); };
import userController from '../controllers/users'; import recipeController from '../controllers/recipes'; import Login from '../middleware/ensureLogin'; import User from '../middleware/isuser'; import recipeAdd from '../middleware/validateAddRecipe'; module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the lamest API for now', })); app.post('/api/v1/users/signup', userController.signUp); app.post('/api/v1/users/signin', userController.signIn); app.post('/api/v1/recipes/testAdd', Login.ensureLogin, User.isuser, recipeAdd, recipeController.addRecipe); app.put('/api/v1/recipe/:recipeId', Login.ensureLogin, User.isuser, recipeAdd, recipeController.modifyRecipe); app.get('/api/v1/recipes', Login.ensureLogin, User.isuser, recipeController.getRecipes); };
Fix HQL parameter is not numbered
package com.ksoichiro.task.repository; import com.ksoichiro.task.domain.Account; import com.ksoichiro.task.domain.Tag; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface TagRepository extends JpaRepository<Tag, Integer> { @Query("SELECT t FROM #{#entityName} t " + "WHERE t.account = ?1 ") Page<Tag> findByAccount(Account account, Pageable pageable); @Query("SELECT t from #{#entityName} t " + "WHERE t.id = ?1 " + "AND t.account = ?2") Tag findByIdAndAccount(Integer id, Account account); }
package com.ksoichiro.task.repository; import com.ksoichiro.task.domain.Account; import com.ksoichiro.task.domain.Tag; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface TagRepository extends JpaRepository<Tag, Integer> { @Query("SELECT t FROM #{#entityName} t " + "WHERE t.account = ? ") Page<Tag> findByAccount(Account account, Pageable pageable); @Query("SELECT t from #{#entityName} t " + "WHERE t.id = ?1 " + "AND t.account = ?2") Tag findByIdAndAccount(Integer id, Account account); }
Put buqeyemodel back in folder for multi-file use
from distutils.core import setup setup( name='buqeyemodel', packages=['buqeyemodel'], # py_modules=['buqeyemodel', 'pymc3_additions'], version='0.1', description='A statistical model of EFT convergence.', author='Jordan Melendez', author_email='jmelendez1992@gmail.com', license='MIT', url='https://github.com/jordan-melendez/buqeyemodel', download_url='https://github.com/jordan-melendez/buqeyemodel/archive/v0.1.tar.gz', keywords='EFT nuclear model gaussian process uncertainty quantification buqeyemodel buqeye', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics' ] )
from distutils.core import setup setup( name='buqeyemodel', # packages=['buqeyemodel'], py_modules=['buqeyemodel'], version='0.1', description='A statistical model of EFT convergence.', author='Jordan Melendez', author_email='jmelendez1992@gmail.com', license='MIT', url='https://github.com/jordan-melendez/buqeyemodel', download_url='https://github.com/jordan-melendez/buqeyemodel/archive/v0.1.tar.gz', keywords='EFT nuclear model gaussian process uncertainty quantification buqeyemodel buqeye', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics' ] )
Add remove temperatureSync from blacklist
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { navigationMiddleware } from './navigation'; import reducers from './reducers'; const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: [ 'pages', 'user', 'prescription', 'patient', 'finalise', 'form', 'prescriber', 'wizard', 'payment', 'insurance', 'dashboard', 'dispensary', 'modules', 'supplierCredit', ], }; const persistedReducer = persistReducer(persistConfig, reducers); const store = createStore(persistedReducer, {}, applyMiddleware(thunk, navigationMiddleware)); const persistedStore = persistStore(store); export { store, persistedStore };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { navigationMiddleware } from './navigation'; import reducers from './reducers'; const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: [ 'pages', 'user', 'prescription', 'patient', 'finalise', 'form', 'prescriber', 'wizard', 'payment', 'insurance', 'dashboard', 'dispensary', 'modules', 'supplierCredit', 'temperatureSync', ], }; const persistedReducer = persistReducer(persistConfig, reducers); const store = createStore(persistedReducer, {}, applyMiddleware(thunk, navigationMiddleware)); const persistedStore = persistStore(store); export { store, persistedStore };
Remove `autoDismiss` and add actions - `autoDismiss: false` can be done by making duration `null` in this case the snackbar won't dismiss until the button is clicked on the snackbar item - Now we can dispatch actions rather than commit mutations directly. Per Vue 'best practices'
export default { state: { isVisible: false, options: { text: '', // duration in ms, 0 indicates it should not automatically dismiss duration: 6000, actionText: '', actionCallback: null, }, }, getters: { snackbarIsVisible(state) { return state.isVisible; }, snackbarOptions(state) { return state.options; }, }, actions: { showSnackbar({ commit }, { text, duration, actionText, actionCallback }) { commit('CORE_CREATE_SNACKBAR', { text, duration, actionText, actionCallback }); }, clearSnackbar({ commit }) { commit('CORE_CLEAR_SNACKBAR'); } }, mutations: { CORE_CREATE_SNACKBAR(state, snackbarOptions = {}) { // reset state.isVisible = false; state.options = {}; // set new options state.isVisible = true; // options include text, duration, actionText, actionCallback, // hideCallback, bottomPosition state.options = snackbarOptions; }, CORE_CLEAR_SNACKBAR(state) { state.isVisible = false; state.options = {}; }, CORE_SET_SNACKBAR_TEXT(state, text) { state.options.text = text; }, }, };
export default { state: { isVisible: false, options: { text: '', autoDismiss: true, }, }, getters: { snackbarIsVisible(state) { return state.isVisible; }, snackbarOptions(state) { return state.options; }, }, mutations: { CORE_CREATE_SNACKBAR(state, snackbarOptions = {}) { // reset state.isVisible = false; state.options = {}; // set new options state.isVisible = true; // options include text, autoDismiss, duration, actionText, actionCallback, // hideCallback, bottomPosition state.options = snackbarOptions; }, CORE_CLEAR_SNACKBAR(state) { state.isVisible = false; state.options = {}; }, CORE_SET_SNACKBAR_TEXT(state, text) { state.options.text = text; }, }, };
Update p560m subarray sum in Python
from typing import List from collections import defaultdict class Solution: def subarraySum(self, nums: List[int], k: int) -> int: sum_count = defaultdict(int) sum_count[0] = 1 s, ans = 0, 0 for n in nums: s += n ans += sum_count[s - k] sum_count[s] += 1 return ans # TESTS tests = [ ([1], 0, 0), ([1, 1, 1], 2, 2), ([1, 2, 3, 4, 5], 11, 0), ([3, 4, 7, 2, -3, 1, 4, 2], 7, 4), ] for t in tests: sol = Solution() act = sol.subarraySum(t[0], t[1]) print("# of subarrays of", t[0], "sum to", t[1], "=>", act) assert act == t[2]
from typing import List from collections import defaultdict class Solution: def subarraySum(self, nums: List[int], k: int) -> int: sum_count = defaultdict(int) sum_count[0] = 1 s, ans = 0, 0 for n in nums: s += n if s - k in sum_count: ans += sum_count[s - k] sum_count[s] += 1 return ans # TESTS tests = [ ([1], 0, 0), ([1, 1, 1], 2, 2), ([1, 2, 3, 4, 5], 11, 0), ([3, 4, 7, 2, -3, 1, 4, 2], 7, 4), ] for t in tests: sol = Solution() act = sol.subarraySum(t[0], t[1]) print("# of subarrays of", t[0], "sum to", t[1], "=>", act) assert act == t[2]
Fix key events for chrome
$(function() { $('#manual').click(function() { $.get('/api/training/alone', function(data) { location.href = "/" + data.game.id + "?token=" + data.token + '&playUrl=' + encodeURIComponent(data.playUrl); }); }); function getParameterByName(name) { var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function shuffle(o) { //v1.0 for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } var url = getParameterByName('playUrl'); if (!url) return; $(document).on('keypress keydown', function(e) { if (e.keyCode == 37) move('west'); if (e.keyCode == 38) move('north'); if (e.keyCode == 39) move('east'); if (e.keyCode == 40) move('south'); e.preventDefault(); }); function move(dir) { $.ajax({ url: url, method: 'post', data: { dir: dir }, }); } });
$(function() { $('#manual').click(function() { $.get('/api/training/alone', function(data) { location.href = "/" + data.game.id + "?token=" + data.token + '&playUrl=' + encodeURIComponent(data.playUrl); }); }); function getParameterByName(name) { var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function shuffle(o) { //v1.0 for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } var url = getParameterByName('playUrl'); if (!url) return; $(document).keypress(function(e) { if (e.keyCode == 37) move('west'); if (e.keyCode == 38) move('north'); if (e.keyCode == 39) move('east'); if (e.keyCode == 40) move('south'); e.preventDefault(); }); function move(dir) { $.ajax({ url: url, method: 'post', data: { dir: dir }, }); } });
Fix broken edit/cancel subscription URL Fixes #651 TODO: add SubscriptionItemComponent tests
import { get, getWithDefault, computed } from "@ember/object"; import { alias } from "@ember/object/computed"; import { inject as service } from "@ember/service"; import { twitch as twitchConfig } from "config"; import ListItemComponent from "../-list-item/component"; import layout from "./template.hbs"; import "./styles.less"; const { subscription: { "edit-url": subscriptionEditUrl, "cancel-url": subscriptionCancelUrl } } = twitchConfig; export default ListItemComponent.extend({ nwjs: service(), layout, classNames: [ "subscription-item-component" ], attributeBindings: [ "style" ], channel: alias( "content.channel" ), style: computed( "channel.profile_banner", "channel.video_banner", function() { const banner = getWithDefault( this, "channel.profile_banner", getWithDefault( this, "channel.video_banner", "" ) ); return ( `background-image:url("${banner}")` ).htmlSafe(); }), openBrowser( url ) { const channel = get( this, "content.product.short_name" ); return this.nwjs.openBrowser( url, { channel }); }, actions: { edit() { return this.openBrowser( subscriptionEditUrl ); }, cancel() { return this.openBrowser( subscriptionCancelUrl ); } } });
import { get, getWithDefault, computed } from "@ember/object"; import { alias } from "@ember/object/computed"; import { inject as service } from "@ember/service"; import { twitch as twitchConfig } from "config"; import ListItemComponent from "../-list-item/component"; import layout from "./template.hbs"; import "./styles.less"; const { subscription: { "edit-url": subscriptionEditUrl, "cancel-url": subscriptionCancelUrl } } = twitchConfig; export default ListItemComponent.extend({ nwjs: service(), layout, classNames: [ "subscription-item-component" ], attributeBindings: [ "style" ], channel: alias( "content.channel" ), style: computed( "channel.profile_banner", "channel.video_banner", function() { const banner = getWithDefault( this, "channel.profile_banner", getWithDefault( this, "channel.video_banner", "" ) ); return ( `background-image:url("${banner}")` ).htmlSafe(); }), openBrowser( url ) { const channel = get( this, "product.short_name" ); return this.nwjs.openBrowser( url, { channel }); }, actions: { edit() { return this.openBrowser( subscriptionEditUrl ); }, cancel() { return this.openBrowser( subscriptionCancelUrl ); } } });
Add merge-conflict extension to postInstall
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const cp = require('child_process'); const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; function npmInstall(location) { const result = cp.spawnSync(npm, ['install'], { cwd: location , stdio: 'inherit' }); if (result.error || result.status !== 0) { process.exit(1); } } npmInstall('extensions'); // node modules shared by all extensions const extensions = [ 'vscode-api-tests', 'vscode-colorize-tests', 'json', 'configuration-editing', 'extension-editing', 'markdown', 'typescript', 'php', 'javascript', 'css', 'html', 'git', 'gulp', 'grunt', 'jake', 'merge-conflict' ]; extensions.forEach(extension => npmInstall(`extensions/${extension}`)); npmInstall(`build`); // node modules required for build
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const cp = require('child_process'); const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; function npmInstall(location) { const result = cp.spawnSync(npm, ['install'], { cwd: location , stdio: 'inherit' }); if (result.error || result.status !== 0) { process.exit(1); } } npmInstall('extensions'); // node modules shared by all extensions const extensions = [ 'vscode-api-tests', 'vscode-colorize-tests', 'json', 'configuration-editing', 'extension-editing', 'markdown', 'typescript', 'php', 'javascript', 'css', 'html', 'git', 'gulp', 'grunt', 'jake' ]; extensions.forEach(extension => npmInstall(`extensions/${extension}`)); npmInstall(`build`); // node modules required for build
Add tests for the performance logger
<?php namespace Larapress\Tests\Services; use Config; use DB; use Helpers; use Lang; use Log; use Mockery; use Larapress\Tests\TestCase; use Request; use View; class HelpersTest extends TestCase { /* |-------------------------------------------------------------------------- | Helpers::setPageTitle() Tests |-------------------------------------------------------------------------- | | Here is where you can test the Helpers::setPageTitle() method | */ public function test_can_set_page_title() { Config::shouldReceive('get')->with('larapress.names.cms')->once()->andReturn('foo')->shouldReceive('offsetGet'); Lang::shouldReceive('get')->with('general.bar')->once()->andReturn('bar'); View::shouldReceive('share')->with('title', 'foo | bar')->once(); Helpers::setPageTitle('bar'); } /* |-------------------------------------------------------------------------- | Helpers::logPerformance() Tests |-------------------------------------------------------------------------- | | Here is where you can test the Helpers::logPerformance() method | */ public function test_can_log_the_applications_performance() { Log::shouldReceive('info')->once(); Request::shouldReceive('getRequestUri')->once(); DB::shouldReceive('getQueryLog')->once(); Helpers::logPerformance(); } }
<?php namespace Larapress\Tests\Services; use Config; use Helpers; use Lang; use Mockery; use Larapress\Tests\TestCase; use View; class HelpersTest extends TestCase { /* |-------------------------------------------------------------------------- | Helpers::setPageTitle() Tests |-------------------------------------------------------------------------- | | Here is where you can test the Helpers::setPageTitle() method | */ public function test_can_set_page_title() { Config::shouldReceive('get')->with('larapress.names.cms')->once()->andReturn('foo')->shouldReceive('offsetGet'); Lang::shouldReceive('get')->with('general.bar')->once()->andReturn('bar'); View::shouldReceive('share')->with('title', 'foo | bar')->once(); Helpers::setPageTitle('bar'); } }
Remove "correct" word from test titles
const assert = require('assert'); const parse = require('../app/shared/database/parse'); describe('database', () => { describe('parse.js', () => { const testQuery = 'Learn something! @3+2w !'; it('should return task text', () => { assert(parse(testQuery).text === 'Learn something!'); }); it('should return starting point', () => { assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000); }); it('should return ending point', () => { assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000); }); it('should return importance', () => { assert(parse(testQuery).importance === 2); }); it('should return status', () => { assert(parse(testQuery).status === 0); }); }); });
const assert = require('assert'); const parse = require('../app/shared/database/parse'); describe('database', () => { describe('parse.js', () => { const testQuery = 'Learn something! @3+2w !'; it('should return correct task text', () => { assert(parse(testQuery).text === 'Learn something!'); }); it('should return correct starting point', () => { assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000); }); it('should return correct ending point', () => { assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000); }); it('should return correct importance', () => { assert(parse(testQuery).importance === 2); }); it('should return correct status', () => { assert(parse(testQuery).status === 0); }); }); });
Change factory, set input stream only when given
<?php namespace Aedart\Scaffold\Console\Style; use Aedart\Scaffold\Contracts\Console\Style\Factory; use Aedart\Scaffold\Testing\Console\Style\ExtendedStyle; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Extended Style Output Factory * * <br /> * * Intended for testing only! * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Scaffold\Console\Style */ class ExtendedStyleFactory implements Factory { /** * Input values * * @var resource|null */ protected $inputValues; /** * ExtendedStyleFactory constructor. * * @param resource|null $inputValues [optional] */ public function __construct($inputValues = null) { $this->inputValues = $inputValues; } /** * {@inheritdoc} */ public function make(InputInterface $input, OutputInterface $output) { $style = new ExtendedStyle($input, $output); // Set input steam (input values) if any are given if(isset($this->inputValues)){ $style->getQuestionHelper()->setInputStream( $this->inputValues ); } return $style; } }
<?php namespace Aedart\Scaffold\Console\Style; use Aedart\Scaffold\Contracts\Console\Style\Factory; use Aedart\Scaffold\Testing\Console\Style\ExtendedStyle; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class ExtendedStyleFactory implements Factory { /** * Input values * * @var resource */ protected $inputValues; /** * ExtendedStyleFactory constructor. * * @param resource $inputValues */ public function __construct($inputValues) { $this->inputValues = $inputValues; } /** * Make a new Symfony Style instance * * @param InputInterface $input * @param OutputInterface $output * * @return SymfonyStyle */ public function make(InputInterface $input, OutputInterface $output) { $style = new ExtendedStyle($input, $output); $style->getQuestionHelper()->setInputStream( $this->inputValues ); return $style; } }
Add timezone/geometry/tags to new Operators from Feed
import Ember from 'ember'; import DS from 'ember-data'; import _ from 'npm:lodash'; var Feed = DS.Model.extend({ onestop_id: Ember.computed.alias('id'), operators: DS.hasMany('operator', { async: true }), url: DS.attr('string'), feed_format: DS.attr('string'), license_name: DS.attr('string'), license_url: DS.attr('string'), license_use_without_attribution: DS.attr('string'), license_create_derived_product: DS.attr('string'), license_redistribute: DS.attr('string'), last_sha1: DS.attr('string'), last_fetched_at: DS.attr('string'), last_imported_at: DS.attr('string'), created_at: DS.attr('date'), updated_at: DS.attr('date'), geometry: DS.attr(), tags: DS.attr(), addOperator: function(operator) { this.get('operators').createRecord({ id: operator.onestop_id, name: operator.name, website: operator.website, timezone: operator.timezone, geometry: operator.geometry, tags: operator.tags }) } }); export default Feed;
import Ember from 'ember'; import DS from 'ember-data'; import _ from 'npm:lodash'; var Feed = DS.Model.extend({ onestop_id: Ember.computed.alias('id'), operators: DS.hasMany('operator', { async: true }), url: DS.attr('string'), feed_format: DS.attr('string'), license_name: DS.attr('string'), license_url: DS.attr('string'), license_use_without_attribution: DS.attr('string'), license_create_derived_product: DS.attr('string'), license_redistribute: DS.attr('string'), last_sha1: DS.attr('string'), last_fetched_at: DS.attr('string'), last_imported_at: DS.attr('string'), created_at: DS.attr('date'), updated_at: DS.attr('date'), geometry: DS.attr(), tags: DS.attr(), addOperator: function(operator) { this.get('operators').createRecord({ id: operator.onestop_id, name: operator.name, website: operator.website, onestop_id: operator.onestop_id, timezone: operator.timezone }) } }); export default Feed;
Change cluster data structure from list to dict
import networkx as nx from ClusterUtility import ClusterUtility class ConnectedComponents: """This is a class for connected component detection method to cluster event logs [1]_. References ---------- .. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log clustering, The 2nd International Seminar on Science and Technology, 2016, pp. 495-496. """ def __init__(self, graph): """This is a constructor for ConnectedComponent class. Parameters ---------- graph : graph A graph to be clustered. """ self.graph = graph def get_clusters(self): """This method find any connected component in a graph. A component represents a cluster and each component will be given a cluster identifier. This method heavily rely on the cosine similarity threshold to build an edge in a graph. Returns ------- clusters : dict[list] Dictionary of cluster list, where each list contains index (line number) of event log. """ clusters = {} cluster_id = 0 for components in nx.connected_components(self.graph): clusters[cluster_id] = components cluster_id += 1 ClusterUtility.set_cluster_id(self.graph, clusters) return clusters
import networkx as nx class ConnectedComponents: """This is a class for connected component detection method to cluster event logs [1]_. References ---------- .. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log clustering, in Proceedings of the International Seminar on Science and Technology, 2016, pp. 495-496. """ def __init__(self, g): """This is a constructor for ConnectedComponent class Parameters ---------- g : graph a graph to be clustered """ self.g = g def get_clusters(self): """This method find any connected component in a graph. A component represents a cluster and each component will be given a cluster identifier. Returns ------- clusters : list[list] List of cluster list, where each list contains index (line number) of event log. """ clusters = [] for components in nx.connected_components(self.g): clusters.append(components) cluster_id = 0 for cluster in clusters: for node in cluster: self.g.node[node]['cluster'] = cluster_id cluster_id += 1 return clusters
[1.4.x] Bump version to no longer claim to be 1.4.5 final.
VERSION = (1, 4, 6, 'alpha', 0) def get_version(version=None): """Derives a PEP386-compliant version number from VERSION.""" if version is None: version = VERSION assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases parts = 2 if version[2] == 0 else 3 main = '.'.join(str(x) for x in version[:parts]) sub = '' if version[3] == 'alpha' and version[4] == 0: # At the toplevel, this would cause an import loop. from django.utils.version import get_svn_revision svn_revision = get_svn_revision()[4:] if svn_revision != 'unknown': sub = '.dev%s' % svn_revision elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return main + sub
VERSION = (1, 4, 5, 'final', 0) def get_version(version=None): """Derives a PEP386-compliant version number from VERSION.""" if version is None: version = VERSION assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases parts = 2 if version[2] == 0 else 3 main = '.'.join(str(x) for x in version[:parts]) sub = '' if version[3] == 'alpha' and version[4] == 0: # At the toplevel, this would cause an import loop. from django.utils.version import get_svn_revision svn_revision = get_svn_revision()[4:] if svn_revision != 'unknown': sub = '.dev%s' % svn_revision elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return main + sub