text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
CHORE: Update badge to security icon
import React from 'react'; import { storiesOf } from '@storybook/react'; import { Badge } from '@appearhere/bloom'; storiesOf('Badge', module) .add('Default badge', () => <Badge>Soon</Badge>) .add('Primary badge', () => <Badge context="primary">New</Badge>) .add('Special badge', () => <Badge context="special">Verified</Badge>) .add('Hollow badge', () => <Badge hollow>Unknown</Badge>) .add('Primary hollow badge', () => ( <Badge context="primary" hollow> Place </Badge> )) .add('Special hollow badge', () => ( <Badge context="special" hollow> Collection </Badge> )) .add('With icon', () => ( <Badge icon="security"> 50% Discount </Badge> ));
import React from 'react'; import { storiesOf } from '@storybook/react'; import { Badge } from '@appearhere/bloom'; storiesOf('Badge', module) .add('Default badge', () => <Badge>Soon</Badge>) .add('Primary badge', () => <Badge context="primary">New</Badge>) .add('Special badge', () => <Badge context="special">Verified</Badge>) .add('Hollow badge', () => <Badge hollow>Unknown</Badge>) .add('Primary hollow badge', () => ( <Badge context="primary" hollow> Place </Badge> )) .add('Special hollow badge', () => ( <Badge context="special" hollow> Collection </Badge> )) .add('With icon', () => ( <Badge icon="price-tag"> 50% Discount </Badge> ));
Fix a few comments for wording.
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); // } /** * Define the routes for the application. * * @return void */ public function map() { $this->loadRoutesFrom(app_path('Http/routes.php')); } }
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, this is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Bootstrap any application services. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); // } /** * Define the routes for the application. * * @return void */ public function map() { $this->loadRoutesFrom(app_path('Http/routes.php')); } }
Use regexp.MustCompile() instead of regexp.Compile().
package cli_test import ( "regexp" "testing" ) func TestCreate(t *testing.T) { run(t, []Command{ { "apps", "", }, { "create acme-inc", "Created acme-inc.", }, }) } func TestApps(t *testing.T) { run(t, []Command{ { "create acme-inc", "Created acme-inc.", }, { "apps", "acme-inc Dec 31 17:01", }, }) } func TestAppInfo(t *testing.T) { run(t, []Command{ { "create acme-inc", "Created acme-inc.", }, { "info -a acme-inc", regexp.MustCompile("Name: acme-inc\nID: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n"), }, }) }
package cli_test import ( "regexp" "testing" ) func TestCreate(t *testing.T) { run(t, []Command{ { "apps", "", }, { "create acme-inc", "Created acme-inc.", }, }) } func TestApps(t *testing.T) { run(t, []Command{ { "create acme-inc", "Created acme-inc.", }, { "apps", "acme-inc Dec 31 17:01", }, }) } func TestAppInfo(t *testing.T) { regex, err := regexp.Compile("Name: acme-inc\nID: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n") if err != nil { t.Fatal(err) } run(t, []Command{ { "create acme-inc", "Created acme-inc.", }, { "info -a acme-inc", regex, }, }) }
Fix for naming of rascal metrics collections.
package org.ossmeter.metricprovider.rascal.trans.model; import com.googlecode.pongo.runtime.PongoDB; import com.mongodb.DB; // protected region custom-imports on begin // protected region custom-imports end public class RascalMetrics extends PongoDB { private final String collectionName; public RascalMetrics(DB db, String collectionName) { this.collectionName = collectionName; setDb(db); } protected MeasurementCollection measurements = null; // protected region custom-fields-and-methods on begin // protected region custom-fields-and-methods end public MeasurementCollection getMeasurements() { return measurements; } @Override public void setDb(DB db) { super.setDb(db); measurements = new MeasurementCollection(db.getCollection(collectionName)); pongoCollections.add(measurements); } }
package org.ossmeter.metricprovider.rascal.trans.model; import com.googlecode.pongo.runtime.PongoDB; import com.mongodb.DB; // protected region custom-imports on begin // protected region custom-imports end public class RascalMetrics extends PongoDB { private final String collectionName; public RascalMetrics(DB db, String collectionName) { this.collectionName = collectionName; setDb(db); } protected MeasurementCollection measurements = null; // protected region custom-fields-and-methods on begin // protected region custom-fields-and-methods end public MeasurementCollection getMeasurements() { return measurements; } @Override public void setDb(DB db) { super.setDb(db); measurements = new MeasurementCollection(db.getCollection("RascalMetrics.measurements")); pongoCollections.add(measurements); } }
feat: Allow configuration from environment variables
package main import ( "log" "os" "path/filepath" "strings" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/spf13/viper" "github.com/swordbeta/trello-burndown/pkg/server" "github.com/swordbeta/trello-burndown/pkg/trello" ) func init() { binaryPath, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { log.Fatal(err) } viper.AddConfigPath(binaryPath) viper.AddConfigPath(".") viper.SetConfigName("config") err = viper.ReadInConfig() if err != nil { log.Println(err) } viper.AutomaticEnv() viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) log.SetFlags(log.LstdFlags | log.Lshortfile) } func main() { go server.Start() trello.Start() }
package main import ( "log" "os" "path/filepath" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/spf13/viper" "github.com/swordbeta/trello-burndown/pkg/server" "github.com/swordbeta/trello-burndown/pkg/trello" ) func init() { binaryPath, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { log.Fatal(err) } viper.AddConfigPath(binaryPath) viper.AddConfigPath(".") viper.SetConfigName("config") err = viper.ReadInConfig() if err != nil { log.Fatalln(err) } log.SetFlags(log.LstdFlags | log.Lshortfile) } func main() { go server.Start() trello.Start() }
:arrow_up: Upgrade spec to gain parity with php
'use babel' import { serialize } from '../' module.exports = function() { const items = [] function debug(item: string, scope: Object = {}) { items.push(serialize(item, scope)) } class Test { serialize() { return 'asd' } } class TestTwo { constructor() { this.test = 'hi' } } class TestParent { serialize() { return serialize([new Test(), new TestTwo()]) } } class DeepUser {} debug(null) debug(1) debug(1.1) debug(1.7976931348623157E+308) debug('你好世界') debug([1, 2, 3, 4, 5]) debug(['Helló', 'World']) debug({ hey: 'hi' }) debug({ key: 'value', key2: 1 }) debug({ key: 1, key2: 'value2' }) debug({ key: '1value', key2: 'value2' }) debug({ key: 'value1', key2: 'value2' }) debug(new Test()) debug(new TestTwo()) debug(new TestParent()) debug(new DeepUser(), { 'Deep\\User': DeepUser, }) return items }
'use babel' import { serialize } from '../' module.exports = function() { const items = [] function debug(item: string, scope: Object = {}) { items.push(serialize(item, scope)) } class Test { serialize() { return 'asd' } } class TestTwo {} class TestParent { serialize() { return serialize([new Test(), new TestTwo()]) } } class DeepUser {} debug(null) debug(1) debug(1.1) debug(1.7976931348623157E+308) debug('你好世界') debug([1, 2, 3, 4, 5]) debug(['Helló', 'World']) debug({ hey: 'hi' }) debug({ key: 'value', key2: 1 }) debug({ key: 1, key2: 'value2' }) debug({ key: '1value', key2: 'value2' }) debug({ key: 'value1', key2: 'value2' }) debug(new Test()) debug(new TestTwo()) debug(new TestParent()) debug(new DeepUser(), { 'Deep\\User': DeepUser, }) return items }
Add riot.render.tag function to create raw tag
// allow to require('riot') var riot = module.exports = require(process.env.RIOT || require('path').resolve(__dirname, '../../riot')) var compiler = require('riot-compiler') // allow to require('riot').compile riot.compile = compiler.compile riot.parsers = compiler.parsers // allow to require('some.tag') require.extensions['.tag'] = function(module, filename) { var src = riot.compile(require('fs').readFileSync(filename, 'utf8')) module._compile( 'var riot = require(process.env.RIOT || "riot/riot.js");module.exports =' + src , filename) } // simple-dom helper var sdom = require('./sdom') riot.render = function(tagName, opts) { var tag = riot.render.tag(tagName, opts), html = sdom.serialize(tag.root) // unmount the tag avoiding memory leaks tag.unmount() return html } riot.render.dom = function(tagName, opts) { return riot.render.tag(tagName, opts).root } riot.render.tag = function(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag }
// allow to require('riot') var riot = module.exports = require(process.env.RIOT || require('path').resolve(__dirname, '../../riot')) var compiler = require('riot-compiler') // allow to require('riot').compile riot.compile = compiler.compile riot.parsers = compiler.parsers // allow to require('some.tag') require.extensions['.tag'] = function(module, filename) { var src = riot.compile(require('fs').readFileSync(filename, 'utf8')) module._compile( 'var riot = require(process.env.RIOT || "riot/riot.js");module.exports =' + src , filename) } // simple-dom helper var sdom = require('./sdom') function createTag(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag } riot.render = function(tagName, opts) { var tag = createTag(tagName, opts), html = sdom.serialize(tag.root) // unmount the tag avoiding memory leaks tag.unmount() return html } riot.render.dom = function(tagName, opts) { return createTag(tagName, opts).root }
HIde ACL menu for now. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<div class="navbar"> <div class="navbar-inner"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target="#authorizenav"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> {{ HTML::link(handles('orchestra::resources/authorize'), 'Authorize', array('class' => 'brand')) }} <div id="authorizenav" class="collapse nav-collapse"> <ul class="nav"> @if (Orchestra::acl()->can('manage-orchestra')) <li class="{{ URI::is('*/resources/authorize.roles*') ? 'active' : '' }}"> {{ HTML::link(handles('orchestra::resources/authorize.roles'), 'Roles') }} </li> @endif </ul> </div> </div> </div>
<div class="navbar"> <div class="navbar-inner"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target="#authorizenav"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> {{ HTML::link(handles('orchestra::resources/authorize'), 'Authorize', array('class' => 'brand')) }} <div id="authorizenav" class="collapse nav-collapse"> <ul class="nav"> @if (Orchestra::acl()->can('manage-orchestra')) <li class="{{ URI::is('*/resources/authorize.roles*') ? 'active' : '' }}"> {{ HTML::link(handles('orchestra::resources/authorize.roles'), 'Roles') }} </li> <li class="{{ URI::is('*/resources/authorize.acls*') ? 'active' : '' }}"> {{ HTML::link(handles('orchestra::resources/authorize.acls'), 'ACL') }} </li> @endif </ul> </div> </div> </div>
Fix undefined name of component Fix minor misspel, `Component` is `React.Component` now, should use name of `WrapperComponent` in `displayName`
import React, { Component } from 'react'; import { instanceOf, func } from 'prop-types'; import Cookies from 'universal-cookie'; import hoistStatics from 'hoist-non-react-statics'; export default function withCookies(WrapperComponent) { class Wrapper extends Component { static displayName = `withCookies(${WrapperComponent.displayName || WrapperComponent.name})`; static WrapperComponent = WrapperComponent; static propTypes = { wrappedComponentRef: func }; static contextTypes = { cookies: instanceOf(Cookies).isRequired }; constructor(props, context) { super(props); context.cookies.addChangeListener(this.onChange); } componentWillUnmount() { this.context.cookies.removeChangeListener(this.onChange); } onChange = () => { this.forceUpdate(); }; render() { const { wrappedComponentRef, ...remainingProps } = this.props; const allCookies = this.context.cookies.getAll(); return ( <WrapperComponent {...remainingProps} cookies={this.context.cookies} allCookies={allCookies} ref={wrappedComponentRef} /> ); } } return hoistStatics(Wrapper, WrapperComponent, { WrappedComponent: true }); }
import React, { Component } from 'react'; import { instanceOf, func } from 'prop-types'; import Cookies from 'universal-cookie'; import hoistStatics from 'hoist-non-react-statics'; export default function withCookies(WrapperComponent) { class Wrapper extends Component { static displayName = `withCookies(${Component.displayName || Component.name})`; static WrapperComponent = WrapperComponent; static propTypes = { wrappedComponentRef: func }; static contextTypes = { cookies: instanceOf(Cookies).isRequired }; constructor(props, context) { super(props); context.cookies.addChangeListener(this.onChange); } componentWillUnmount() { this.context.cookies.removeChangeListener(this.onChange); } onChange = () => { this.forceUpdate(); }; render() { const { wrappedComponentRef, ...remainingProps } = this.props; const allCookies = this.context.cookies.getAll(); return ( <WrapperComponent {...remainingProps} cookies={this.context.cookies} allCookies={allCookies} ref={wrappedComponentRef} /> ); } } return hoistStatics(Wrapper, WrapperComponent, { WrappedComponent: true }); }
Update to new storage payload api
""" Command that will allow for a user to inject triples into a database. """ from rhobot.components.commands.base_command import BaseCommand from rdflib.namespace import FOAF, RDF from rhobot.namespace import RHO from rhobot.components.storage import ResultPayload, ResultCollectionPayload import logging logger = logging.getLogger(__name__) class FindOwner(BaseCommand): def initialize_command(self): super(FindOwner, self).initialize_command() logger.info('Initialize Command') self._initialize_command(identifier='find_owner', name='Find Owner', additional_dependencies={'rho_bot_storage_client'}) def command_start(self, request, initial_session): """ Provide the configuration details back to the requester and end the command. :param request: :param initial_session: :return: """ storage = self.xmpp['rho_bot_storage_client'].create_payload() storage.add_type(FOAF.Person, RHO.Owner) results = self.xmpp['rho_bot_storage_client'].find_nodes(storage) initial_session['payload'] = results.populate_payload() initial_session['next'] = None initial_session['has_next'] = False return initial_session find_owner = FindOwner
""" Command that will allow for a user to inject triples into a database. """ from rhobot.components.commands.base_command import BaseCommand from rdflib.namespace import FOAF, RDF from rhobot.namespace import RHO from rhobot.components.storage import ResultPayload, ResultCollectionPayload import logging logger = logging.getLogger(__name__) class FindOwner(BaseCommand): def initialize_command(self): super(FindOwner, self).initialize_command() logger.info('Initialize Command') self._initialize_command(identifier='find_owner', name='Find Owner', additional_dependencies={'rho_bot_storage_client'}) def command_start(self, request, initial_session): """ Provide the configuration details back to the requester and end the command. :param request: :param initial_session: :return: """ storage = self.xmpp['rho_bot_storage_client'].create_payload() storage.add_type(FOAF.Person, RHO.Owner) results = self.xmpp['rho_bot_storage_client'].find_nodes(storage) initial_session['payload'] = results._populate_payload() initial_session['next'] = None initial_session['has_next'] = False return initial_session find_owner = FindOwner
Enable CoreOS Install to Disk
// Copyright 2015, EMC, Inc. module.exports = { friendlyName: 'Install CoreOS', injectableName: 'Task.Os.Install.CoreOS', implementsTask: 'Task.Base.Os.Install', options: { // NOTE: user/pass aren't used by the coreos installer at the moment, // but they are required values username: 'root', password: 'root', profile: 'install-coreos.ipxe', comport: 'ttyS0', hostname: 'coreos-node', installDisk: '/dev/sda', completionUri: 'pxe-cloud-config.yml' }, properties: { os: { linux: { distribution: 'coreos' } } } };
// Copyright 2015, EMC, Inc. module.exports = { friendlyName: 'Install CoreOS', injectableName: 'Task.Os.Install.CoreOS', implementsTask: 'Task.Base.Os.Install', options: { // NOTE: user/pass aren't used by the coreos installer at the moment, // but they are required values username: 'root', password: 'root', profile: 'install-coreos.ipxe', comport: 'ttyS0', hostname: 'coreos-node', completionUri: 'pxe-cloud-config.yml' }, properties: { os: { linux: { distribution: 'coreos' } } } };
Fix Bug for Nonetype ROI
import cv2 import numpy as np import plantcv as pcv def white_balance(img, roi=None): """Corrects the exposure of an image based on its histogram. Inputs: img - A grayscale image on which to perform the correction roi - A list of 4 points (x, y, width, height) that form the rectangular ROI of the white color standard. If a list of 4 points is not given, whole image will be used. Returns: img - Image after exposure correction """ # Finds histogram of roi if valid roi is given. Otherwise, finds histogram of entire image if roi is not None and len(roi) == 4: hist = cv2.calcHist(tuple(img[roi[1]:roi[1]+roi[3], roi[0]:roi[0]+roi[2]]), [0], None, [256], [0, 256]) else: hist = cv2.calcHist(tuple(img), [0], None, [256], [0, 256]) # Creates histogram of original image # Calculates index of maximum of histogram and finds alpha based on the peak hmax = np.argmax(hist) alpha = 255 / float(hmax) # Converts values greater than hmax to 255 and scales all others by alpha img = np.asarray(np.where(img <= hmax, np.multiply(alpha, img), 255), np.uint8) return img
import cv2 import numpy as np import plantcv as pcv def white_balance(img, roi=None): """Corrects the exposure of an image based on its histogram. Inputs: img - A grayscale image on which to perform the correction roi - A list of 4 points (x, y, width, height) that form the rectangular ROI of the white color standard. If a list of 4 points is not given, whole image will be used. Returns: img - Image after exposure correction """ # Finds histogram of roi if valid roi is given. Otherwise, finds histogram of entire image if len(roi) != 4: hist = cv2.calcHist(tuple(img), [0], None, [256], [0, 256]) # Creates histogram of original image else: hist = cv2.calcHist(tuple(img[roi[1]:roi[1]+roi[3], roi[0]:roi[0]+roi[2]]), [0], None, [256], [0, 256]) # Calculates index of maximum of histogram and finds alpha based on the peak hmax = np.argmax(hist) alpha = 255 / float(hmax) # Converts values greater than hmax to 255 and scales all others by alpha img = np.asarray(np.where(img <= hmax, np.multiply(alpha, img), 255), np.uint8) return img
Make this in practice unreachable code work on Py2
from __future__ import absolute_import, division, unicode_literals from collections import Mapping class Trie(Mapping): """Abstract base class for tries""" def keys(self, prefix=None): keys = super(Trie, self).keys() if prefix is None: return set(keys) # Python 2.6: no set comprehensions return set([x for x in keys if x.startswith(prefix)]) def has_keys_with_prefix(self, prefix): for key in self.keys(): if key.startswith(prefix): return True return False def longest_prefix(self, prefix): if prefix in self: return prefix for i in range(1, len(prefix) + 1): if prefix[:-i] in self: return prefix[:-i] raise KeyError(prefix) def longest_prefix_item(self, prefix): lprefix = self.longest_prefix(prefix) return (lprefix, self[lprefix])
from __future__ import absolute_import, division, unicode_literals from collections import Mapping class Trie(Mapping): """Abstract base class for tries""" def keys(self, prefix=None): keys = super().keys() if prefix is None: return set(keys) # Python 2.6: no set comprehensions return set([x for x in keys if x.startswith(prefix)]) def has_keys_with_prefix(self, prefix): for key in self.keys(): if key.startswith(prefix): return True return False def longest_prefix(self, prefix): if prefix in self: return prefix for i in range(1, len(prefix) + 1): if prefix[:-i] in self: return prefix[:-i] raise KeyError(prefix) def longest_prefix_item(self, prefix): lprefix = self.longest_prefix(prefix) return (lprefix, self[lprefix])
Add test annotation again, ignore overrides this. git-svn-id: 6e5f6f61bd1b925b71fe8065f445f9178a317ca5@353 7701cf9b-ed3c-0410-a7c3-1ff289697e89
package com.crawljax.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import org.junit.Ignore; import org.junit.Test; public class PrettyHTMLTest { private static final String TESTFILE = "src/test/java/com/crawljax/util/tuduDombefore.html"; private static final String CONTROLFILE = "src/test/java/com/crawljax/util/tuduDombefore.html.tidy"; @Ignore @Test public void prettifyHTML() { String testdom = Helper.getContent(new File(TESTFILE)); String controldom = Helper.getContent(new File(CONTROLFILE)); assertNotNull("File should be read", testdom); assertNotNull("File should be read", controldom); testdom = PrettyHTML.prettyHTML(testdom); assertEquals(controldom, testdom); } }
package com.crawljax.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import org.junit.Ignore; public class PrettyHTMLTest { private static final String TESTFILE = "src/test/java/com/crawljax/util/tuduDombefore.html"; private static final String CONTROLFILE = "src/test/java/com/crawljax/util/tuduDombefore.html.tidy"; @Ignore public void prettifyHTML() { String testdom = Helper.getContent(new File(TESTFILE)); String controldom = Helper.getContent(new File(CONTROLFILE)); assertNotNull("File should be read", testdom); assertNotNull("File should be read", controldom); testdom = PrettyHTML.prettyHTML(testdom); assertEquals(controldom, testdom); } }
Update choices descriptions in FileTypes
class ExportEvents: """The different csv events types.""" EXPORT_PENDING = "export_pending" EXPORT_SUCCESS = "export_success" EXPORT_FAILED = "export_failed" EXPORT_DELETED = "export_deleted" EXPORTED_FILE_SENT = "exported_file_sent" CHOICES = [ (EXPORT_PENDING, "Data export was started."), (EXPORT_SUCCESS, "Data export was completed successfully."), (EXPORT_FAILED, "Data export failed."), (EXPORT_DELETED, "Export file was started."), ( EXPORTED_FILE_SENT, "Email with link to download csv file was sent to the customer.", ), ] class FileTypes: CSV = "csv" XLSX = "xlsx" CHOICES = [ (CSV, "Plain CSV file."), (XLSX, "Excel XLSX file."), ]
class ExportEvents: """The different csv events types.""" EXPORT_PENDING = "export_pending" EXPORT_SUCCESS = "export_success" EXPORT_FAILED = "export_failed" EXPORT_DELETED = "export_deleted" EXPORTED_FILE_SENT = "exported_file_sent" CHOICES = [ (EXPORT_PENDING, "Data export was started."), (EXPORT_SUCCESS, "Data export was completed successfully."), (EXPORT_FAILED, "Data export failed."), (EXPORT_DELETED, "Export file was started."), ( EXPORTED_FILE_SENT, "Email with link to download csv file was sent to the customer.", ), ] class FileTypes: CSV = "csv" XLSX = "xlsx" CHOICES = [ (CSV, "Plain csv file."), (XLSX, "Excel .xlsx file."), ]
Work around not being able to set res.body For #268
var CONTENT_TYPE = 'Content-Type'; var JSON_CONTENT_TYPE = 'application/json'; var _ = require('../../../../utils/mindash'); module.exports = { id: 'parseJSON', after: function (res) { if (isJson(res)) { return res.json().then(function (body) { try { res.body = body; } catch (e) { if (e instanceof TypeError) { // Workaround for Chrome 43+ where Response.body is not settable. Object.defineProperty(res, 'body', {value: body}); } else { throw e; } } return res; }); } return res; } }; function isJson(res) { var contentTypes = res.headers.get(CONTENT_TYPE); if (!_.isArray(contentTypes)) { if (contentTypes === undefined || contentTypes === null) { contentTypes = []; } else { contentTypes = [contentTypes]; } } return _.any(contentTypes, function (contentType) { return contentType.indexOf(JSON_CONTENT_TYPE) !== -1; }); }
var CONTENT_TYPE = 'Content-Type'; var JSON_CONTENT_TYPE = 'application/json'; var _ = require('../../../../utils/mindash'); module.exports = { id: 'parseJSON', after: function (res) { if (isJson(res)) { return res.json().then(function (body) { res.body = body; return res; }); } return res; } }; function isJson(res) { var contentTypes = res.headers.get(CONTENT_TYPE); if (!_.isArray(contentTypes)) { if (contentTypes === undefined || contentTypes === null) { contentTypes = []; } else { contentTypes = [contentTypes]; } } return _.any(contentTypes, function (contentType) { return contentType.indexOf(JSON_CONTENT_TYPE) !== -1; }); }
Update script file name. Laravel Elixir now outputs scripts using their source name, rather than renaming to `bundle.js`, so we need to update our script tag.
<script type="text/javascript" charset="utf-8"> function loadScript(src) { var async = arguments[1] === undefined ? true : arguments[1]; var ref = window.document.getElementsByTagName('script')[0]; var script = window.document.createElement('script'); script.src = src; if(async) script.async = async; ref.parentNode.insertBefore(script, ref); } var supportsMQ = window.matchMedia && window.matchMedia( "only all" ) !== null && window.matchMedia( "only all" ).matches; if (!supportsMQ) { loadScript('{{ asset('assets/vendor/respond.min.js') }}', false) } if ('querySelector' in document && 'addEventListener' in window) { loadScript('{{ asset('js/app.js') }}'); } </script> <!--[if lte IE 8]> <script type="text/javascript" charset="utf-8" src="{{ asset('assets/vendor/html5shiv.min.js') }}"></script> <![endif]-->
<script type="text/javascript" charset="utf-8"> function loadScript(src) { var async = arguments[1] === undefined ? true : arguments[1]; var ref = window.document.getElementsByTagName('script')[0]; var script = window.document.createElement('script'); script.src = src; if(async) script.async = async; ref.parentNode.insertBefore(script, ref); } var supportsMQ = window.matchMedia && window.matchMedia( "only all" ) !== null && window.matchMedia( "only all" ).matches; if (!supportsMQ) { loadScript('{{ asset('assets/vendor/respond.min.js') }}', false) } if ('querySelector' in document && 'addEventListener' in window) { loadScript('{{ asset('js/bundle.js') }}'); } </script> <!--[if lte IE 8]> <script type="text/javascript" charset="utf-8" src="{{ asset('assets/vendor/html5shiv.min.js') }}"></script> <![endif]-->
Use py_modules and not packages
import os from distutils.core import setup requirements = map(str.strip, open('requirements.txt').readlines()) setup( name='py_eventsocket', version='0.1.4', author="Aaron Westendorf", author_email="aaron@agoragames.com", url='https://github.com/agoragames/py-eventsocket', license='LICENSE.txt', py_modules = ['eventsocket'], description='Easy to use TCP socket based on libevent', install_requires = requirements, long_description=open('README.rst').read(), keywords=['socket', 'event'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Communications", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', 'Topic :: Software Development :: Libraries' ] )
import os from distutils.core import setup requirements = map(str.strip, open('requirements.txt').readlines()) setup( name='py_eventsocket', version='0.1.4', author="Aaron Westendorf", author_email="aaron@agoragames.com", packages = ['eventsocket'], url='https://github.com/agoragames/py-eventsocket', license='LICENSE.txt', description='Easy to use TCP socket based on libevent', install_requires = requirements, long_description=open('README.rst').read(), keywords=['socket', 'event'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Communications", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', 'Topic :: Software Development :: Libraries' ] )
Comment fix and removed trim() because it is really not this method's job.
package com.untamedears.mustercull; /** * The method used to cull the mobs * @author Celdecea */ enum CullType { /** * Uses Bukkit events to deny a spawn. */ SPAWN, /** * Uses Bukkit events to prevent a spawner from operating. */ SPAWNER, /** * Uses damage on mobs in crowded chunks. */ DAMAGE; /** * Returns a CullType representing the name provided. * @param name A case-insensitive name to compare to. * @return The CullType representing the name provided, or null. */ public static CullType fromName(String name) { if (name == null) { return null; } for (CullType culling : values()) { if (0 == name.compareToIgnoreCase(culling.name())) { return culling; } } return null; } }
package com.untamedears.mustercull; /** * The method used to cull the mobs * @author Celdecea */ enum CullType { /** * Uses Bukkit events to deny a spawn. */ SPAWN, /** * Uses Bukkit events to prevent a spawner from operating. */ SPAWNER, /** * Uses damage on mobs in crowded chunks. */ DAMAGE; /** * Returns a CullType representing the name provided. * @param name A case-sensitive name to compare to. * @return The CullType representing the name provided. */ public static CullType fromName(String name) { if (name == null) { return null; } name = name.trim(); for (CullType culling : values()) { if (0 == name.compareToIgnoreCase(culling.name())) { return culling; } } return null; } }
Return output from ExecCmd function
package scipipe import ( // "github.com/go-errors/errors" //"os" "os" "os/exec" re "regexp" ) func ExecCmd(cmd string) string { Info.Println("Executing command: ", cmd) combOutput, err := exec.Command("bash", "-lc", cmd).CombinedOutput() if err != nil { Error.Println("Could not execute command `" + cmd + "`: " + string(combOutput)) os.Exit(128) } return string(combOutput) } func Check(err error) { if err != nil { panic(err) } } func copyMapStrStr(m map[string]string) (nm map[string]string) { nm = make(map[string]string) for k, v := range m { nm[k] = v } return nm } // Return the regular expression used to parse the place-holder syntax for in-, out- and // parameter ports, that can be used to instantiate a SciProcess. func getShellCommandPlaceHolderRegex() *re.Regexp { r, err := re.Compile("{(o|os|i|is|p):([^{}:]+)}") Check(err) return r }
package scipipe import ( // "github.com/go-errors/errors" //"os" "os/exec" re "regexp" ) func ExecCmd(cmd string) { Info.Println("Executing command: ", cmd) combOutput, err := exec.Command("bash", "-lc", cmd).CombinedOutput() if err != nil { Error.Println("Could not execute command `" + cmd + "`: " + string(combOutput)) } } func Check(err error) { if err != nil { panic(err) } } func copyMapStrStr(m map[string]string) (nm map[string]string) { nm = make(map[string]string) for k, v := range m { nm[k] = v } return nm } // Return the regular expression used to parse the place-holder syntax for in-, out- and // parameter ports, that can be used to instantiate a SciProcess. func getShellCommandPlaceHolderRegex() *re.Regexp { r, err := re.Compile("{(o|os|i|is|p):([^{}:]+)}") Check(err) return r }
Test promises instead of promiseList.
var assert = require("assert"); var {defer, promises} = require("ringo/promise"); exports.testPromiseList = function() { var d1 = defer(), d2 = defer(), d3 = defer(); var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise l.then(function(result) { assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]); }, function(error) { assert.fail("promiseList called error callback"); }); d2.resolve(1); d3.resolve("error", true); d1.resolve("ok"); }; // start the test runner if we're called directly from command line if (require.main == module.id) { system.exit(require('test').run(exports)); }
var assert = require("assert"); var {defer, promiseList} = require("ringo/promise"); exports.testPromiseList = function() { var d1 = defer(), d2 = defer(), d3 = defer(); var l = promiseList(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise l.then(function(result) { assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]); }, function(error) { assert.fail("promiseList called error callback"); }); d2.resolve(1); d3.resolve("error", true); d1.resolve("ok"); }; // start the test runner if we're called directly from command line if (require.main == module.id) { system.exit(require('test').run(exports)); }
Fix method name to not clash with regular global name
<?php declare(strict_types=1); namespace Becklyn\RadBundle\Model; /** * Trait for doctrine models that use a sortable handler */ trait SortableModelTrait { /** * Applies the sort order mapping as provided in the parameters. * * The model should wrap this method and use type hints on the $where parameter entries. * * @param array $sortMapping * @param array $where * * @return bool */ protected function flushSortOrderMapping (array $sortMapping, array $where) : bool { if ($this->sortableHandler->applySorting($sortMapping, $where)) { $this->flush(); return true; } return false; } }
<?php declare(strict_types=1); namespace Becklyn\RadBundle\Model; /** * Trait for doctrine models that use a sortable handler */ trait SortableModelTrait { /** * Applies the sort order mapping as provided in the parameters. * * The model should wrap this method and use type hints on the $where parameter entries. * * @param array $sortMapping * @param array $where * * @return bool */ protected function applySortOrderMapping (array $sortMapping, array $where) : bool { if ($this->sortableHandler->applySorting($sortMapping, $where)) { $this->flush(); return true; } return false; } }
Remove useless property in exception class
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * @author Nils Adermann <naderman@naderman.de> */ class SolverBugException extends \RuntimeException { public function __construct($message) { parent::__construct( $message."\nThis exception was most likely caused by a bug in Composer.\n". "Please report the command you ran, the exact error you received, and your composer.json on https://github.com/composer/composer/issues - thank you!\n"); } }
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; /** * @author Nils Adermann <naderman@naderman.de> */ class SolverBugException extends \RuntimeException { protected $problems; public function __construct($message) { parent::__construct( $message."\nThis exception was most likely caused by a bug in Composer.\n". "Please report the command you ran, the exact error you received, and your composer.json on https://github.com/composer/composer/issues - thank you!\n"); } }
Fix errors format to when creating a DS.InvalidError object
import callbacks from 'ember-encore/mixins/adapter-callbacks'; export default DS.RESTAdapter.extend(callbacks, { defaultSerializer: '-encore', pathForType: function(type) { return Ember.String.pluralize(Ember.String.underscore(type)); }, ajaxError: function(jqXHR) { var error = this._super(jqXHR); var data = JSON.parse(jqXHR.responseText); if (jqXHR && jqXHR.status === 422) { var errors = data.errors.reduce(function(memo, errorGroup) { memo[errorGroup.field] = errorGroup.types; return memo; }, {}); return new DS.InvalidError(errors); } else { return error; } } });
import callbacks from 'ember-encore/mixins/adapter-callbacks'; export default DS.RESTAdapter.extend(callbacks, { defaultSerializer: '-encore', pathForType: function(type) { return Ember.String.pluralize(Ember.String.underscore(type)); }, ajaxError: function(jqXHR) { var error = this._super(jqXHR); var data = JSON.parse(jqXHR.responseText); if (jqXHR && jqXHR.status === 422) { var errors = data.errors.reduce(function(memo, errorGroup) { memo[errorGroup.field] = errorGroup.types[0]; return memo; }, {}); return new DS.InvalidError(errors); } else { return error; } } });
Fix JSONP function name extraction
var vm = require('vm') var Headers = require('@http/headers') var requestOptions = require('../config/options') exports.filter = function (options) { var result = {} for (var key in options) { if (requestOptions.indexOf(key) === -1) { result[key] = options[key] } } result.headers = result.headers.toObject() return result } exports.response = function (res) { res.headers = new Headers(res.headers) } exports.rfc3986 = function (str) { return str.replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } exports.isJSON = function (res) { var type = res.headers.get('content-type') , encoding = res.headers.get('content-encoding') return (/json|javascript/.test(type) || /json/.test(encoding)) } exports.isJSONP = function (body) { return /^\w+[^(]*\(.+\)/.test(body) } exports.parseJSONP = function (body) { var func = body.replace(/(^\w+[^(]*).*/, '$1') var obj = {} obj[func] = function (json) {return json} var sandbox = vm.createContext(obj) var json = vm.runInContext(body, sandbox) // either object or string return json }
var vm = require('vm') var Headers = require('@http/headers') var requestOptions = require('../config/options') exports.filter = function (options) { var result = {} for (var key in options) { if (requestOptions.indexOf(key) === -1) { result[key] = options[key] } } result.headers = result.headers.toObject() return result } exports.response = function (res) { res.headers = new Headers(res.headers) } exports.rfc3986 = function (str) { return str.replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } exports.isJSON = function (res) { var type = res.headers.get('content-type') , encoding = res.headers.get('content-encoding') return (/json|javascript/.test(type) || /json/.test(encoding)) } exports.isJSONP = function (body) { return /^\w+[^(]*\(.+\)/.test(body) } exports.parseJSONP = function (body) { var func = body.replace(/(^\w+[^(]*)/, '$1') var obj = {} obj[func] = function (json) {return json} var sandbox = vm.createContext(obj) var json = vm.runInContext(body, sandbox) // either object or string return json }
Fix running tests form command line
from cfgen import cfgen from nose.tools import assert_equals import os def setup(): test_root_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(test_root_dir + "/test_dir") clean() def test_cmd_write(): cfgen.cmd_write("test.cfg") with open("test.cfg") as actual, open("test.cfg.expected") as expected: actual_lines = actual.read().splitlines() expected_lines = expected.read().splitlines() assert_equals(len(actual_lines), len(expected_lines)) for line_number in range(0, len(actual_lines)): assert_equals(actual_lines[line_number], expected_lines[line_number]) def clean(): if os.path.isfile("test.cfg"): os.remove("test.cfg") if os.path.isfile("test.cfg.metaconfig.cache"): os.remove("test.cfg.metaconfig.cache")
from cfgen import cfgen from nose.tools import assert_equals import os def setup(): os.chdir("test_dir") clean() def test_cmd_write(): cfgen.cmd_write("test.cfg") with open("test.cfg") as actual, open("test.cfg.expected") as expected: actual_lines = actual.read().splitlines() expected_lines = expected.read().splitlines() assert_equals(len(actual_lines), len(expected_lines)) for line_number in range(0, len(actual_lines)): assert_equals(actual_lines[line_number], expected_lines[line_number]) def clean(): if os.path.isfile("test.cfg"): os.remove("test.cfg") if os.path.isfile("test.cfg.metaconfig.cache"): os.remove("test.cfg.metaconfig.cache")
Move goog.module.declareLegacyNamespace() calls to be next to goog.module ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=271418472
// Copyright 2014 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A test file for testing goog.module. * @suppress {unusedLocalVariables} */ goog.module('goog.test_module'); goog.module.declareLegacyNamespace(); goog.setTestOnly('goog.test_module'); /** @suppress {extraRequire} */ var testModuleDep = goog.require('goog.test_module_dep'); // Verify that when this module loads the script tag in the next // line doesn't cause the script tag it is loaded in to be closed // prematurely. var aScriptTagShouldntBreakAnything = '<script>hello</script>world'; /** @constructor */ var test = function() {}; // Verify that when this module loads the script tag is not modified by // escaping code in base.js. test.CLOSING_SCRIPT_TAG = '</script>'; exports = test;
// Copyright 2014 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A test file for testing goog.module. * @suppress {unusedLocalVariables} */ goog.module('goog.test_module'); goog.setTestOnly('goog.test_module'); goog.module.declareLegacyNamespace(); /** @suppress {extraRequire} */ var testModuleDep = goog.require('goog.test_module_dep'); // Verify that when this module loads the script tag in the next // line doesn't cause the script tag it is loaded in to be closed // prematurely. var aScriptTagShouldntBreakAnything = '<script>hello</script>world'; /** @constructor */ var test = function() {}; // Verify that when this module loads the script tag is not modified by // escaping code in base.js. test.CLOSING_SCRIPT_TAG = '</script>'; exports = test;
Use `console.warn` instead of `log.warn`
function ServerCookies(req, res) { if (!req) { throw new Error('req is required'); } if (!res) { throw new Error('res is required'); } this.req = req; this.res = res; } ServerCookies.prototype = { get: function(key) { if (this.req.cookies) { return this.req.cookies[key]; } console.warn( 'Warning: Could not find cookies in req. Do you have the cookie-parser middleware ' + '(https://www.npmjs.com/package/cookie-parser) installed?' ); }, set: function(key, value, options) { this.res.cookie(key, value, options); }, expire: function(key) { this.res.clearCookie(key); } } module.exports = ServerCookies;
function ServerCookies(req, res) { if (!req) { throw new Error('req is required'); } if (!res) { throw new Error('res is required'); } this.req = req; this.res = res; } ServerCookies.prototype = { get: function(key) { if (this.req.cookies) { return this.req.cookies[key]; } log.warn( 'Warning: Could not find cookies in req. Do you have the cookie-parser middleware ' + '(https://www.npmjs.com/package/cookie-parser) installed?' ); }, set: function(key, value, options) { this.res.cookie(key, value, options); }, expire: function(key) { this.res.clearCookie(key); } } module.exports = ServerCookies;
Test for list volumes added
<?php namespace tests\Nerdstorm\GoogleBooks\Api; use GuzzleHttp\Psr7\Response; use Nerdstorm\GoogleBooks\Api\VolumesSearch; use tests\Nerdstorm\Config; class VolumeSearchTest extends \PHPUnit_Framework_TestCase { /** @var VolumeSearch */ protected $volume_search; public function setup() { $this->volume_search = new VolumesSearch( Config::API_KEY, Config::guzzleOpts() ); } public function testVolumeList() { /** @var Response $response */ $response = $this->volume_search->volumesList('Systems analysis and design'); $json = (string) $response->getBody(); $data = json_decode($json, true); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('application/json; charset=UTF-8', $response->getHeader('Content-Type')[0]); $this->assertEquals($data['kind'], 'books#volumes'); if ($data['totalItems'] >= 10) { $this->assertCount(10, $data['items']); } else { $this->assertCount($data['totalItems'], $data['items']); } } }
<?php namespace tests\Nerdstorm\GoogleBooks\Api; use GuzzleHttp\Psr7\Response; use Nerdstorm\GoogleBooks\Api\VolumesSearch; use tests\Nerdstorm\Config; class VolumeSearchTest extends \PHPUnit_Framework_TestCase { /** @var VolumeSearch */ protected $volume_search; public function setup() { $this->volume_search = new VolumesSearch( Config::API_KEY, Config::guzzleOpts() ); } public function testVolumeList() { /** @var Response $response */ $response = $this->volume_search->volumesList('Systems analysis and design'); $response->getBody()->getContents(); } }
Set application port and remove fs dependency
/** * React form server.The simplest server ever. * * This Express application serves the contact form with its * assets and processes the submission. A lot of aspects * of a real life application have been omitted here * for the sake of simplicity such as form validation and * security. */ var bodyParser = require('body-parser'); var express = require('express'); var app = express(); // Sets the port to use. app.set('port', (process.env.PORT || 3000)); // Exposes public assets such as index.html and JavaScript files. app.use(express.static('public')); // Adds support for JSON-encoded bodies used in POST requests. app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // Processes a form submission. app.post('/send', function (req, res) { console.log(req.body); return res.send({status: 'OK'}); }); // Starts the web application. var server = app.listen(app.get('port'), function () { console.log('App is running at port', app.get('port')); });
/** * React form server.The simplest server ever. * * This Express application serves the contact form with its * assets and processes the submission. A lot of aspects * of a real life application have been omitted here * for the sake of simplicity such as form validation and * security. */ var bodyParser = require('body-parser'); var fs = require('fs'); var express = require('express'); var app = express(); // Exposes public assets such as index.html and JavaScript files. app.use(express.static('public')); // Adds support for JSON-encoded bodies used in POST requests. app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // Processes a form submission. app.post('/send', function (req, res) { console.log(req.body); return res.send({status: 'OK'}); }); // Starts the web application. var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; });
Add layers to map options
angular.module('anol.map') .provider('MapService', [function() { var _view; var buildMapConfig = function(layers, controls) { var map = new ol.Map(angular.extend({}, { controls: controls, layers: layers })); map.setView(_view); return map; }; this.addView = function(view) { _view = view; }; this.$get = ['LayersService', 'ControlsService', function(LayersService, ControlsService) { var MapService = function() { this.map = undefined; }; MapService.prototype.getMap = function() { if(angular.isUndefined(this.map)) { this.map = buildMapConfig( LayersService.layers, ControlsService.controls ); LayersService.registerMap(this.map); } return this.map; }; return new MapService(); }]; }]);
angular.module('anol.map') .provider('MapService', [function() { var _view; var buildMapConfig = function(layers, controls) { var map = new ol.Map(angular.extend({}, { 'controls': controls })); map.setView(_view); angular.forEach(layers, function(layer) { map.addLayer(layer); }); return map; }; this.addView = function(view) { _view = view; }; this.$get = ['LayersService', 'ControlsService', function(LayersService, ControlsService) { var MapService = function() { this.map = undefined; }; MapService.prototype.getMap = function() { if(angular.isUndefined(this.map)) { this.map = buildMapConfig( LayersService.layers, ControlsService.controls ); LayersService.registerMap(this.map); } return this.map; }; return new MapService(); }]; }]);
Check to see what values are in which file.
const propertiesReader = require("properties-reader"); const fs = require("fs"); const defaults = { "primary-color": "#1890ff", "info-color": "#1890ff", "link-color": "#1890ff", "font-size-base": "14px", "border-radius-base": "2px", }; const iridaConfig = "/etc/irida/irida.conf"; const propertiesConfig = "../resources/configuration.properties"; function formatAntStyles() { const colourProperties = {}; const re = /styles.ant.([\w+-]*)/; try { if (fs.existsSync(propertiesConfig)) { const properties = propertiesReader(propertiesConfig); properties.each((key, value) => { const found = key.match(re); if (found) { colourProperties[found[1]] = value; } }); } if (fs.existsSync(iridaConfig)) { const properties = propertiesReader(iridaConfig); properties.each((key, value) => { const found = key.match(re); if (found) { colourProperties[found[1]] = value; } }); } } catch (e) { console.log("No styles in `/etc/irida/irida.conf`"); } return Object.assign({}, defaults, colourProperties); } module.exports = { formatAntStyles };
const propertiesReader = require("properties-reader"); const defaults = { "primary-color": "#1890ff", "info-color": "#1890ff", "link-color": "#1890ff", "font-size-base": "14px", "border-radius-base": "2px", }; function formatAntStyles() { const custom = {}; const re = /styles.ant.([\w+-]*)/; try { const properties = propertiesReader("/etc/irida/irida.conf"); properties.each((key, value) => { const found = key.match(re); if (found) { custom[found[1]] = value; } }); } catch (e) { console.log("No styles in `/etc/irida/irida.conf`"); } return Object.assign({}, defaults, custom); } module.exports = { formatAntStyles };
Fix adjacent page lookup for page preloading `AdjacentPage#nextPage` already returns a page widget instance. `AdjacentPage#of` treated it like a jQuery object.
pageflow.AdjacentPages = pageflow.Object.extend({ initialize: function(pages, scrollNavigator) { this.pages = pages; this.scrollNavigator = scrollNavigator; }, of: function(page) { var result = []; var pages = this.pages(); var nextPage = this.nextPage(page); if (nextPage) { result.push(nextPage); } _(page.linkedPages()).each(function(permaId) { var linkedPage = pages.filter('#' + permaId); if (linkedPage.length) { result.push(linkedPage.page('instance')); } }, this); return result; }, nextPage: function(page) { var nextPage = this.scrollNavigator.getNextPage(page.element, this.pages()); return nextPage.length && nextPage.page('instance'); } });
pageflow.AdjacentPages = pageflow.Object.extend({ initialize: function(pages, scrollNavigator) { this.pages = pages; this.scrollNavigator = scrollNavigator; }, of: function(page) { var result = []; var pages = this.pages(); var nextPage = this.nextPage(page); if (nextPage.length) { result.push(nextPage.page('instance')); } _(page.linkedPages()).each(function(permaId) { var linkedPage = pages.filter('#' + permaId); if (linkedPage.length) { result.push(linkedPage.page('instance')); } }, this); return result; }, nextPage: function(page) { var nextPage = this.scrollNavigator.getNextPage(page.element, this.pages()); return nextPage.length && nextPage.page('instance'); } });
FIX - IE11 does not support inside loops
'use strict'; /** * Module dependenices */ const clone = require('shallow-clone'); const typeOf = require('kind-of'); function cloneDeep(val, instanceClone) { switch (typeOf(val)) { case 'object': return cloneObjectDeep(val, instanceClone); case 'array': return cloneArrayDeep(val, instanceClone); default: { return clone(val); } } } function cloneObjectDeep(val, instanceClone) { if (typeof instanceClone === 'function') { return instanceClone(val); } if (typeOf(val) === 'object') { const res = new val.constructor(); for (let key in val) { res[key] = cloneDeep(val[key], instanceClone); } return res; } return val; } function cloneArrayDeep(val, instanceClone) { const res = new val.constructor(val.length); for (let i = 0; i < val.length; i++) { res[i] = cloneDeep(val[i], instanceClone); } return res; } /** * Expose `cloneDeep` */ module.exports = cloneDeep;
'use strict'; /** * Module dependenices */ const clone = require('shallow-clone'); const typeOf = require('kind-of'); function cloneDeep(val, instanceClone) { switch (typeOf(val)) { case 'object': return cloneObjectDeep(val, instanceClone); case 'array': return cloneArrayDeep(val, instanceClone); default: { return clone(val); } } } function cloneObjectDeep(val, instanceClone) { if (typeof instanceClone === 'function') { return instanceClone(val); } if (typeOf(val) === 'object') { const res = new val.constructor(); for (const key in val) { res[key] = cloneDeep(val[key], instanceClone); } return res; } return val; } function cloneArrayDeep(val, instanceClone) { const res = new val.constructor(val.length); for (let i = 0; i < val.length; i++) { res[i] = cloneDeep(val[i], instanceClone); } return res; } /** * Expose `cloneDeep` */ module.exports = cloneDeep;
Remove height setting from js
$(document).ready(function(){ $('.popup__toggle').on('click', popup); function popup() { $('#popup').toggleClass("open"); } function fileHandler(event){ var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element) var reader = new FileReader(); reader.onload = function(event){ var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader). $("#preview-img").attr('src', data); }; reader.readAsDataURL(file); } function addImgToInfo() { $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper'); } $('#file').on("change", fileHandler); $('#submit-img').on('click', addImgToInfo); }); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }
$(document).ready(function(){ $('.popup__toggle').on('click', popup); function popup() { $('#popup').toggleClass("open"); } function fileHandler(event){ var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element) var reader = new FileReader(); reader.onload = function(event){ var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader). $("#preview-img").attr('src', data); }; reader.readAsDataURL(file); } function addImgToInfo() { $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper'); } $('#file').on("change", fileHandler); $('#submit-img').on('click', addImgToInfo); }); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); $("html, body, #popup").css({ height: $(window).height() }); }
Return null if view is not available. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Notifier; use Illuminate\Support\Arr; use Illuminate\Support\Fluent; use Orchestra\Contracts\Notification\Message as MessageContract; class Message extends Fluent implements MessageContract { /** * Create a new Message instance. * * @param string|array $view * @param array $data * @param string|null $subject * @return static */ public static function create($view, array $data = [], $subject = null) { return new static([ 'view' => $view, 'data' => $data, 'subject' => $subject, ]); } /** * Get data. * * @return array */ public function getData() { return Arr::get($this->attributes, 'data', []); } /** * Get subject. * * @return string */ public function getSubject() { return Arr::get($this->attributes, 'subject', ''); } /** * Get view. * * @return string|array */ public function getView() { return Arr::get($this->attributes, 'view'); } }
<?php namespace Orchestra\Notifier; use Illuminate\Support\Arr; use Illuminate\Support\Fluent; use Orchestra\Contracts\Notification\Message as MessageContract; class Message extends Fluent implements MessageContract { /** * Create a new Message instance. * * @param string|array $view * @param array $data * @param string|null $subject * @return static */ public static function create($view, array $data = [], $subject = null) { return new static([ 'view' => $view, 'data' => $data, 'subject' => $subject, ]); } /** * Get data. * * @return array */ public function getData() { return Arr::get($this->attributes, 'data', []); } /** * Get subject. * * @return string */ public function getSubject() { return Arr::get($this->attributes, 'subject', ''); } /** * Get view. * * @return string|array */ public function getView() { return Arr::get($this->attributes, 'view', ''); } }
Handle non-existent translation_domain table to allow its creation Fixes #2
<?php namespace Argentum\TranslationBundle\Entity; use Doctrine\DBAL\DBALException; use Doctrine\ORM\EntityRepository; /** * TranslationDomainRepository * * @author Vadim Borodavko <javer@argentum.ua> * @copyright Argentum IT Lab, http://argentum.ua */ class TranslationDomainRepository extends EntityRepository { /** * Returns a list of all domains. * * @return array */ public function getAllDomains() { try { $result = $this->createQueryBuilder('d') ->select('d.name') ->getQuery() ->getArrayResult(); $domains = array_map('current', $result); } catch (DBALException $e) { $domains = array(); } return $domains; } /** * Returns a domain by name. * * @param string $name * * @return TranslationDomain */ public function getByName($name) { return $this->findOneBy(array('name' => $name)); } }
<?php namespace Argentum\TranslationBundle\Entity; use Doctrine\ORM\EntityRepository; /** * TranslationDomainRepository * * @author Vadim Borodavko <javer@argentum.ua> * @copyright Argentum IT Lab, http://argentum.ua */ class TranslationDomainRepository extends EntityRepository { /** * Returns a list of all domains. * * @return array */ public function getAllDomains() { $result = $this->createQueryBuilder('d') ->select('d.name') ->getQuery() ->getArrayResult(); $domains = array_map('current', $result); return $domains; } /** * Returns a domain by name. * * @param string $name * * @return TranslationDomain */ public function getByName($name) { return $this->findOneBy(array('name' => $name)); } }
Remove unused moment lib form job run test
let JobRun = require('../JobRun'); let JobTaskList = require('../JobTaskList'); describe('JobRun', function () { describe('#getDateCreated', function () { it('should return null if createdAt is undefined', function () { let activeRun = new JobRun({foo: 'bar'}); expect(activeRun.getDateCreated()).toEqual(null); }); it('should return the correct value in milliseconds', function () { let activeRun = new JobRun({createdAt: '1990-01-03T02:00:00Z-1'}); expect(activeRun.getDateCreated()).toEqual(631332000000); }); }); describe('#getJobID', function () { it('should return the jobId', function () { let activeRun = new JobRun({jobId: 'foo'}); expect(activeRun.getJobID()).toEqual('foo'); }); }); describe('#getStatus', function () { it('should return the id', function () { let activeRun = new JobRun({status: 'foo'}); expect(activeRun.getStatus()).toEqual('foo'); }); }); describe('#getTasks', function () { it('should return an instance of JobTaskList', function () { let activeRun = new JobRun({id: 'foo', tasks: []}); expect(activeRun.getTasks() instanceof JobTaskList).toBeTruthy(); }); }); });
let moment = require('moment'); let JobRun = require('../JobRun'); let JobTaskList = require('../JobTaskList'); describe('JobRun', function () { describe('#getDateCreated', function () { it('should return null if createdAt is undefined', function () { let activeRun = new JobRun({foo: 'bar'}); expect(activeRun.getDateCreated()).toEqual(null); }); it('should return the correct value in milliseconds', function () { let activeRun = new JobRun({createdAt: '1990-01-03T02:00:00Z-1'}); expect(activeRun.getDateCreated()).toEqual(631332000000); }); }); describe('#getJobID', function () { it('should return the jobId', function () { let activeRun = new JobRun({jobId: 'foo'}); expect(activeRun.getJobID()).toEqual('foo'); }); }); describe('#getStatus', function () { it('should return the id', function () { let activeRun = new JobRun({status: 'foo'}); expect(activeRun.getStatus()).toEqual('foo'); }); }); describe('#getTasks', function () { it('should return an instance of JobTaskList', function () { let activeRun = new JobRun({id: 'foo', tasks: []}); expect(activeRun.getTasks() instanceof JobTaskList).toBeTruthy(); }); }); });
Allow multiple lines of traceback.
#!/usr/bin/python3 from pprint import pprint import json import sys def get(obj, path): try: for part in path: obj = obj[part] return obj except KeyError: return None def display(obj): for path in paths: subobj = get(obj, path) if subobj is not None: obj = subobj break if isinstance(obj, str): print(obj) else: pprint(obj) if __name__ == '__main__': if len(sys.argv) >= 2: paths = [sys.argv[1].split('.')] else: paths = [ ['meta', 'error', 'stack'], ['error', 'stack'], ['traceback'], ] for line in sys.stdin.readlines(): obj = json.loads(line) display(obj)
#!/usr/bin/python3 from pprint import pprint import json import sys def get(obj, path): try: for part in path: obj = obj[part] return obj except KeyError: return None if __name__ == '__main__': if len(sys.argv) >= 2: paths = [sys.argv[1].split('.')] else: paths = [ ['meta', 'error', 'stack'], ['error', 'stack'], ['traceback'], ] obj = json.load(sys.stdin) for path in paths: subobj = get(obj, path) if subobj is not None: obj = subobj break if isinstance(obj, str): print(obj) else: pprint(obj)
Add third_party/android_tools/sdk/platform-tools to PATH if available R=whesse@google.com Review URL: https://codereview.chromium.org/1938973002 .
#!/usr/bin/env python # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import string import subprocess import sys import utils def Main(): args = sys.argv[1:] tools_dir = os.path.dirname(os.path.realpath(__file__)) dart_script_name = 'test.dart' dart_test_script = string.join([tools_dir, dart_script_name], os.sep) command = [utils.CheckedInSdkExecutable(), '--checked', dart_test_script] + args # The testing script potentially needs the android platform tools in PATH so # we do that in ./tools/test.py (a similar logic exists in ./tools/build.py). android_platform_tools = os.path.normpath(os.path.join( tools_dir, '../third_party/android_tools/sdk/platform-tools')) if os.path.isdir(android_platform_tools): os.environ['PATH'] = '%s%s%s' % ( os.environ['PATH'], os.pathsep, android_platform_tools) exit_code = subprocess.call(command) utils.DiagnoseExitCode(exit_code, command) return exit_code if __name__ == '__main__': sys.exit(Main())
#!/usr/bin/env python # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import string import subprocess import sys import utils def Main(): args = sys.argv[1:] tools_dir = os.path.dirname(os.path.realpath(__file__)) dart_script_name = 'test.dart' dart_test_script = string.join([tools_dir, dart_script_name], os.sep) command = [utils.CheckedInSdkExecutable(), '--checked', dart_test_script] + args exit_code = subprocess.call(command) utils.DiagnoseExitCode(exit_code, command) return exit_code if __name__ == '__main__': sys.exit(Main())
Make handle function to behave similar as main function
# Author: Milos Buncic # Date: 2017/10/14 # Description: Convert YAML to JSON and vice versa (OpenFaaS function) import os import sys import json import yaml def yaml2json(data): """ Convert YAML to JSON (output: JSON) """ try: d = yaml.load(data, Loader=yaml.BaseLoader) except Exception as e: d = {'error': '{}'.format(e)} return json.dumps(d) def json2yaml(data): """ Convert JSON to YAML (output: YAML) """ try: d = json.loads(data) except Exception as e: d = {'error': '{}'.format(e)} return yaml.dump(d, default_flow_style=False) def handle(data, **parms): if parms.get('reverse') == 'true': print(json2yaml(data)) else: print(yaml2json(data))
# Author: Milos Buncic # Date: 2017/10/14 # Description: Convert YAML to JSON and vice versa (OpenFaaS function) import os import sys import json import yaml def handle(data, **parms): def yaml2json(ydata): """ Convert YAML to JSON (output: JSON) """ try: d = yaml.load(ydata, Loader=yaml.BaseLoader) except Exception as e: d = {'error': '{}'.format(e)} return json.dumps(d) def json2yaml(jdata): """ Convert JSON to YAML (output: YAML) """ try: d = json.loads(jdata) except Exception as e: d = {'error': '{}'.format(e)} return yaml.dump(d, default_flow_style=False) if parms.get('reverse') == 'true': print(json2yaml(data)) else: print(yaml2json(data))
Package name for psycopg2 has been changed
#! /usr/bin/env python3 from setuptools import setup from dictorm.dictorm import __version__, __doc__ as ddoc config = { 'name':'dictorm', 'version':str(__version__), 'author':'rolobio', 'author_email':'rolobio+dictorm@rolobio.com', 'description':ddoc, 'license':'Apache2', 'keywords':'psycopg2 dictionary python dict', 'url':'https://github.com/rolobio/DictORM', 'packages':[ 'dictorm', ], 'long_description':ddoc, 'classifiers':[ "Development Status :: 5 - Production/Stable", "Topic :: Utilities", ], 'setup_requires': ['green>=2.12.0'], 'tests_require': [ 'coverage', 'coveralls', 'green>=2.12.0', 'psycopg2-binary', ], 'extras_require':{ 'Postgresql': ['psycopg2-binary'], 'testing': ['psycopg2-binary', 'green>=2.12.0', 'coveralls', 'coverage'], } } setup(**config)
#! /usr/bin/env python3 from setuptools import setup from dictorm.dictorm import __version__, __doc__ as ddoc config = { 'name':'dictorm', 'version':str(__version__), 'author':'rolobio', 'author_email':'rolobio+dictorm@rolobio.com', 'description':ddoc, 'license':'Apache2', 'keywords':'psycopg2 dictionary python dict', 'url':'https://github.com/rolobio/DictORM', 'packages':[ 'dictorm', ], 'long_description':ddoc, 'classifiers':[ "Development Status :: 5 - Production/Stable", "Topic :: Utilities", ], 'setup_requires': ['green>=2.12.0'], 'tests_require': [ 'coverage', 'coveralls', 'green>=2.12.0', 'psycopg2', ], 'extras_require':{ 'Postgresql': ['psycopg2'], 'testing': ['psycopg2', 'green>=2.12.0', 'coveralls', 'coverage'], } } setup(**config)
Add Users library to main script.
var app = require('express').createServer(); var sys = require('sys'); var books = require("./books"); var users = require("./users"); var client = require("./lib/redis-client").createClient(); app.listen(8124); app.get('/', function(req, res){ res.send('hello world'); }); // List All Users app.get('/users', function(req, res){ var userlist = "<h1>User List</h1><br />" users.listUsers( client, function(name) {userlist+=String(name+"<br />")}, function() {res.send(userlist)} ); }); // List All Books app.get('/books', function(req, res){ var booklist = "<h1>Book List</h1><br />" books.listBooks(client, function(title) {booklist+=String(title+"<br />")}, function() {res.send(booklist)} ); });
var app = require('express').createServer(); var sys = require('sys'); var client = require("./lib/redis-client").createClient(); var books = require("./books"); app.listen(8124); app.get('/', function(req, res){ res.send('hello world'); }); // List All Users app.get('/users', function(req, res){ var userlist = "<h1>User List</h1><br />" users.listUsers( client, function(name) {userlist+=String(name+"<br />")}, function() {res.send(userlist)} ); }); // List All Books app.get('/books', function(req, res){ var booklist = "<h1>Book List</h1><br />" books.listBooks(client, function(title) {booklist+=String(title+"<br />")}, function() {res.send(booklist)} ); });
Fix handling of separator characters by Python modules Currently the Python modules do not tolerate more than one equal sign ("=") in each line of the config file. However REs with look-ahead functionality require this character. Introduce new RE-based line-splitting mechanism. Fix handling of in-line comments.
#!/usr/bin/env python-2.7 """ Module for common processes in bcelldb computing: get information from config file """ import re re_key_value = re.compile("^\s*([_A-Za-z][_0-9A-Za-z]+)=(.*?)\s*;?\s*$") re_inline_comment = re.compile("^(.*?)(?<!\\\\)#.*") def get_config(): """ Look for config file in . and than ../ Return config key value pairs in dictionary conf[]. """ # try to open config file in . try: config_file = open("config","r") except IOError: # try from ../ directory try: config_file = open("../config", "r") except IOError: print "no config file found" # global dictionary conf that will be exported conf = dict() # read lines of config for line in config_file: line = line.rstrip() if not re.match("^\s*$", line) and not re.match("^\s*#", line): # Split entries into key-value. line = re_inline_comment.sub('\g<1>', line) key, value = re_key_value.match(line).group(1,2) conf[key] = value return conf
#!/usr/bin/env python-2.7 """ Module for common processes in bcelldb computing: get information from config file """ import re def get_config(): """ Look for config file in . and than ../ Return config key value pairs in dictionary conf[]. """ # try to open config file in . try: config_file = open("config","r") except IOError: # try from ../ directory try: config_file = open("../config", "r") except IOError: print "no config file found" # global dictionary conf that will be exported conf = dict() # read lines of config for line in config_file: # every line with # is used as a comment line if re.search('=', line) and not re.match('\s?#', line): # split entries into key-value [key, value] = re.split("=", line) # get rid of new line conf[key] = value[:-1] # return conf[] return conf
Use the scale in the var name.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.bcel; public class NanoTimer { private long timeNanos = 0; public NanoTimer start() { timeNanos -= System.nanoTime(); return this; } public void stop() { timeNanos += System.nanoTime(); } public void subtract(final NanoTimer o) { timeNanos -= o.timeNanos; } public void reset() { timeNanos = 0; } /** * May ony be called after stop has been called as many times as start. */ @Override public String toString() { return ((double) timeNanos / 1000000000) + " s"; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.bcel; public class NanoTimer { private long time = 0; public NanoTimer start() { time -= System.nanoTime(); return this; } public void stop() { time += System.nanoTime(); } public void subtract(final NanoTimer o) { time -= o.time; } public void reset() { time = 0; } /** * May ony be called after stop has been called as many times as start. */ @Override public String toString() { return ((double) time / 1000000000) + " s"; } }
Convert README.md to reStructuredText with pypandoc
# -*- coding: utf-8 -*- from setuptools import find_packages, setup from pyglins import __version__, __description__ def read_readme(): try: import pypandoc description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): with open('README.md') as file: description = file.read() return description setup(name='pyglins', version=__version__, description=__description__, long_description=read_readme(), classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', 'Operating System :: OS Independent'], keywords='plugin manager', author='Javier Caballero', author_email='paxet83@gmail.com', url='https://github.com/paxet/pyglins', license='MIT', packages=find_packages(exclude=['tests']), )
# -*- coding: utf-8 -*- import os from setuptools import find_packages, setup from pyglins import __version__, __description__ def read_readme(): with open(os.path.join(os.path.dirname(__file__), 'README.md')) as file: return file.read() setup(name='pyglins', version=__version__, description=__description__, long_description=read_readme(), classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', 'Operating System :: OS Independent'], keywords='plugin manager', author='Javier Caballero', author_email='paxet83@gmail.com', url='https://github.com/paxet/pyglins', license='MIT', packages=find_packages(exclude=['tests']), )
Update gulpfile to watch contrib styles and not just core project files
var autoprefix = require("gulp-autoprefixer"), connect = require("gulp-connect"), gulp = require("gulp"), sass = require("gulp-sass"); var paths = { scss: [ "./core/**/*.scss", "./contrib/**/*.scss"] }; gulp.task("sass", function () { return gulp.src(paths.scss) .pipe(sass({ sourcemaps: true })) .pipe(autoprefix("last 2 versions")) .pipe(gulp.dest("./contrib")) .pipe(connect.reload()); }); gulp.task("connect", function() { connect.server({ root: "contrib", port: 8000, livereload: true }); }); gulp.task("default", ["sass", "connect"], function() { gulp.watch(paths.scss, ["sass"]); });
var autoprefix = require("gulp-autoprefixer"), connect = require("gulp-connect"), gulp = require("gulp"), sass = require("gulp-sass"); var paths = { scss: [ "./core/**/*.scss", "./contrib/styles.scss"] }; gulp.task("sass", function () { return gulp.src(paths.scss) .pipe(sass({ sourcemaps: true })) .pipe(autoprefix("last 2 versions")) .pipe(gulp.dest("./contrib")) .pipe(connect.reload()); }); gulp.task("connect", function() { connect.server({ root: "contrib", port: 8000, livereload: true }); }); gulp.task("default", ["sass", "connect"], function() { gulp.watch(paths.scss, ["sass"]); });
Use offsetHeight instead of clientHeight as it's more technically correct
function jumpToToday() { var todayMatches = document.querySelectorAll(".match.today-ish:not(.filter-no-match)"); var lastToday = todayMatches[todayMatches.length - 1]; if(lastToday) { var filtersHeight = document.getElementById("filters-wrapper").offsetHeight; window.scrollTo(0, lastToday.offsetTop - filtersHeight); } else { window.scrollTo(0, 0); } } document.addEventListener("DOMContentLoaded", function(event) { document.querySelector("a#today").addEventListener("click", function(event) { event.preventDefault(); jumpToToday(); }); document.querySelector("a#top").addEventListener("click", function(event) { event.preventDefault(); window.scrollTo(0, 0); }); document.querySelector("a#end").addEventListener("click", function(event) { event.preventDefault(); document.body.scrollIntoView(false); }); setTimeout(jumpToToday, 0); });
function jumpToToday() { var todayMatches = document.querySelectorAll(".match.today-ish:not(.filter-no-match)"); var lastToday = todayMatches[todayMatches.length - 1]; if(lastToday) { var filtersHeight = document.getElementById("filters-wrapper").clientHeight; window.scrollTo(0, lastToday.offsetTop - filtersHeight); } else { window.scrollTo(0, 0); } } document.addEventListener("DOMContentLoaded", function(event) { document.querySelector("a#today").addEventListener("click", function(event) { event.preventDefault(); jumpToToday(); }); document.querySelector("a#top").addEventListener("click", function(event) { event.preventDefault(); window.scrollTo(0, 0); }); document.querySelector("a#end").addEventListener("click", function(event) { event.preventDefault(); document.body.scrollIntoView(false); }); setTimeout(jumpToToday, 0); });
Optimize cases when no wait is required
module.exports = limiter; /*global setTimeout, clearTimeout */ function limiter(interval) { var queue = [], lastTrigger = 0, timer; function now() { return + (new Date); } function since() { return now() - lastTrigger; } function deque() { timer = undefined; var fn = queue.shift(); fn(); lastTrigger = now(); schedule(); } function schedule() { if (!timer && queue.length) { timer = setTimeout(deque, interval - since()); } } function trigger(fn) { if (since() >= interval && !queue.length) { fn(); lastTrigger = now(); } else { queue.push(fn); schedule(); } } function cancel() { if (timer) { clearTimeout(timer); } queue = []; } return { trigger: trigger, cancel: cancel }; }
module.exports = limiter; /*global setTimeout, clearTimeout */ function limiter(interval) { var queue = [], lastTrigger = 0, timer; function now() { return + (new Date); } function since() { return now() - lastTrigger; } function deque() { var fn = queue.shift(); timer = undefined; lastTrigger = now(); fn(); if (queue.length) { schedule(); } } function schedule() { var now = Date.now(); timer = setTimeout(deque, interval - since()); } function trigger(fn) { queue.push(fn); if (since() >= interval) { deque(); } else { schedule(); } } function cancel() { if (timer) { clearTimeout(timer); } queue = []; } return { trigger: trigger, cancel: cancel }; }
Remove line break in includes params This was causing a 400 Invalid Request on the organizations page.
import Ember from 'ember'; import TravisRoute from 'travis/routes/basic'; import config from 'travis/config/environment'; export default TravisRoute.extend({ needsAuth: false, titleToken(model) { var name = model.name || model.login; return name; }, model(params, transition) { var options; options = {}; if (this.get('auth.signedIn')) { options.headers = { Authorization: 'token ' + (this.auth.token()) }; } // eslint-disable-next-line let includes = `?include=owner.repositories,repository.default_branch,build.commit,repository.current_build`; let { owner } = transition.params.owner; let url = `${config.apiEndpoint}/v3/owner/${owner}${includes}`; return Ember.$.get(url, options); } });
import Ember from 'ember'; import TravisRoute from 'travis/routes/basic'; import config from 'travis/config/environment'; export default TravisRoute.extend({ needsAuth: false, titleToken(model) { var name = model.name || model.login; return name; }, model(params, transition) { var options; options = {}; if (this.get('auth.signedIn')) { options.headers = { Authorization: 'token ' + (this.auth.token()) }; } let includes = `?include=owner.repositories,repository.default_branch, build.commit,repository.current_build`; let { owner } = transition.params.owner; let url = `${config.apiEndpoint}/v3/owner/${owner}${includes}`; return Ember.$.get(url, options); } });
Add request handler for specific restaurant.
from flask import Flask from flask_caching import Cache import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return main.list_restaurants() @app.route('/api/restaurant/<name>') @cache.cached(timeout=3600) def api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(404) return data @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
from flask import Flask from flask_caching import Cache import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>' + '<body>' + '<p><a href="ki">Campus Solna (KI)</a></p>' + '<p><a href="uu">Campus Uppsala (BMC)</a></p>' + '</body>' + '</html>') return content @app.route('/api/restaurants') @cache.cached(timeout=3600) def api_list_restaurants(): return main.list_restaurants() @app.route('/ki') @cache.cached(timeout=3600) def make_menu_ki(): return main.gen_ki_menu() @app.route('/uu') @cache.cached(timeout=3600) def make_menu_uu(): return main.gen_uu_menu()
Fix typo in metaData merging logic
var request = require('./request'); var config = require('./config'); var notifierVersion = require('./version').notifierVersion; function merge(target, obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { target[key] = obj[key]; } } return target; } function notify(err, options) { if (!options) options = {}; request(config.endpoint, { payloadVersion: '3', notifierVersion: notifierVersion, apiKey: config.apiKey, projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host, context: config.context || window.location.pathname, user: config.user, metaData: merge(merge({}, config.metaData), options.metaData || {}), releaseStage: config.releaseStage, appVersion: config.appVersion, url: window.location.href, userAgent: navigator.userAgent, language: navigator.language || navigator.userLanguage, severity: options.severity || config.severity, name: err.name, message: err.message, stacktrace: err.stack || err.backtrace || err.stacktrace, file: err.fileName || err.sourceURL, lineNumber: -1, columnNumber: -1, breadcrumbs: [] }); } module.exports = notify;
var request = require('./request'); var config = require('./config'); var notifierVersion = require('./version').notifierVersion; function merge(target, obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { target[key] = obj[key]; } } return target; } function notify(err, options) { if (!options) options = {}; request(config.endpoint, { payloadVersion: '3', notifierVersion: notifierVersion, apiKey: config.apiKey, projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host, context: config.context || window.location.pathname, user: config.user, metaData: merge(merge({}, config.metaData), config.metaData || {}), releaseStage: config.releaseStage, appVersion: config.appVersion, url: window.location.href, userAgent: navigator.userAgent, language: navigator.language || navigator.userLanguage, severity: options.severity || config.severity, name: err.name, message: err.message, stacktrace: err.stack || err.backtrace || err.stacktrace, file: err.fileName || err.sourceURL, lineNumber: -1, columnNumber: -1, breadcrumbs: [] }); } module.exports = notify;
Fix golint errors when generating informer code Kubernetes-commit: acf78cd6133de6faea9221d8c53b02ca6009b0bb
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by informer-gen. DO NOT EDIT. package internalinterfaces import ( time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" cache "k8s.io/client-go/tools/cache" versioned "k8s.io/csi-api/pkg/client/clientset/versioned" ) // NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle type SharedInformerFactory interface { Start(stopCh <-chan struct{}) InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } // TweakListOptionsFunc is a function that transforms a v1.ListOptions. type TweakListOptionsFunc func(*v1.ListOptions)
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by informer-gen. DO NOT EDIT. package internalinterfaces import ( time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" cache "k8s.io/client-go/tools/cache" versioned "k8s.io/csi-api/pkg/client/clientset/versioned" ) type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle type SharedInformerFactory interface { Start(stopCh <-chan struct{}) InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } type TweakListOptionsFunc func(*v1.ListOptions)
Use graceful-fs in place of fs Change generate-requires.js to use the graceful-fs module instead of fs. This is to avoid EMFILE errors on OSX because the maximum number of file descriptors have been reached.
var fs = require('graceful-fs'); // The number of files that we need to generate goog.require's for. var numFiles = process.argv.length - 1; /** * Object used a set of found goog.provide's. * @type {Object.<string, boolean>} */ var requires = {}; process.argv.forEach(function(val, index, array) { if (index === 0) { return; } fs.readFile(val, function(err, data) { if (err) { return; } var re = new RegExp('goog\\.provide\\(\'(.*)\'\\);'); data.toString().split('\n').forEach(function(line) { var match = line.match(re); if (match) { requires[match[1]] = true; } }); if (--numFiles === 0) { Object.keys(requires).sort().forEach(function(key) { process.stdout.write('goog.require(\'' + key + '\');\n'); }); } }); });
var fs = require('fs'); // The number of files that we need to generate goog.require's for. var numFiles = process.argv.length - 1; /** * Object used a set of found goog.provide's. * @type {Object.<string, boolean>} */ var requires = {}; process.argv.forEach(function(val, index, array) { if (index === 0) { return; } fs.readFile(val, function(err, data) { if (err) { return; } var re = new RegExp('goog\\.provide\\(\'(.*)\'\\);'); data.toString().split('\n').forEach(function(line) { var match = line.match(re); if (match) { requires[match[1]] = true; } }); if (--numFiles === 0) { Object.keys(requires).sort().forEach(function(key) { process.stdout.write('goog.require(\'' + key + '\');\n'); }); } }); });
Use jquery to send parcels tab and trips tab html back into profile in DOM
$(document).ready(function() { $('#history_tab').on('click', function(event) { event.preventDefault(); event.stopPropagation(); var $details = $(event.target); console.log($details[0].href) $.ajax({ url: $details[0].href, type: 'GET', }).done(function (response) { $('.profile-content').children().hide(); $('.profile-content').append(response); }).fail(function (response) { alert("Can Not Render Your Parcels Due to Error") }) $('#parcels_tab').on('click', function(event) { $('.profile-content').children().show(); $('#history_show').hide(); }); $('#trips_tab').on('click', function(event) { $('.profile-content').children().show(); $('#history_show').hide(); }); }); })
$(document).ready(function() { $('#history_tab').on('click', function(event) { event.preventDefault(); event.stopPropagation(); var $details = $(event.target); console.log($details[0].href) $.ajax({ url: $details[0].href, type: 'GET', }).done(function (response) { $('.profile-content').children().hide(); $('.profile-content').append(response); }).fail(function (response) { alert("Can Not Render Your Parcels Due to Error") }) $('#parcels_tab').on('click', function(event) { $('.profile-content').children().show(); $('#history_show').hide(); }); }); })
Fix this logging n stuff
const Command = require('../structures/Command'); const snekfetch = require('snekfetch'); const { inspect } = require('util'); class PostCommand extends Command { constructor() { super({ name: 'post', description: 'Update the guild count on <https://bots.discord.pw>', ownersOnly: true }); } async run(message, args) { const { config: { useDiscordBots, discordBotsAPI }, user, guilds, logger } = message.client; if (!useDiscordBots) return; snekfetch.post(`https://bots.discord.pw/api/bots/${user.id}/stats`) .set('Authorization', `${discordBotsAPI}`) .set('Content-type', 'application/json; charset=utf-8') .send(`{"server_count": ${guilds.size}}`) .then(res => message.reply('POST request sent successfully!')) .catch(err => { message.reply(`an error occurred updating the guild count: \`\`${err.statusCode}: ${err.statusText}\`\``); logger.error(`Error updating to DiscordBots: ${err.statusCode} - ${err.statusText}`); }); } } module.exports = PostCommand;
const Command = require('../structures/Command'); const snekfetch = require('snekfetch'); const { inspect } = require('util'); class PostCommand extends Command { constructor() { super({ name: 'post', description: 'Update the guild count on <https://bots.discord.pw>', ownersOnly: true }); } async run(message, args) { const { config: { useDiscordBots, discordBotsAPI }, user, guilds, logger } = message.client; if (!useDiscordBots) return; snekfetch.post(`https://bots.discord.pw/api/bots/${user.id}/stats`) .set('Authorization', `${discordBotsAPI}`) .set('Content-type', 'application/json; charset=utf-8') .send(`{"server_count": ${guilds.size}}`) .then(res => message.reply('POST request sent successfully!')) .catch(err => { const errorDetails = `${err.host ? err.host : ''} ${err.text ? err.text : ''}`.trim(); message.reply(`an error occurred updating the guild count: \`\`${err.status}: ${errorDetails}\`\``); logger.error(inspect(err)); }); } } module.exports = PostCommand;
Revert back to Local API
export const TYPE_STORIES = 'story'; export const TYPE_TACTICS = 'tactic'; export const TYPE_PRINCIPLES = 'principle'; export const TYPE_THEORIES = 'theory'; export const TYPE_METHODOLOGIES = 'methodology'; // RECAPTCHA FOR LOCALHOST // export const RECAPTCHA_SITE_KEY = '6LfeoicUAAAAADHJTSBd6PhfWyrJ1O_5f2Lx5GMe'; // RECAPTCHA FOR BETA AND PROD export const RECAPTCHA_SITE_KEY = '6LeCpCgTAAAAAFc4TwetXb1yBzJvaYo-FvrQvAlx'; export const PRODUCTION_ENDPOINT = 'https://api.beautifulrising.org/api/v1/all'; export const DEVELOPMENT_ENDPOINT = 'https://api-develop.beautifulrising.org/api/v1/all'; export const MODULE_TYPE_FULL = 'full'; export const MODULE_TYPE_GALLERY = 'gallery'; export const MODULE_TYPE_UNTRANSLATED = 'untranslated'; export const MODULE_TYPE_SNAPSHOT = 'snapshot';
export const TYPE_STORIES = 'story'; export const TYPE_TACTICS = 'tactic'; export const TYPE_PRINCIPLES = 'principle'; export const TYPE_THEORIES = 'theory'; export const TYPE_METHODOLOGIES = 'methodology'; // RECAPTCHA FOR LOCALHOST export const RECAPTCHA_SITE_KEY = '6LfeoicUAAAAADHJTSBd6PhfWyrJ1O_5f2Lx5GMe'; // RECAPTCHA FOR BETA AND PROD // export const RECAPTCHA_SITE_KEY = '6LeCpCgTAAAAAFc4TwetXb1yBzJvaYo-FvrQvAlx'; export const PRODUCTION_ENDPOINT = 'https://api.beautifulrising.org/api/v1/all'; export const DEVELOPMENT_ENDPOINT = 'https://api-develop.beautifulrising.org/api/v1/all'; export const MODULE_TYPE_FULL = 'full'; export const MODULE_TYPE_GALLERY = 'gallery'; export const MODULE_TYPE_UNTRANSLATED = 'untranslated'; export const MODULE_TYPE_SNAPSHOT = 'snapshot';
Add imageUrl function to document model
(function(){ var dc = window.dc; var $ = dc.$; var _ = dc._; var Backbone = dc.Backbone; var definition = dc.embed.definition; var data = dc.embed.data; var views = dc.embed.views; definition.Document = definition.Document || Backbone.Model.extend({ imageUrl : function(pageNumber) { if (!this._imageUrl) { var resources = this.get('resources'); var urlTemplate = resources['page']['image']; this._imageUrl = urlTemplate.replace('{size}', 'normal').replace('{page}', pageNumber); } return this._imageUrl; }, }, { extractId: function(url){ return url.match(/(\d+[A-Za-z-]+).js(on)?$/)[1]; } }); definition.DocumentSet = definition.DocumentSet || Backbone.Collection.extend({ model: definition.Document }); definition.PageView = definition.PageView || Backbone.View.extend({ }); data.documents = data.documents || new definition.DocumentSet(); views.pages = views.pages || new Backbone.Collection(); dc.embed.loadPage = function(url, opts){ var options = opts || {}; var id = definition.Document.extractId(url); var doc = new definition.Document({id: id}); data.documents.add(doc); doc.fetch({url: url}); }; })();
(function(){ var dc = window.dc; var $ = dc.$; var _ = dc._; var Backbone = dc.Backbone; var definition = dc.embed.definition; var data = dc.embed.data; var views = dc.embed.views; definition.Document = definition.Document || Backbone.Model.extend({}, { extractId: function(url){ return url.match(/(\d+[A-Za-z-]+).js(on)?$/)[1]; } }); definition.DocumentSet = definition.DocumentSet || Backbone.Collection.extend({ model: definition.Document }); definition.PageView = definition.PageView || Backbone.View.extend({ }); data.documents = data.documents || new definition.DocumentSet(); views.pages = views.pages || new Backbone.Collection(); dc.embed.loadPage = function(url, opts){ var options = opts || {}; var id = definition.Document.extractId(url); var doc = new definition.Document({id: id}); data.documents.add(doc); doc.fetch({url: url}); }; })();
Add two new constructor to renderable string. Signed-off-by: Clement Escoffier <6397137e57d1f87002962a37058f2a1c76fca9db@gmail.com>
package org.ow2.chameleon.wisdom.api.bodies; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.io.IOUtils; import org.ow2.chameleon.wisdom.api.http.Context; import org.ow2.chameleon.wisdom.api.http.Renderable; import org.ow2.chameleon.wisdom.api.http.Result; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Map; /** * A renderable object taking a String as parameter. */ public class RenderableString implements Renderable { //TODO Support encoding private final String rendered; public RenderableString(String object) { rendered = object; } public RenderableString(StringBuilder object) { rendered = object.toString(); } public RenderableString(StringBuffer object) { rendered = object.toString(); } public RenderableString(Object object) { rendered = object.toString(); } @Override public InputStream render(Context context, Result result) throws Exception { return new ByteArrayInputStream(rendered.getBytes()); } @Override public long length() { return rendered.length(); } }
package org.ow2.chameleon.wisdom.api.bodies; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.io.IOUtils; import org.ow2.chameleon.wisdom.api.http.Context; import org.ow2.chameleon.wisdom.api.http.Renderable; import org.ow2.chameleon.wisdom.api.http.Result; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Map; /** * A renderable object taking a String as parameter. */ public class RenderableString implements Renderable { //TODO Support encoding private final String rendered; public RenderableString(String object) { rendered = object; } public RenderableString(Object object) { rendered = object.toString(); } @Override public InputStream render(Context context, Result result) throws Exception { return new ByteArrayInputStream(rendered.getBytes()); } @Override public long length() { return rendered.length(); } }
Rename method sign-> isClockwise, simplify contains method body.
package com.sdsmdg.kd.trianglify.models; import android.graphics.Point; public class Triangle { public Point a; public Point b; public Point c; public Triangle (Point a, Point b, Point c) { this.a = a; this.b = b; this.c = c; } private boolean isClockwise (Point p1, Point p2, Point p3) { return (p1.x - p3.x) * (p2.y - p3.y) - (p1.y - p3.y) * (p2.x - p3.x) < 0f; } public boolean contains (Point p) { return isClockwise(p, a, b) == isClockwise(p, b, c) == isClockwise(p, c, a); } }
package com.sdsmdg.kd.trianglify.models; import android.graphics.Point; public class Triangle { public Point a; public Point b; public Point c; public Triangle (Point a, Point b, Point c) { this.a = a; this.b = b; this.c = c; } private float sign (Point p1, Point p2, Point p3) { return (p1.x - p3.x) * (p2.y - p3.y) - (p1.y - p3.y) * (p2.x - p3.x); } public boolean contains (Point p) { boolean pab, pbc, pca; pab = sign(p, a, b) < 0f; pbc = sign(p, b, c) < 0f; if (pab == pbc) return false; pca = sign(p, c, a) < 0f; return (pab == pca); } }
Delete cleaned up default true selectorContextIncludeRunId flag PiperOrigin-RevId: 461172350
/* * Copyright 2021 Google LLC * * 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.android.as.oss.fl.federatedcompute.config; /** Interface to add and override PCS-specific flags. */ public abstract class PcsFcFlags { /** Whether to read FC flags from DeviceConfig. */ public abstract boolean enableDeviceConfigOverrides(); /** Percentage of messages to be logged. */ public int logSamplingPercentage() { return 0; } /** Maximum size of serialized atoms logged by PCS. */ public int maxSerializedAtomSize() { return 0; } /** Whether or not PCS should log error message strings from federated compute. */ public boolean allowLoggingErrorMessage() { return false; } /** Whether or not SecAggClientLogEvents should be logged. */ public boolean allowLoggingSecAggClientEvent() { return false; } }
/* * Copyright 2021 Google LLC * * 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.android.as.oss.fl.federatedcompute.config; /** Interface to add and override PCS-specific flags. */ public abstract class PcsFcFlags { /** Whether to read FC flags from DeviceConfig. */ public abstract boolean enableDeviceConfigOverrides(); /** Percentage of messages to be logged. */ public int logSamplingPercentage() { return 0; } /** Maximum size of serialized atoms logged by PCS. */ public int maxSerializedAtomSize() { return 0; } /** Whether or not PCS should log error message strings from federated compute. */ public boolean allowLoggingErrorMessage() { return false; } /** Whether or not SecAggClientLogEvents should be logged. */ public boolean allowLoggingSecAggClientEvent() { return false; } @Override public boolean selectorContextIncludeRunId() { return true; } }
Use better method names in unit test of magic packet
package eu.nerro.wolappla.entity; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; public class MagicPacketTest { @Test public void getSynchronizationStream_shouldNotBeNull() { MagicPacket magicPacket = new MagicPacket(); byte[] synchronizationStream = magicPacket.getSynchronizationStream(); assertThat(synchronizationStream, is(notNullValue())); } @Test public void getSynchronizationStream_arrayLengthShouldBeSix() { MagicPacket magicPacket = new MagicPacket(); byte[] stream = magicPacket.getSynchronizationStream(); assertThat(stream.length, is(6)); } @Test public void getSynchronizationStream_shouldContainSixBytesOf0xFF() { MagicPacket magicPacket = new MagicPacket(); byte[] actualStream = magicPacket.getSynchronizationStream(); byte[] expectedStream = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; assertThat(actualStream, equalTo(expectedStream)); } }
package eu.nerro.wolappla.entity; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; public class MagicPacketTest { @Test public void getSynchronizationStream_shouldNotBeNull() { MagicPacket magicPacket = new MagicPacket(); byte[] synchronizationStream = magicPacket.getSynchronizationStream(); assertThat(synchronizationStream, is(notNullValue())); } @Test public void getSynchronizationStream_lengthShouldBeSix() { MagicPacket magicPacket = new MagicPacket(); byte[] stream = magicPacket.getSynchronizationStream(); assertThat(stream.length, is(6)); } @Test public void getSynchronizationStream_shouldBeSixBytesOf0xff() { MagicPacket magicPacket = new MagicPacket(); byte[] actualStream = magicPacket.getSynchronizationStream(); byte[] expectedStream = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; assertThat(actualStream, equalTo(expectedStream)); } }
[Google] Add the possibility to get more details on an api error
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter\Google\Exception; use ErrorException; use GuzzleHttp\Message\Response, GuzzleHttp\Exception\ParseException; /** * Whenever the Api returns an unexpected result * * @author Baptiste Clavié <baptiste@wisembly.com> */ class ApiErrorException extends ErrorException { public function __construct(Response $response) { try { $this->details = $response->json(); $message = $this->details['error']['message']; } catch (ParseException $e) { $message = $response->getReasonPhrase(); } parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode()); } public function getDetails() { return $this->details; } }
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter\Google\Exception; use ErrorException; use GuzzleHttp\Message\Response, GuzzleHttp\Exception\ParseException; /** * Whenever the Api returns an unexpected result * * @author Baptiste Clavié <baptiste@wisembly.com> */ class ApiErrorException extends ErrorException { public function __construct(Response $response) { try { $json = $response->json(); $message = $json['error']['message']; } catch (ParseException $e) { $message = $response->getReasonPhrase(); } parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode()); } }
Use containsLocation() for URL handler processing
const fs = require('fs-plus') // Converts a query string parameter for a line or column number // to a zero-based line or column number for the Atom API. function getLineColNumber (numStr) { const num = parseInt(numStr || 0, 10) return Math.max(num - 1, 0) } function openFile (atom, {query}) { const {filename, line, column} = query atom.workspace.open(filename, { initialLine: getLineColNumber(line), initialColumn: getLineColNumber(column), searchAllPanes: true }) } function windowShouldOpenFile ({query}) { const {filename} = query const stat = fs.statSyncNoException(filename) return win => win.containsLocation({ pathToOpen: filename, exists: Boolean(stat), isFile: stat.isFile(), isDirectory: stat.isDirectory() }) } const ROUTER = { '/open/file': { handler: openFile, getWindowPredicate: windowShouldOpenFile } } module.exports = { create (atomEnv) { return function coreURIHandler (parsed) { const config = ROUTER[parsed.pathname] if (config) { config.handler(atomEnv, parsed) } } }, windowPredicate (parsed) { const config = ROUTER[parsed.pathname] if (config && config.getWindowPredicate) { return config.getWindowPredicate(parsed) } else { return () => true } } }
// Converts a query string parameter for a line or column number // to a zero-based line or column number for the Atom API. function getLineColNumber (numStr) { const num = parseInt(numStr || 0, 10) return Math.max(num - 1, 0) } function openFile (atom, {query}) { const {filename, line, column} = query atom.workspace.open(filename, { initialLine: getLineColNumber(line), initialColumn: getLineColNumber(column), searchAllPanes: true }) } function windowShouldOpenFile ({query}) { const {filename} = query return (win) => win.containsPath(filename) } const ROUTER = { '/open/file': { handler: openFile, getWindowPredicate: windowShouldOpenFile } } module.exports = { create (atomEnv) { return function coreURIHandler (parsed) { const config = ROUTER[parsed.pathname] if (config) { config.handler(atomEnv, parsed) } } }, windowPredicate (parsed) { const config = ROUTER[parsed.pathname] if (config && config.getWindowPredicate) { return config.getWindowPredicate(parsed) } else { return (win) => true } } }
Update example with newer tied layer specification.
#!/usr/bin/env python import matplotlib.pyplot as plt import theanets from utils import load_mnist, plot_layers, plot_images train, valid, _ = load_mnist() e = theanets.Experiment( theanets.Autoencoder, layers=(784, 256, 64, 36, ('tied', 64), ('tied', 256), ('tied', 784)), train_batches=100, ) e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1) e.train(train, valid) plot_layers([e.network.find(i, 'w') for i in (1, 2, 3)], tied_weights=True) plt.tight_layout() plt.show() valid = valid[:16*16] plot_images(valid, 121, 'Sample data') plot_images(e.network.predict(valid), 122, 'Reconstructed data') plt.tight_layout() plt.show()
#!/usr/bin/env python import matplotlib.pyplot as plt import theanets from utils import load_mnist, plot_layers, plot_images train, valid, _ = load_mnist() e = theanets.Experiment( theanets.Autoencoder, layers=(784, 256, 64, 36, 64, 256, 784), train_batches=100, tied_weights=True, ) e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1) e.train(train, valid) plot_layers([e.network.find(i, 0) for i in (1, 2, 3)], tied_weights=True) plt.tight_layout() plt.show() valid = valid[:16*16] plot_images(valid, 121, 'Sample data') plot_images(e.network.predict(valid), 122, 'Reconstructed data') plt.tight_layout() plt.show()
Remove initDependencies from composer service provider
<?php namespace OpenDominion\Providers; use Cache; use Illuminate\Contracts\View\View; use Illuminate\Support\ServiceProvider; use OpenDominion\Calculators\NetworthCalculator; class ComposerServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function boot() { view()->composer('partials.main-footer', function (View $view) { $version = (Cache::has('version') ? Cache::get('version') : 'unknown'); $view->with('version', $version); }); // todo: do we need this here in this class? view()->composer('partials.resources-overview', function (View $view) { $networthCalculator = app(NetworthCalculator::class); $view->with('networthCalculator', $networthCalculator); }); } /** * Register the service provider. * * @return void */ public function register() { // } }
<?php namespace OpenDominion\Providers; use Cache; use Illuminate\Contracts\View\View; use Illuminate\Support\ServiceProvider; use OpenDominion\Calculators\NetworthCalculator; use OpenDominion\Services\DominionSelectorService; class ComposerServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function boot() { view()->composer('partials.main-footer', function (View $view) { $version = (Cache::has('version') ? Cache::get('version') : 'unknown'); $view->with('version', $version); }); view()->composer('partials.resources-overview', function (View $view) { $networthCalculator = app(NetworthCalculator::class); $networthCalculator->initDependencies(); $view->with('networthCalculator', $networthCalculator); }); } /** * Register the service provider. * * @return void */ public function register() { // } }
Fix that HTTP status code was not passed on The bootstrap file is supposed to return the HTTP status code to send to the browser, because `http_response_code()` is only available as of PHP 5.4. This return value was not passed on from the anonymous function to the ResponseFactory.
<?php /* * (c) webfactory GmbH <info@webfactory.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Webfactory\Bundle\LegacyIntegrationBundle\Integration; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; class BootstrapFileKernelAdaptor implements HttpKernelInterface { protected $file; public function __construct($filename) { $this->file = $filename; } public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { $file = $this->file; return LegacyCaptureResponseFactory::create(function () use ($file, $request) { return include($file); }); } }
<?php /* * (c) webfactory GmbH <info@webfactory.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Webfactory\Bundle\LegacyIntegrationBundle\Integration; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; class BootstrapFileKernelAdaptor implements HttpKernelInterface { protected $file; public function __construct($filename) { $this->file = $filename; } public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { $file = $this->file; return LegacyCaptureResponseFactory::create(function () use ($file, $request) { include($file); }); } }
Remove promise from NPM dependencies Meteor has https://github.com/meteor/promise already.
Package.describe({ summary: 'Minifiers for Meteor with PostCSS processing - use Autoprefixer and others with ease', version: '0.2.4', name: 'juliancwirko:postcss', git: 'https://github.com/juliancwirko/meteor-postcss.git' }); Package.registerBuildPlugin({ name: 'minifiers-postcss', use: [ 'ecmascript@0.1.6', 'minifiers@1.1.7' ], npmDependencies: { 'source-map': '0.5.3', 'postcss': '5.0.12', 'app-module-path': '1.0.5' }, sources: [ 'plugin/minify-js.js', 'plugin/minify-css.js' ] }); Package.onUse(function(api) { api.use('meteorhacks:npm@1.5.0', ['client']); api.use('isobuild:minifier-plugin@1.0.0'); }); Package.onTest(function(api) { });
Package.describe({ summary: 'Minifiers for Meteor with PostCSS processing - use Autoprefixer and others with ease', version: '0.2.4', name: 'juliancwirko:postcss', git: 'https://github.com/juliancwirko/meteor-postcss.git' }); Package.registerBuildPlugin({ name: 'minifiers-postcss', use: [ 'ecmascript@0.1.6', 'minifiers@1.1.7' ], npmDependencies: { 'source-map': '0.5.3', 'postcss': '5.0.12', 'es6-promise': '3.0.2', 'app-module-path': '1.0.5' }, sources: [ 'plugin/minify-js.js', 'plugin/minify-css.js' ] }); Package.onUse(function(api) { api.use('meteorhacks:npm@1.5.0', ['client']); api.use('isobuild:minifier-plugin@1.0.0'); }); Package.onTest(function(api) { });
Make the position of the roms work for everybody. Here you previously used a directory that mentions your particular setting. Substitute it by a relative directory so it works for everybody. Also, suggest at the read file to create a 'rome' directory with 'breakout.bin' in it.
"""This script launches all of the processes necessary to train a deep Q-network on an ALE game. Usage: ale_run.py [--glue_port GLUE_PORT] All unrecognized command line arguments will be passed on to rl_glue_ale_agent.py """ import subprocess import sys import os import argparse # Put your binaries under the directory 'deep_q_rl/roms' ROM_PATH = "../roms/breakout.bin" # Check for glue_port command line argument and set it up... parser = argparse.ArgumentParser(description='Neural rl agent.') parser.add_argument('--glue_port', type=str, default="4096", help='rlglue port (default 4096)') args, unknown = parser.parse_known_args() my_env = os.environ.copy() my_env["RLGLUE_PORT"] = args.glue_port # Start the necessary processes: p1 = subprocess.Popen(['rl_glue'], env=my_env) ale_string = ("ale -game_controller rlglue -frame_skip 4 " "-restricted_action_set true ") p2 = subprocess.Popen(ale_string + ROM_PATH, shell=True, env=my_env) p3 = subprocess.Popen(['./rl_glue_ale_experiment.py'], env=my_env) p4 = subprocess.Popen(['./rl_glue_ale_agent.py'] + sys.argv[1:], env=my_env) p1.wait() p2.wait() p3.wait() p4.wait()
"""This script launches all of the processes necessary to train a deep Q-network on an ALE game. Usage: ale_run.py [--glue_port GLUE_PORT] All unrecognized command line arguments will be passed on to rl_glue_ale_agent.py """ import subprocess import sys import os import argparse ROM_PATH = "/home/spragunr/neural_rl_libraries/roms/breakout.bin" # Check for glue_port command line argument and set it up... parser = argparse.ArgumentParser(description='Neural rl agent.') parser.add_argument('--glue_port', type=str, default="4096", help='rlglue port (default 4096)') args, unknown = parser.parse_known_args() my_env = os.environ.copy() my_env["RLGLUE_PORT"] = args.glue_port # Start the necessary processes: p1 = subprocess.Popen(['rl_glue'], env=my_env) ale_string = ("ale -game_controller rlglue -frame_skip 4 " "-restricted_action_set true ") p2 = subprocess.Popen(ale_string + ROM_PATH, shell=True, env=my_env) p3 = subprocess.Popen(['./rl_glue_ale_experiment.py'], env=my_env) p4 = subprocess.Popen(['./rl_glue_ale_agent.py'] + sys.argv[1:], env=my_env) p1.wait() p2.wait() p3.wait() p4.wait()
Change to use Ember.$ on revision table
import Ember from 'ember'; import layout from './template'; /** * @module ember-osf * @submodule components */ /** * Display information about one revision of a file * * Sample usage: * ```handlebars * {{file-version * version=version * download='download' * currentVersion=currentVersion * versionUrl='versionUrl'}} * ``` * @class file-version */ export default Ember.Component.extend({ layout, classNames: ['file-version'], tagName: 'tr', currentVersion: null, versionUrl: null, clickable: Ember.computed('version', 'currentVersion', function() { return this.get('version.id') != this.get('currentVersion'); }), actions: { downloadVersion(version) { this.attrs.download(version); }, changeVersion(version) { this.attrs.versionChange(version); }, copyLink(id) { Ember.$('#'+id).select(); document.execCommand('copy'); } } });
import Ember from 'ember'; import layout from './template'; /** * @module ember-osf * @submodule components */ /** * Display information about one revision of a file * * Sample usage: * ```handlebars * {{file-version * version=version * download='download' * currentVersion=currentVersion * versionUrl='versionUrl'}} * ``` * @class file-version */ export default Ember.Component.extend({ layout, classNames: ['file-version'], tagName: 'tr', currentVersion: null, versionUrl: null, clickable: Ember.computed('version', 'currentVersion', function() { return this.get('version.id') != this.get('currentVersion'); }), actions: { downloadVersion(version) { this.attrs.download(version); }, changeVersion(version) { this.attrs.versionChange(version); }, copyLink(id) { $('#'+id).select(); document.execCommand('copy'); } } });
Fix unit tests for Version.objects.get_current(). The unit tests assumed that no Version objects were present, but this wasn't always the case. This clears them before the test runs.
from datetime import datetime from django.test.testcases import TestCase from django_evolution.models import Version class VersionManagerTests(TestCase): """Unit tests for django_evolution.models.VersionManager.""" def test_current_version_with_dup_timestamps(self): """Testing Version.current_version() with two entries with same timestamps""" # Remove anything that may already exist. Version.objects.all().delete() timestamp = datetime(year=2015, month=12, day=10, hour=12, minute=13, second=14) Version.objects.create(signature='abc123', when=timestamp) version = Version.objects.create(signature='abc123-def456', when=timestamp) latest_version = Version.objects.current_version() self.assertEqual(latest_version, version)
from datetime import datetime from django.test.testcases import TestCase from django_evolution.models import Version class VersionManagerTests(TestCase): """Unit tests for django_evolution.models.VersionManager.""" def test_current_version_with_dup_timestamps(self): """Testing Version.current_version() with two entries with same timestamps""" timestamp = datetime(year=2015, month=12, day=10, hour=12, minute=13, second=14) Version.objects.create(signature='abc123', when=timestamp) version = Version.objects.create(signature='abc123-def456', when=timestamp) latest_version = Version.objects.current_version() self.assertEqual(latest_version, version)
Add iterator to the armor set for convenience
package info.u_team.u_team_core.item.armor; import java.util.Iterator; import com.google.common.collect.Iterators; import net.minecraftforge.fml.RegistryObject; public class ArmorSet implements Iterable<RegistryObject<? extends UArmorItem>> { private final RegistryObject<UHelmetItem> helmet; private final RegistryObject<UChestplateItem> chestplate; private final RegistryObject<ULeggingsItem> leggings; private final RegistryObject<UBootsItem> boots; public ArmorSet(RegistryObject<UHelmetItem> helmet, RegistryObject<UChestplateItem> chestplate, RegistryObject<ULeggingsItem> leggings, RegistryObject<UBootsItem> boots) { this.helmet = helmet; this.chestplate = chestplate; this.leggings = leggings; this.boots = boots; } public RegistryObject<UHelmetItem> getHelmet() { return helmet; } public RegistryObject<UChestplateItem> getChestplate() { return chestplate; } public RegistryObject<ULeggingsItem> getLeggings() { return leggings; } public RegistryObject<UBootsItem> getBoots() { return boots; } @Override public Iterator<RegistryObject<? extends UArmorItem>> iterator() { return Iterators.forArray(helmet, chestplate, leggings, boots); } }
package info.u_team.u_team_core.item.armor; import net.minecraftforge.fml.RegistryObject; public class ArmorSet { private final RegistryObject<UHelmetItem> helmet; private final RegistryObject<UChestplateItem> chestplate; private final RegistryObject<ULeggingsItem> leggings; private final RegistryObject<UBootsItem> boots; public ArmorSet(RegistryObject<UHelmetItem> helmet, RegistryObject<UChestplateItem> chestplate, RegistryObject<ULeggingsItem> leggings, RegistryObject<UBootsItem> boots) { this.helmet = helmet; this.chestplate = chestplate; this.leggings = leggings; this.boots = boots; } public RegistryObject<UHelmetItem> getHelmet() { return helmet; } public RegistryObject<UChestplateItem> getChestplate() { return chestplate; } public RegistryObject<ULeggingsItem> getLeggings() { return leggings; } public RegistryObject<UBootsItem> getBoots() { return boots; } }
Fix original in map to pass validation. The generator _validateMapping function does not expect a mapping to contain `original` when `source` is undefined, but the code was passing in `{}`. This corrects the problem by ensuring original not defined when there is no source.
var SMConsumer = require('source-map').SourceMapConsumer; /** * @name mappingsFromMap * @function * @param map {Object} the JSON.parse()'ed map * @return {Array} array of mappings */ module.exports = function (map) { var consumer = new SMConsumer(map); var mappings = []; consumer.eachMapping(function (mapping) { // only set source if we have original position to handle edgecase (see inline-source-map tests) mappings.push({ original: mapping.originalColumn != null ? { column: mapping.originalColumn , line: mapping.originalLine } : undefined , generated: { column: mapping.generatedColumn , line: mapping.generatedLine } , source: mapping.originalColumn != null ? mapping.source : undefined , name: mapping.name }); }); return mappings; }
var SMConsumer = require('source-map').SourceMapConsumer; /** * @name mappingsFromMap * @function * @param map {Object} the JSON.parse()'ed map * @return {Array} array of mappings */ module.exports = function (map) { var consumer = new SMConsumer(map); var mappings = []; consumer.eachMapping(function (mapping) { // only set source if we have original position to handle edgecase (see inline-source-map tests) mappings.push({ original: { column: mapping.originalColumn , line: mapping.originalLine } , generated: { column: mapping.generatedColumn , line: mapping.generatedLine } , source: mapping.originalColumn != null ? mapping.source : undefined , name: mapping.name }); }); return mappings; }
Remove ' and " from css values to embed.
/** * juice * Copyright(c) 2011 LearnBoost <dev@learnboost.com> * MIT Licensed */ module.exports = exports = Property; /** * Module dependencies. */ var compare = require('./utils').compare /** * CSS property constructor. * * @param {String} property * @param {String} value * @param {Selector} selector the property originates from * @api public */ function Property (prop, value, selector) { this.prop = prop; this.value = value; this.selector = selector } /** * Compares with another Property based on Selector#specificity. * * @api public */ Property.prototype.compare = function (property) { var a = this.selector.specificity() , b = property.selector.specificity() , winner = compare(a, b) if (winner == a) return this; return property; }; /** * Returns CSS property * * @api public */ Property.prototype.toString = function () { return this.prop + ': ' + this.value.replace(/['"]+/g, '') + ';'; };
/** * juice * Copyright(c) 2011 LearnBoost <dev@learnboost.com> * MIT Licensed */ module.exports = exports = Property; /** * Module dependencies. */ var compare = require('./utils').compare /** * CSS property constructor. * * @param {String} property * @param {String} value * @param {Selector} selector the property originates from * @api public */ function Property (prop, value, selector) { this.prop = prop; this.value = value; this.selector = selector } /** * Compares with another Property based on Selector#specificity. * * @api public */ Property.prototype.compare = function (property) { var a = this.selector.specificity() , b = property.selector.specificity() , winner = compare(a, b) if (winner == a) return this; return property; }; /** * Returns CSS property * * @api public */ Property.prototype.toString = function () { return this.prop + ': ' + this.value + ';'; };
Add Redis enable/disable commands tests
<?php namespace Pantheon\Terminus\Tests\Functional; use Pantheon\Terminus\Tests\Traits\LoginHelperTrait; use Pantheon\Terminus\Tests\Traits\TerminusTestTrait; use PHPUnit\Framework\TestCase; /** * Class RedisCommandsTest * * @package Pantheon\Terminus\Tests\Functional */ class RedisCommandsTest extends TestCase { use TerminusTestTrait; use LoginHelperTrait; /** * @test * @covers \Pantheon\Terminus\Commands\Redis\EnableCommand * * @group redis * @group short */ public function testRedisEnable() { $this->terminus("redis:enable {$this->getSiteName()}"); } /** * @test * @covers \Pantheon\Terminus\Commands\Redis\DisableCommand * * @group redis * @group short */ public function testRedisDisable() { $this->terminus("redis:disable {$this->getSiteName()}"); } }
<?php namespace Pantheon\Terminus\Tests\Functional; use Pantheon\Terminus\Tests\Traits\LoginHelperTrait; use Pantheon\Terminus\Tests\Traits\SiteBaseSetupTrait; use Pantheon\Terminus\Tests\Traits\TerminusTestTrait; use Pantheon\Terminus\Tests\Traits\UrlStatusCodeHelperTrait; use PHPUnit\Framework\TestCase; /** * Class RedisCommandsTest * * @package Pantheon\Terminus\Tests\Functional */ class RedisCommandsTest extends TestCase { use TerminusTestTrait; use LoginHelperTrait; /** * @test * @covers \Pantheon\Terminus\Commands\Redis\EnableCommand * @covers \Pantheon\Terminus\Commands\Redis\DisableCommand * * @group redis * @gropu long */ public function testConnection() { $this->fail("To Be Written"); } }
Use `UnicodeText` instead of `Text` to ensure a unicode-capable column type is used in the backend
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.UnicodeText, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
""" byceps.services.news.models.channel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder from ..transfer.models import ChannelID class Channel(db.Model): """A channel to which news items can be published.""" __tablename__ = 'news_channels' id = db.Column(db.Unicode(40), primary_key=True) brand_id = db.Column(db.Unicode(20), db.ForeignKey('brands.id'), index=True, nullable=False) url_prefix = db.Column(db.Text, nullable=False) def __init__(self, channel_id: ChannelID, brand_id: BrandID, url_prefix: str) -> None: self.id = channel_id self.brand_id = brand_id self.url_prefix = url_prefix def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .add('brand', self.brand_id) \ .build()
Fix timing issue with map test.
var EC = protractor.ExpectedConditions; describe('con10t pages', function() { function click() { browser.waitForAngular(); return element.all(by.css('.ar-map-zoomcontrol-box')).get(0).getText().click(); } it('should contain markers on the grako_map page', function(done) { browser.get('/project/grako_map'); click().then(click).then(click).then(click).then(click).then(function() { var marker = element(by.css('.leaflet-marker-icon')); browser.wait(EC.presenceOf(marker), 10000); expect(marker.isPresent()).toBe(true); done(); }) }); });
var EC = protractor.ExpectedConditions; describe('con10t pages', function() { function click() { element.all(by.css('.ar-map-zoomcontrol-box')).get(0).getText(); // hack to slow it down return element.all(by.css('.ar-map-zoomcontrol-box')).get(0).getText().click(); } it('should contain markers on the grako_map page', function(done) { browser.get('/project/grako_map'); click().then(click).then(click).then(click).then(click).then(click).then(function() { var marker = element(by.css('.leaflet-marker-icon')); browser.wait(EC.presenceOf(marker), 10000); expect(marker.isPresent()).toBe(true); done(); }) }); });
Add Field and Searchable to annotations
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\Search\Mapping\Annotations; use Doctrine\Common\Annotations\Annotation; /** * @Annotation * @Target("PROPERTY") */ final class Field {} /** * @Annotation * @Target("CLASS") */ final class Searchable {}
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\Search\Mapping\Annotations; use Doctrine\Common\Annotations\Annotation;
Add the test case for thClick
var expect = require('chai').expect; var sinon = require('sinon'); var ColumnShifter = require('component/grid/projection/column-shifter'); var Base = require('component/grid/projection/base'); var Response = require( 'component/grid/model/response'); describe('projection ColumnShifter', function () { it('update should run normal', function() { var model = new ColumnShifter(); var originalData = new Base(); originalData.data = new Response({ columns: [ {name: 'hello', property: 'name'}, {id: '007', property: 'id'} ] }); originalData.pipe(model); expect(model.data.get('columns')[0]['property']).to.be.equal('column.skip.less'); expect(model.data.get('columns')[3]['property']).to.be.equal('column.skip.more'); }); it('thClick should run normal', function() { var model = new ColumnShifter(); model.get = sinon.stub().returns(1); sinon.spy(model, 'set'); console.log(model.get('column.skip')); model.thClick({}, { column: {$metadata: {enabled: true}}, property: 'column.skip.less' }); expect(model.set.calledWith({'column.skip': 0})).to.be.true; }); });
var expect = require('chai').expect; var sinon = require('sinon'); var ColumnShifter = require('component/grid/projection/column-shifter'); var Base = require('component/grid/projection/base'); var Response = require( 'component/grid/model/response'); describe('projection ColumnShifter', function () { it('update should run normal', function() { var model = new ColumnShifter(); var originalData = new Base(); originalData.data = new Response({ columns: [ {name: 'hello', property: 'name'}, {id: '007', property: 'id'} ] }); originalData.pipe(model); expect(model.data.get('columns')[0]['property']).to.be.equal('column.skip.less'); expect(model.data.get('columns')[3]['property']).to.be.equal('column.skip.more'); }); });
Update Conversation's form : add field recipients
<?php namespace FireDIY\PrivateMessageBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ConversationType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('recipients') ->add('subject') ->add('firstMessage', PrivateMessageType::class); } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'FireDIY\PrivateMessageBundle\Entity\Conversation' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'firediy_privatemessagebundle_conversation'; } }
<?php namespace FireDIY\PrivateMessageBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ConversationType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('subject') ->add('firstMessage', PrivateMessageType::class) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'FireDIY\PrivateMessageBundle\Entity\Conversation' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'firediy_privatemessagebundle_conversation'; } }
Handle HTTP Error 410 when checking blog post
""" Validator functions """ from urllib import request from urllib.error import HTTPError from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" try: online_resource = request.urlopen(url) except HTTPError as exception: if exception.code == 410: raise ValidationError("Online document was removed.") # This is the code returned by Google Drive # Need to test if website didn't redirect the request to another resource. if url != online_resource.geturl() or online_resource.getcode() != 200: raise ValidationError("Can't access online document.") def pdf(value): """Check if filename looks like a PDF file.""" filename = value.name.lower() if not filename.endswith(".pdf"): raise ValidationError("File name doesn't look to be a PDF file.") try: pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable except: raise ValidationError("File doesn't look to be a PDF file.")
""" Validator functions """ from urllib import request from django.core.exceptions import ValidationError import PyPDF2 def online_document(url): """Check if online document is available.""" online_resource = request.urlopen(url) # Need to test if website didn't redirect the request to another resource. if url != online_resource.geturl() or online_resource.getcode() != 200: raise ValidationError("Can't access online document.") def pdf(value): """Check if filename looks like a PDF file.""" filename = value.name.lower() if not filename.endswith(".pdf"): raise ValidationError("File name doesn't look to be a PDF file.") try: pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable except: raise ValidationError("File doesn't look to be a PDF file.")
Fix compilation error in RN 0.47.0
package com.poberwong.launcher; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by poberwong on 16/6/30. */ public class IntentLauncherPackage implements ReactPackage{ @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new IntentLauncherModule(reactContext)); // 返回一个NativeModule范型的数组就ok } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package com.poberwong.launcher; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by poberwong on 16/6/30. */ public class IntentLauncherPackage implements ReactPackage{ @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new IntentLauncherModule(reactContext)); // 返回一个NativeModule范型的数组就ok } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Add test_is_coord_on_board() to assert the function returns True if the coordinate is on the board and False otherwise
import engine VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_COORDS = [ (0, 0), (-1, -1), (96, 49), (96, 48), (105, 49), (104, 48), (96, 56), (97, 57), (105, 56), (104, 57) ] VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_A1 = ['a0', 'a9', 'h0', 'h9', 'z1', 'z8'] def test_coord_to_a1(): for coord in VALID_COORDS: assert engine._coord_to_a1.get(coord, False) is not False for coord in INVALID_COORDS: assert engine._coord_to_a1.get(coord, False) is False def test_a1_to_coord(): for a1 in VALID_A1: assert engine._a1_to_coord.get(a1, False) is not False for a1 in INVALID_A1: assert engine._a1_to_coord.get(a1, False) is False def test_is_coord_on_board(): for coord in VALID_COORDS: assert engine._is_coord_on_board(coord) is True for coord in INVALID_COORDS: assert engine._is_coord_on_board(coord) is False
import engine VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_COORDS = [ (0, 0), (-1, -1), (96, 49), (96, 48), (105, 49), (104, 48), (96, 56), (97, 57), (105, 56), (104, 57) ] VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)] INVALID_A1 = ['a0', 'a9', 'h0', 'h9', 'z1', 'z8'] def test_coord_to_a1(): for coord in VALID_COORDS: assert engine._coord_to_a1.get(coord, False) is not False for coord in INVALID_COORDS: assert engine._coord_to_a1.get(coord, False) is False def test_a1_to_coord(): for a1 in VALID_A1: assert engine._a1_to_coord.get(a1, False) is not False for a1 in INVALID_A1: assert engine._a1_to_coord.get(a1, False) is False
Fix some warnings about playerlist
import React from 'react' import PlayerListRow from './PlayerListRow' import './PlayerList.css' /*const colors = [ 'firebrick', 'hotpink', 'tomato', 'peachpuff', 'thistle', 'darkorchid', 'plategreen', 'mediumaquamarine', 'plateturquoise', 'lightsteelblue', 'wheat', 'mistyrose' ]*/ const PlayerList = ({ userIds }) => ( <div className="PlayerList"> <div className="title">Current Players</div> <ul className="PlayerList-list"> {userIds && userIds.length > 0 ? userIds.map(userId => <PlayerListRow userId={userId}/>) : <div className="PlayerList-empty">Game currently has no players. Share the game code with your friends!</div> } </ul> </div> ) export default PlayerList
import React from 'react' import PlayerListRow from './PlayerListRow' import UserColor from './UserColor' import UserName from './Username' import './PlayerList.css' const colors = [ 'firebrick', 'hotpink', 'tomato', 'peachpuff', 'thistle', 'darkorchid', 'plategreen', 'mediumaquamarine', 'plateturquoise', 'lightsteelblue', 'wheat', 'mistyrose' ] const PlayerList = ({ userIds }) => ( <div className="PlayerList"> <div className="title">Current Players</div> <ul className="PlayerList-list"> {userIds && userIds.length > 0 ? userIds.map(userId => <li className="PlayerList-player" > <UserColor userId={userId} /> <UserName userId={userId} /> </li>) : <div className="PlayerList-empty">Game currently has no players. Share the game code with your friends!</div> } </ul> </div> ) export default PlayerList
Print rule difference between good and bad sets.
class ContractDebugger: def __init__(self, pathCondGen): self.pathCondGen = pathCondGen def explain_failures(self, contract_name, contract, success_pcs, failed_pcs): print("Explaining why contract fails: " + contract_name) # print("Success PCs: ") # print(success_pcs) # print("Failed PCs: ") # print(failed_pcs) self.get_rule_differences(success_pcs, failed_pcs) def get_rule_differences(self, success_pcs, failed_pcs): rules_in_success = self.get_rules(success_pcs) rules_in_failed = self.get_rules(failed_pcs) good_rules = sorted([rule for rule in rules_in_success if not rule in rules_in_failed]) bad_rules = sorted([rule for rule in rules_in_failed if not rule in rules_in_success]) print("Good rules: (Rules in success set and not failure set)") print(good_rules) print("Bad rules: (Rules in failure set and not success set)") print(bad_rules) def get_rules(self, pcs): rules = [] for pc in pcs: rules += self.pathCondGen.rules_in_pc_real_name(pc) return list(set(rules))
class ContractDebugger: def __init__(self, pathCondGen): self.pathCondGen = pathCondGen def explain_failures(self, contract_name, contract, success_pcs, failed_pcs): print("Explaining why contract fails: " + contract_name) print(success_pcs) print(failed_pcs) self.get_rule_differences(success_pcs, failed_pcs) def get_rule_differences(self, success_pcs, failed_pcs): rules_in_success = self.get_rules(success_pcs) rules_in_failed = self.get_rules(failed_pcs) good_rules = [rule for rule in rules_in_success if not rule in rules_in_failed] bad_rules = [rule for rule in rules_in_failed if not rule in rules_in_success] print("Good rules: (Rules in success set and not failure set)") print(good_rules) print("Bad rules: (Rules in failure set and not success set)") print(bad_rules) def get_rules(self, pcs): rules = [] for pc in pcs: r = self.pathCondGen.rules_in_pc_real_name(pc) print(r) return rules
Add test for fudge serialization of LocalDate.ALL
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.util.time; import org.testng.annotations.Test; import org.threeten.bp.LocalDate; import com.opengamma.util.test.AbstractFudgeBuilderTestCase; /** * Test Fudge encoding. */ @Test(groups = "unit") public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase { public void test_inclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_exclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_all() { assertEncodeDecodeCycle(LocalDateRange.class, LocalDateRange.ALL); } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.util.time; import org.testng.annotations.Test; import org.threeten.bp.LocalDate; import com.opengamma.util.test.AbstractFudgeBuilderTestCase; /** * Test Fudge encoding. */ @Test(groups = "unit") public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase { public void test_inclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true); assertEncodeDecodeCycle(LocalDateRange.class, range); } public void test_exclusive() { LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false); assertEncodeDecodeCycle(LocalDateRange.class, range); } }
Check element before performing calculations
import Ember from "ember"; export default Ember.Mixin.create({ windowResized: function() { this.calcPageRectangle(); }, didInsertElement: function() { Ember.$(window).on('resize', this.windowResized.bind(this)); this.calcPageRectangle(); }, calcPageRectangle: function() { var innerWrap = Ember.$('.inner-wrap'), el = this.$(), nav, header, remainingHeight; if(!el) { return; } nav = Ember.$('nav.tab-bar'); header = Ember.$('header'); remainingHeight = innerWrap.height() - nav.height() - (header.height()||0); this.set('sizingRect', { width: el.width(), height: remainingHeight }); }, sizingRectStyle: function() { var rect = this.get('sizingRect'); if(!rect) { return ""; } return "height: "+rect.height+"px"; }.property('sizingRect.width', 'sizingRect.height'), willDestroyElement: function() { Ember.$(window).off('resize', this.windowResized); } });
import Ember from "ember"; export default Ember.Mixin.create({ windowResized: function() { this.calcPageRectangle(); }, didInsertElement: function() { Ember.$(window).on('resize', this.windowResized.bind(this)); this.calcPageRectangle(); }, calcPageRectangle: function() { var innerWrap = Ember.$('.inner-wrap'), el = this.$(), nav = Ember.$('nav.tab-bar'), header = Ember.$('header'), remainingHeight = innerWrap.height() - nav.height() - (header.height()||0); this.set('sizingRect', { width: el.width(), height: remainingHeight }); }, sizingRectStyle: function() { var rect = this.get('sizingRect'); if(!rect) { return ""; } return "height: "+rect.height+"px"; }.property('sizingRect.width', 'sizingRect.height'), willDestroyElement: function() { Ember.$(window).off('resize', this.windowResized); } });
Transform OAuth errors so they can be used by HTML templates
'use strict'; /** * Translates user creation errors into an end-user friendly userMessage * @param {*} err */ function oktaErrorTransformer(err) { if (err && err.errorCauses) { err.errorCauses.forEach(function (cause) { if (cause.errorSummary === 'login: An object with this field already exists in the current organization') { err.userMessage = 'An account with that email address already exists.'; } else if (!err.userMessage) { // This clause allows the first error cause to be returned to the user err.userMessage = cause.errorSummary; } }); } // For OAuth errors if (err && err.error_description) { err.message = err.error_description; } if (err && err.error === 'invalid_grant') { err.status = 400; err.code = 7104; err.message = 'Invalid username or password.'; } return err; } module.exports = oktaErrorTransformer;
'use strict'; /** * Translates user creation errors into an end-user friendly userMessage * @param {*} err */ function oktaErrorTransformer(err) { if (err && err.errorCauses) { err.errorCauses.forEach(function (cause) { if (cause.errorSummary === 'login: An object with this field already exists in the current organization') { err.userMessage = 'An account with that email address already exists.'; } else if (!err.userMessage) { // This clause allows the first error cause to be returned to the user err.userMessage = cause.errorSummary; } }); } if (err && err.error === 'invalid_grant') { err.status = 400; err.code = 7104; err.message = 'Invalid username or password.'; } return err; } module.exports = oktaErrorTransformer;
Add some more information about the speakers for the 24th.
<a href="assets/images/new31.jpg" target="_blank"><img src="assets/images/new31.jpg" alt="New US 31 Hamilton County" align="right" /></a> <p>Coming to us from <a href="http://chacompanies.com" target="_blank">CHA Companies</a> is Jason Rowley, a consultant working for <a href="http://www.in.gov/indot/" target="_blank">INDOT</a>'s <a href="http://us31hamiltoncounty.in.gov" target="_blank">New US 31</a> road project in Hamilton County. Joining Jason is Michelle Kearns from <a href="http://www.empowerresults.com">Empower Results</a>.</p> <p>The New US 31 Hamilton County team will provide IREX members with an overview of the project that will upgrade US 31 to freeway standards from I-465 at the Marion-Hamilton county line, through Carmel and Westfield to SR 38. In terms of dollars, this will be the largest and most aggressive road project ever completed in Hamilton County.</p> <p>The presentation will include a review of completed and upcoming construction, as well as the opportunity for IREX members to ask specific questions about the project.</p>
<a href="assets/images/new31.jpg" target="_blank"><img src="assets/images/new31.jpg" alt="New US 31 Hamilton County" align="right" /></a> <p>Coming to us from <a href="http://chacompanies.com" target="_blank">CHA Companies</a> is Jason Rowley, a consultant working for <a href="http://www.in.gov/indot/" target="_blank">INDOT</a>'s <a href="http://us31hamiltoncounty.in.gov" target="_blank">New US 31</a> road project in Hamilton County.</p> <p>Joining Jason is Michelle Kearns from <a href="http://www.empowerresults.com">Empower Results</a>.</p> <p>The New US 31 Hamilton County team will provide IREX members with an overview of the project that will upgrade US 31 to freeway standards from I-465 at the Marion-Hamilton county line, through Carmel and Westfield to SR 38. In terms of dollars, this will be the largest and most aggressive road project ever completed in Hamilton County.</p>
Fix test for TravisCi Strategy
<?php namespace Joli\JoliCi\BuildStrategy; use org\bovigo\vfs\vfsStream; use Joli\JoliCi\BuildStrategy\TravisCiBuildStrategy; class TravisCiBuildStrategyTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->buildPath = vfsStream::setup('build-path'); $this->strategy = new TravisCiBuildStrategy(vfsStream::url('build-path'), __DIR__."/../../../../resources/travisci"); } public function testSupportTrue() { $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project1"); $this->assertTrue($support); } public function testSupportFalse() { $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project2"); $this->assertFalse($support); } }
<?php namespace Joli\JoliCi; use org\bovigo\vfs\vfsStream; use Joli\JoliCi\BuildStrategy\TravisCiBuildStrategy; class TravisCiBuildStrategyTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->buildPath = vfsStream::setup('build-path'); $this->strategy = new TravisCiBuildStrategy(vfsStream::url('build-path')); } public function testSupportTrue() { $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project1"); $this->assertTrue($support); } public function testSupportFalse() { $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project2"); $this->assertFalse($support); } }
Send hideSubmit prop to form
import React, { Component } from 'react'; import { Button, ButtonGroup, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import FontAwesome from 'react-fontawesome'; export default class ModalForm extends Component { render() { return ( <Modal isOpen={this.props.isOpen} toggle={this.props.toggle}> <ModalHeader toggle={this.toggle}>New Link</ModalHeader> <ModalBody> <this.props.form hideSubmit={ true } onSubmit={this.props.onSubmit} /> </ModalBody> <ModalFooter> <Button color="primary" disabled={ this.props.disabled } onClick={this.props.onSubmitClick}>Submit</Button>{' '} <Button color="secondary" onClick={ this.props.toggle }>Cancel</Button> </ModalFooter> </Modal> ); } }
import React, { Component } from 'react'; import { Button, ButtonGroup, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import FontAwesome from 'react-fontawesome'; export default class ModalForm extends Component { render() { return ( <Modal isOpen={this.props.isOpen} toggle={this.props.toggle}> <ModalHeader toggle={this.toggle}>New Link</ModalHeader> <ModalBody> <this.props.form onSubmit={this.props.onSubmit} /> </ModalBody> <ModalFooter> <Button color="primary" disabled={ this.props.disabled } onClick={this.props.onSubmitClick}>Submit</Button>{' '} <Button color="secondary" onClick={ this.props.toggle }>Cancel</Button> </ModalFooter> </Modal> ); } }
Fix issue with null data.
<?php namespace UWaterlooAPI\Data\JSON\Common\Components; class ComponentFactory { /** * Builds the given component using the given array as the data input. * * @param array|null $data * @param string $component * * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null */ public static function buildComponent($data, $component) { return empty($data) ? null : new $component($data); } /** * Builds the given component using the first element of the given array as the data input. * * @param array $data * @param string $component * * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null */ public static function buildComponentArray(array $data, $component) { return empty($data) ? null : new $component(reset($data)); } /** * Builds an array of components using the elements of the given array as the data input. * * @param array $data * @param string $component * * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null */ public static function buildComponents(array $data, $component) { return array_map(function ($element) use ($component) { return new $component($element); }, $data); } }
<?php namespace UWaterlooAPI\Data\JSON\Common\Components; class ComponentFactory { /** * Builds the given component using the given array as the data input. * * @param array $data * @param string $component * * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null */ public static function buildComponent(array $data, $component) { return empty($data) ? null : new $component($data); } /** * Builds the given component using the first element of the given array as the data input. * * @param array $data * @param string $component * * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null */ public static function buildComponentArray(array $data, $component) { return empty($data) ? null : new $component(reset($data)); } /** * Builds an array of components using the elements of the given array as the data input. * * @param array $data * @param string $component * * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null */ public static function buildComponents(array $data, $component) { return array_map(function ($element) use ($component) { return new $component($element); }, $data); } }
Update pod-checkpointer image to try secureClient first * https://github.com/kubernetes-incubator/bootkube/pull/1027
package asset // DefaultImages are the defualt images bootkube components use. var DefaultImages = ImageVersions{ Etcd: "quay.io/coreos/etcd:v3.1.8", Flannel: "quay.io/coreos/flannel:v0.10.0-amd64", FlannelCNI: "quay.io/coreos/flannel-cni:v0.3.0", Calico: "quay.io/calico/node:v3.0.3", CalicoCNI: "quay.io/calico/cni:v2.0.0", CoreDNS: "k8s.gcr.io/coredns:1.2.4", Hyperkube: "k8s.gcr.io/hyperkube:v1.12.1", PodCheckpointer: "quay.io/coreos/pod-checkpointer:83e25e5968391b9eb342042c435d1b3eeddb2be1", }
package asset // DefaultImages are the defualt images bootkube components use. var DefaultImages = ImageVersions{ Etcd: "quay.io/coreos/etcd:v3.1.8", Flannel: "quay.io/coreos/flannel:v0.10.0-amd64", FlannelCNI: "quay.io/coreos/flannel-cni:v0.3.0", Calico: "quay.io/calico/node:v3.0.3", CalicoCNI: "quay.io/calico/cni:v2.0.0", CoreDNS: "k8s.gcr.io/coredns:1.2.4", Hyperkube: "k8s.gcr.io/hyperkube:v1.12.1", PodCheckpointer: "quay.io/coreos/pod-checkpointer:018007e77ccd61e8e59b7e15d7fc5e318a5a2682", }
Handle scenario where subscription confirmation would fail if the env was invalid
'use strict'; var config = require('config'); const BASE_URL = config.get('apiGateway.externalUrl'); const logger = require('logger'); class UrlService { static flagshipUrl(path) { if (!path) { path = ''; } return config.get('gfw.flagshipUrl') + path; } static flagshipUrlRW(path, env = 'production') { if (!path) { path = ''; } logger.info('config', config.get('rw.flagshipUrl')); if (!['production', 'staging', 'preproduction'].includes(env)) { logger.warn(`invalid env requested: ${env}. Overriding with staging`); env = 'staging'; } return config.get(`rw.flagshipUrl.${env}`) + path; } static confirmationUrl(subscription) { return BASE_URL + '/subscriptions/' + subscription._id + '/confirm?application=' + subscription.application; } static unsubscribeUrl(subscription) { return BASE_URL + '/subscriptions/' + subscription._id + '/unsubscribe?redirect=true'; } } module.exports = UrlService;
'use strict'; var config = require('config'); const BASE_URL = config.get('apiGateway.externalUrl'); const logger = require('logger'); class UrlService { static flagshipUrl(path) { if (!path) { path = ''; } return config.get('gfw.flagshipUrl') + path; } static flagshipUrlRW(path, env = 'production') { if (!path) { path = ''; } logger.info('config', config.get('rw.flagshipUrl')); return config.get(`rw.flagshipUrl.${env}`) + path; } static confirmationUrl(subscription) { return BASE_URL + '/subscriptions/' + subscription._id + '/confirm?application=' + subscription.application; } static unsubscribeUrl(subscription) { return BASE_URL + '/subscriptions/' + subscription._id + '/unsubscribe?redirect=true'; } } module.exports = UrlService;
Fix syntax error in test
#!/usr/bin/env python """ Test the MPS class """ import unittest import numpy as np import parafermions as pf class Test(unittest.TestCase): def test_pe_degeneracy(self): # should initialise with all zeros N, l = 8, 0.2 pe = PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64')) d, v = pe.Diagonalise(k=100) assert(np.sum(d[1:11:2]-d[:11:2]) < 1e-10) N, l = 8, 1.0 pe = PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64')) d, v = pe.Diagonalise(k=100) assert((d[1]-d[0]) < 1e-15) assert(np.sum(d[1:11:2]-d[:11:2]) > 1e-2)
#!/usr/bin/env python """ Test the MPS class """ import unittest import numpy as np import parafermions as pf class Test(unittest.TestCase): def test_pe_degeneracy(self): # should initialise with all zeros N, l = 8, 0.2 pe = PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64')) d, v = pe.Diagonalise(k=100) assert(np.sum(d[1:11:2]-d[:11:2] < 1e-10) N, l = 8, 1.0 pe = PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64')) d, v = pe.Diagonalise(k=100) assert((d[1]-d[0]) < 1e-15) assert(np.sum(d[1:11:2]-d[:11:2] > 1e-2)
Add more keywords to ruby sandbox
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|method|call|unpack|eval|require|Dir|File|ENV|Process|send|load|include|extend|const|get|glob|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|method|call|unpack|eval|require|Dir|File|ENV|Process|send|load|include|extend|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
Remove pinned Stripe API version.
from django.conf import settings import stripe stripe.api_key = settings.STRIPE_API_KEY class StripeGateway: """A gateway to Stripe This insulates the rest of the system from Stripe errors and configures the Stripe module with the API key. """ def create_customer(self, user: settings.AUTH_USER_MODEL, stripe_token: str) -> str: """Add a user to Stripe and join them to the plan.""" # Let this fail on purpose. If it fails, the error monitoring system # will log it and I'll learn how to harden it for the conductor env. customer = stripe.Customer.create(email=user.email, source=stripe_token) stripe.Subscription.create( customer=customer.id, items=[{"plan": settings.STRIPE_PLAN}], trial_from_plan=True, ) return customer.id stripe_gateway = StripeGateway()
from django.conf import settings import stripe stripe.api_key = settings.STRIPE_API_KEY stripe.api_version = "2018-10-31" class StripeGateway: """A gateway to Stripe This insulates the rest of the system from Stripe errors and configures the Stripe module with the API key. """ def create_customer(self, user: settings.AUTH_USER_MODEL, stripe_token: str) -> str: """Add a user to Stripe and join them to the plan.""" # Let this fail on purpose. If it fails, the error monitoring system # will log it and I'll learn how to harden it for the conductor env. customer = stripe.Customer.create(email=user.email, source=stripe_token) stripe.Subscription.create( customer=customer.id, items=[{"plan": settings.STRIPE_PLAN}], trial_from_plan=True, ) return customer.id stripe_gateway = StripeGateway()
Add a default port (8080)
/** * Extract all the necessary * configuration information * from either command line arguments * (which take priority) or environment * variables. Non-specified information * should prevent the application from starting, * unless there's a sensible default. * @module config */ // Parse arguments var argv = require('minimist')(process.argv.slice(2)); // Extract values by priorities var port = Number(argv.port || argv.p || process.env.HTTP_PORT || '8080'); var db_address = argv['db-address'] || process.env.DB_ADDRESS; if (db_address === '' || db_address === undefined) { var db_host = argv['db-host'] || process.env.DB_HOST; var db_port = argv['db-port'] || process.env.DB_PORT || '27017'; var db_name = argv['db-name'] || process.env.DB_NAME; if (db_host === undefined || db_name === undefined) { console.error('Please provide database information'); process.exit(1); } db_address = 'mongodb://' + db_host + ':' + db_port + '/' + db_name; } // Validate values, where needed if (isNaN(port) || port === 0) { console.error('Please provide a valid port number'); process.exit(1); } module.exports = { port: port, db_address: db_address }
/** * Extract all the necessary * configuration information * from either command line arguments * (which take priority) or environment * variables. Non-specified information * should prevent the application from starting, * unless there's a sensible default. * @module config */ // Parse arguments var argv = require('minimist')(process.argv.slice(2)); // Extract values by priorities var port = Number(argv.port || argv.p || process.env.HTTP_PORT); var db_address = argv['db-address'] || process.env.DB_ADDRESS; if (db_address === '' || db_address === undefined) { var db_host = argv['db-host'] || process.env.DB_HOST; var db_port = argv['db-port'] || process.env.DB_PORT || '27017'; var db_name = argv['db-name'] || process.env.DB_NAME; if (db_host === undefined || db_name === undefined) { console.error('Please provide database information'); process.exit(1); } db_address = 'mongodb://' + db_host + ':' + db_port + '/' + db_name; } // Validate values, where needed if (isNaN(port) || port === 0) { console.error('Please provide a valid port number'); process.exit(1); } module.exports = { port: port, db_address: db_address }
Move additional field "issuer" out of the "solution" object
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() }, issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}` } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
Delete many to reduce round trips to the cache.
from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key def update_submission(id): key = 'version:submission-%d' % id cache.add(key, 0, None) cache.incr(key) def update_stats(): cache.delete_many(('sub_stats_table', 'sub_stats_data')) def point_update(profile): cache.delete(make_template_fragment_key('global_user')) def finished_submission(sub): keys = ['user_complete:%d' % sub.user_id] if hasattr(sub, 'contest'): participation = sub.contest.participation keys += ['contest_complete:%d' % participation.id, make_template_fragment_key('conrank_user_prob', (participation.profile.user_id, participation.contest_id))] cache.delete_many(keys)
from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key def update_submission(id): key = 'version:submission-%d' % id cache.add(key, 0, None) cache.incr(key) def update_stats(): cache.delete('sub_stats_table') cache.delete('sub_stats_data') def point_update(profile): cache.delete(make_template_fragment_key('global_user')) def finished_submission(sub): cache.delete('user_complete:%d' % sub.user_id) if hasattr(sub, 'contest'): participation = sub.contest.participation cache.delete('contest_complete:%d' % participation.id) cache.delete(make_template_fragment_key('conrank_user_prob', (participation.profile.user_id, participation.contest_id)))