text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Truncate really long message previews
package ca.corefacility.bioinformatics.irida.ria.web.models.datatables; import java.util.Date; import ca.corefacility.bioinformatics.irida.model.announcements.Announcement; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.ria.web.components.datatables.models.DataTablesResponseModel; /** * User interface model for DataTables for administration of {@link Announcement} */ public class DTAnnouncementAdmin implements DataTablesResponseModel { private Long id; private String message; private Date createdDate; private User user; public DTAnnouncementAdmin(Announcement announcement) { this.id = announcement.getId(); // Only display the first line of the message. this.message = announcement.getMessage().split("\\r?\\n")[0]; if(this.message.length() > 80){ // If the message is still really long just take a substring of it. this.message = this.message.substring(0, 79) + " ..."; } this.createdDate = announcement.getCreatedDate(); this.user = announcement.getUser(); } @Override public Long getId() { return id; } public String getMessage() { return message; } public Date getCreatedDate() { return createdDate; } public User getUser() { return user; } }
package ca.corefacility.bioinformatics.irida.ria.web.models.datatables; import java.util.Date; import ca.corefacility.bioinformatics.irida.model.announcements.Announcement; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.ria.web.components.datatables.models.DataTablesResponseModel; /** * User interface model for DataTables for administration of {@link Announcement} */ public class DTAnnouncementAdmin implements DataTablesResponseModel { private Long id; private String message; private Date createdDate; private User user; public DTAnnouncementAdmin(Announcement announcement) { this.id = announcement.getId(); // Only display the first line of the message. this.message = announcement.getMessage().split("\\r?\\n")[0]; this.createdDate = announcement.getCreatedDate(); this.user = announcement.getUser(); } @Override public Long getId() { return id; } public String getMessage() { return message; } public Date getCreatedDate() { return createdDate; } public User getUser() { return user; } }
Improve error message for malformed dependencies
<?php namespace Phactory; class Dependency { private $dependency; private $property; public function __construct($dependency) { $this->dependency = $dependency; } public function meet($blueprint) { $parts = explode('.', $this->dependency); return $this->get($parts, $blueprint); } private function get($parts, $subject) { $part = array_shift($parts); if (method_exists($subject, $part)) $value = call_user_func(array($subject, $part)); elseif (is_array($subject) && isset($subject[$part])) $value = $subject[$part]; elseif (is_object($subject) && isset($subject->$part)) $value = $subject->$part; else throw new \Exception(sprintf( "Can't find %s in %s", $part, is_object($subject) ? get_class($subject) : gettype($subject) )); if (count($parts) == 0) return $value; else return $this->get($parts, $value); } }
<?php namespace Phactory; class Dependency { private $dependency; private $property; public function __construct($dependency) { $this->dependency = $dependency; } public function meet($blueprint) { $parts = explode('.', $this->dependency); return $this->get($parts, $blueprint); } private function get($parts, $subject) { $part = array_shift($parts); if (method_exists($subject, $part)) $value = call_user_func(array($subject, $part)); elseif (is_array($subject) && isset($subject[$part])) $value = $subject[$part]; elseif (is_object($subject) && isset($subject->$part)) $value = $subject->$part; else throw new \Exception(""); if (count($parts) == 0) return $value; else return $this->get($parts, $value); } }
Remove comment superseded by support library changes
/* * Copyright 2016 Juliane Lehmann <jl@lambdasoup.com> * * 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.lambdasoup.appbarsyncedfabSample; import android.view.View; public class ComplexAppBarActivity extends BaseAppBarActivity { @Override protected void onBeforeInflateAppBarLayout() { View coordinatorLayout = findViewById(R.id.coordinator_layout); // Because we're using a single base layout, for proper appearance // of the collapsing toolbar layout, we need to do this programmatically. //noinspection ConstantConditions coordinatorLayout.setFitsSystemWindows(true); } @Override protected int getAppBarLayoutResource() { return R.layout.app_bar_complex_collapsing_app_bar; } @Override protected int getNavId() { return R.id.nav_complex_app_bar; } }
/* * Copyright 2016 Juliane Lehmann <jl@lambdasoup.com> * * 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.lambdasoup.appbarsyncedfabSample; import android.view.View; public class ComplexAppBarActivity extends BaseAppBarActivity { @Override protected void onBeforeInflateAppBarLayout() { View coordinatorLayout = findViewById(R.id.coordinator_layout); // Because we're using a single base layout, for proper appearance // of the collapsing toolbar layout, we need to do this programmatically. // Waiting for https://code.google.com/p/android/issues/detail?id=212720 to get resolved // so this has a chance to work; until then this is a reminder for users of CollapsingToolbarLayout. //noinspection ConstantConditions coordinatorLayout.setFitsSystemWindows(true); } @Override protected int getAppBarLayoutResource() { return R.layout.app_bar_complex_collapsing_app_bar; } @Override protected int getNavId() { return R.id.nav_complex_app_bar; } }
Change bitshuffle call to hdf5plugin
import h5py import hdf5plugin import numpy import tempfile def test_is_h5py_correctly_installed(): """ If this test fails you probably need to install h5py from source manually: $ pip install --no-binary=h5py h5py """ f = h5py.File(tempfile.gettempdir() + '/h5testfile', "w") block_size = 0 dataset = f.create_dataset( "data", (100, 100, 100), dtype='float32', **hdf5plugin.Bitshuffle(nelems=0, lz4=True) ) array = numpy.random.rand(100, 100, 100) array = array.astype('float32') dataset[:] = array f.close()
import h5py import bitshuffle.h5 import numpy import tempfile def test_is_h5py_correctly_installed(): """ If this test fails you probably need to install h5py from source manually: $ pip install --no-binary=h5py h5py """ f = h5py.File(tempfile.gettempdir() + '/h5testfile', "w") block_size = 0 dataset = f.create_dataset( "data", (100, 100, 100), compression=bitshuffle.h5.H5FILTER, compression_opts=(block_size, bitshuffle.h5.H5_COMPRESS_LZ4), dtype='float32', ) array = numpy.random.rand(100, 100, 100) array = array.astype('float32') dataset[:] = array f.close()
TST: Remove tmp folder at end of tests
describe( 'esbeautifier', function () { var expand = require( 'glob-expand' ); var path = require( 'path' ); var exec = require( '../lib/exec' ); var read = function ( file ) { return require( 'fs' ).readFileSync( file, { encoding: 'utf8' } ); }; //var write = require( 'write' ).sync; var fs = require( 'fs-extra' ); fs.removeSync( './tmp' ); fs.copySync( './resources', './tmp' ); var files = expand( 'tmp/fixtures/**/*.js' ); files.forEach( function ( file ) { var basename = path.basename( file ); it( 'should format the file ' + basename + ' and match the expected result', function ( done ) { exec( './bin/cli.js --no-use-cache ' + file, { stdio: 'ignore' } ).then( function () { var expected = read( path.join( 'tmp/expected/', basename ) ); var result = read( file ); //console.log('here >> task complete, result', result, expected); expect( result ).to.equal( expected ); done(); } ).catch( function ( err ) { done( err ); } ); } ); } ); after( function () { //eslint-disable-line fs.removeSync( './tmp' ); } ); } );
describe( 'esbeautifier', function () { var expand = require( 'glob-expand' ); var path = require( 'path' ); var exec = require( '../lib/exec' ); var read = function ( file ) { return require( 'fs' ).readFileSync( file, { encoding: 'utf8' } ); }; //var write = require( 'write' ).sync; var fs = require( 'fs-extra' ); fs.removeSync( './tmp' ); fs.copySync( './resources', './tmp' ); var files = expand( 'tmp/fixtures/**/*.js' ); files.forEach( function ( file ) { var basename = path.basename( file ); it( 'should format the file ' + basename + ' and match the expected result', function ( done ) { exec( './bin/cli.js --no-use-cache ' + file, { stdio: 'ignore' } ).then( function () { var expected = read( path.join( 'tmp/expected/', basename ) ); var result = read( file ); //console.log('here >> task complete, result', result, expected); expect( result ).to.equal( expected ); done(); } ).catch( function ( err ) { done( err ); } ); } ); } ); after( function () { //eslint-disable-line //fs.removeSync( './tmp' ); } ); } );
Build correct url on production
import { Environment, Network, RecordSource, Store, } from 'relay-runtime'; import { getToken } from 'app/utils/token'; const GRAPHQL_PORT = process.env.GRAPHQL_PORT; const GRAPHQL_HOST = process.env.GRAPHQL_HOST; const makeURL = () => { if(! GRAPHQL_PORT || ! GRAPHQL_HOST) { return `/graphql`; } return `http://${GRAPHQL_HOST}:${GRAPHQL_PORT}/graphql`; } // Define a function that fetches the results of an operation (query/mutation/etc) // and returns its results as a Promise: function fetchQuery( operation, variables, cacheConfig, uploadables, ) { return fetch(makeURL(), { method: 'POST', headers: { 'content-type': 'application/json', 'Authorization': `JWT ${getToken()}`, }, body: JSON.stringify({ query: operation.text, variables, }), }).then(response => { return response.json(); }); } const source = new RecordSource(); const store = new Store(source); const network = Network.create(fetchQuery); const environment = new Environment({ network, store, }); export default environment;
import { Environment, Network, RecordSource, Store, } from 'relay-runtime'; import { getToken } from 'app/utils/token'; const GRAPHQL_PORT = process.env.GRAPHQL_PORT; const GRAPHQL_HOST = process.env.GRAPHQL_HOST; // Define a function that fetches the results of an operation (query/mutation/etc) // and returns its results as a Promise: function fetchQuery( operation, variables, cacheConfig, uploadables, ) { return fetch(`http://${GRAPHQL_HOST}:${GRAPHQL_PORT}/graphql`, { method: 'POST', headers: { 'content-type': 'application/json', 'Authorization': `JWT ${getToken()}`, }, body: JSON.stringify({ query: operation.text, variables, }), }).then(response => { return response.json(); }); } const source = new RecordSource(); const store = new Store(source); const network = Network.create(fetchQuery); const environment = new Environment({ network, store, }); export default environment;
Improve broadcast performance for ws This commit makes ws use the same buffer for all clients when iterating over them instead of copying the data every time.
'use strict'; var cluster = require('cluster'); var ws = require('ws'); var wss = new ws.Server({ perMessageDeflate: false, port: 3334 }); if (cluster.isWorker) { process.on('message', broadcastMessage); } function broadcastMessage(msg) { var buf = Buffer.from(msg); var opts = {binary: false}; for (var i = 0; i < wss.clients.length; i++) { wss.clients[i].send(buf, opts); } } function echo(ws, payload) { ws.send(JSON.stringify({type: 'echo', payload: payload})); } function broadcast(ws, payload) { var msg = JSON.stringify({type: 'broadcast', payload: payload}); if (cluster.isWorker) { process.send(msg); } broadcastMessage(msg); ws.send(JSON.stringify({type: 'broadcastResult', payload: payload})); } wss.on('connection', function connection(ws) { // uws removes the `upgradeReq` object right after emitting the `connection` // event. The same is also done here for parity. ws.upgradeReq = null; ws.on('message', function incoming(message) { var msg = JSON.parse(message); switch (msg.type) { case 'echo': echo(ws, msg.payload); break; case 'broadcast': broadcast(ws, msg.payload); break; default: console.log('unknown message type: %s', message); } }); });
'use strict'; var cluster = require('cluster'); var ws = require('ws'); var wss = new ws.Server({ perMessageDeflate: false, port: 3334 }); if (cluster.isWorker) { process.on('message', function(msg) { wss.clients.forEach(function each(client) { client.send(msg); }); }); } function echo(ws, payload) { ws.send(JSON.stringify({type: 'echo', payload: payload})); } function broadcast(ws, payload) { var msg = JSON.stringify({type: 'broadcast', payload: payload}); if (cluster.isWorker) { process.send(msg); } wss.clients.forEach(function each(client) { client.send(msg); }); ws.send(JSON.stringify({type: 'broadcastResult', payload: payload})); } wss.on('connection', function connection(ws) { // uws removes the `upgradeReq` object right after emitting the `connection` // event. The same is also done here for parity. ws.upgradeReq = null; ws.on('message', function incoming(message) { var msg = JSON.parse(message); switch (msg.type) { case 'echo': echo(ws, msg.payload); break; case 'broadcast': broadcast(ws, msg.payload); break; default: console.log('unknown message type: %s', message); } }); });
Clean up: Remove unused property and function call parameter Introduced in 1058f244fe6b478a26b02bef8100b943a0cb76d7, the implementation was changed in 2c129ef69a3d408973be66ac85309514355e95b4, however, the now superfluous property and function call parameter were not removed.
<?php /** * WHIP libary file. * * @package Yoast\WHIP */ /** * Class Whip_HostMessage. */ class Whip_HostMessage implements Whip_Message { /** * @var string */ private $textdomain; /** * @var string */ private $messageKey; /** * Whip_Message constructor. * * @param string $messageKey The environment key to use to retrieve the message from. * @param string $textdomain The text domain to use for translations. */ public function __construct( $messageKey, $textdomain ) { $this->textdomain = $textdomain; $this->messageKey = $messageKey; } /** * Renders the message body. * * @return string The message body. */ public function body() { $message = array(); $message[] = Whip_MessageFormatter::strong( $this->title() ) . '<br />'; $message[] = Whip_MessageFormatter::paragraph( Whip_Host::message( $this->messageKey ) ); return implode( $message, "\n" ); } /** * Renders the message title. * * @return string The message title. */ public function title() { return sprintf( __( 'A message from %1$s', $this->textdomain ), Whip_Host::name() ); } }
<?php /** * WHIP libary file. * * @package Yoast\WHIP */ /** * Class Whip_HostMessage. */ class Whip_HostMessage implements Whip_Message { /** * @var string */ private $textdomain; /** * @var string */ private $messageKey; /** * @var string */ private $filterKey; /** * Whip_Message constructor. * * @param string $messageKey The environment key to use to retrieve the message from. * @param string $textdomain The text domain to use for translations. */ public function __construct( $messageKey, $textdomain ) { $this->textdomain = $textdomain; $this->messageKey = $messageKey; } /** * Renders the message body. * * @return string The message body. */ public function body() { $message = array(); $message[] = Whip_MessageFormatter::strong( $this->title() ) . '<br />'; $message[] = Whip_MessageFormatter::paragraph( Whip_Host::message( $this->messageKey, $this->filterKey ) ); return implode( $message, "\n" ); } /** * Renders the message title. * * @return string The message title. */ public function title() { return sprintf( __( 'A message from %1$s', $this->textdomain ), Whip_Host::name() ); } }
Prepare to code the validator
# coding: utf-8 # Copyright 2013 Alan Justino da Silva, Oscar Vilaplana, et. al. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import unicode_literals __version__ = '0.1.0' def formater(postcode): ''' Format a UK Post Code to the official form. Expects a valid postcode. ''' postcode = postcode.upper().replace(' ', '').strip() inward = postcode[-3:] outward = postcode[:-3] return '%s %s' % (outward, inward) def validate(postcode): ''' Returns True if the postcode is valid. False otherwise. ''' raise NotImplementedError()
# coding: utf-8 # Copyright 2013 Alan Justino da Silva, Oscar Vilaplana, et. al. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import unicode_literals __version__ = '0.1.0' def formater(postcode): ''' Format a UK Post Code to the official form. Expects a valid postcode. ''' postcode = postcode.upper().replace(' ', '').strip() inward = postcode[-3:] outward = postcode[:-3] return '%s %s' % (outward, inward)
FIX crash on undefined or null 'who'
"use strict" import {Store} from "flummox" import find from "lodash/collection/find" export default class PollStore extends Store { constructor(flux) { super(); this.state = { "showReport": false, "showTable": true } const pollActions = flux.getActions("poll") this.register(pollActions.select, this.onUpdateSelections) this.register(pollActions.unselect, this.onUpdateSelections) this.register(pollActions.updateWho, this.onUpdateWho) this.register(pollActions.load, this.onLoad) this.register(pollActions.toggleTable, this.onToggleTable) this.register(pollActions.toggleReport, this.onToggleReport) } findSelection(selection) { return find(this.state.selections, { "workshop": selection.workshop, "hour": selection.hour }) } onUpdateSelections(selections) { this.setState({ "selections": selections }) } onUpdateWho(who) { this.setState({ "who": who }) } onLoad(data) { this.setState(data) } onToggleReport(show) { this.setState({"showReport": show}) } onToggleTable(show) { this.setState({"showTable": show}) } isValidWho(who) { return who && who.length > 0 && !who.match(/^\s+/) && !who.match(/\s+$/) } }
"use strict" import {Store} from "flummox" import find from "lodash/collection/find" export default class PollStore extends Store { constructor(flux) { super(); this.state = { "showReport": false, "showTable": true } const pollActions = flux.getActions("poll") this.register(pollActions.select, this.onUpdateSelections) this.register(pollActions.unselect, this.onUpdateSelections) this.register(pollActions.updateWho, this.onUpdateWho) this.register(pollActions.load, this.onLoad) this.register(pollActions.toggleTable, this.onToggleTable) this.register(pollActions.toggleReport, this.onToggleReport) } findSelection(selection) { return find(this.state.selections, { "workshop": selection.workshop, "hour": selection.hour }) } onUpdateSelections(selections) { this.setState({ "selections": selections }) } onUpdateWho(who) { this.setState({ "who": who }) } onLoad(data) { this.setState(data) } onToggleReport(show) { this.setState({"showReport": show}) } onToggleTable(show) { this.setState({"showTable": show}) } isValidWho(who) { return who.length > 0 && !who.match(/^\s+/) && !who.match(/\s+$/) } }
Switch to new engine facade for StandardAttribute objects Enable the new Engine Facade for StandardAttribute objects. Change-Id: Ia3eb436d07e3b2fc633b219aa00c78cc07ed30db
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_versionedobjects import fields as obj_fields from neutron.db import standard_attr from neutron.objects import base from neutron.objects.extensions import standardattributes as stdattr_obj # TODO(ihrachys): add unit tests for the object @base.NeutronObjectRegistry.register class StandardAttribute(base.NeutronDbObject): # Version 1.0: Initial version VERSION = '1.0' new_facade = True db_model = standard_attr.StandardAttribute fields = { 'id': obj_fields.IntegerField(), 'resource_type': obj_fields.StringField(), } fields.update(stdattr_obj.STANDARD_ATTRIBUTES)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_versionedobjects import fields as obj_fields from neutron.db import standard_attr from neutron.objects import base from neutron.objects.extensions import standardattributes as stdattr_obj # TODO(ihrachys): add unit tests for the object @base.NeutronObjectRegistry.register class StandardAttribute(base.NeutronDbObject): # Version 1.0: Initial version VERSION = '1.0' db_model = standard_attr.StandardAttribute fields = { 'id': obj_fields.IntegerField(), 'resource_type': obj_fields.StringField(), } fields.update(stdattr_obj.STANDARD_ATTRIBUTES)
Fix cmislib branch for py3k
#!/usr/bin/env python from setuptools import setup, find_packages from imp import load_source setup( name='cmis', version=load_source('', 'cmis/_version.py').__version__, description='A server architecture built on top of a solid foundation ' 'provided by flask, sqlalchemy, and various extensions.', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], author='Concordus Applications', author_email='support@concordusapps.com', url='http://github.com/concordusapps/alchemist', packages=find_packages('.'), entry_points={'pytest11': ['alchemist = alchemist.plugin']}, dependency_links=[ 'git+git://github.com/concordusapps/python-cmislib.git@topics/py3k' '#egg=cmislib-dev', ], install_requires=[ "cmislib == dev" ], )
#!/usr/bin/env python from setuptools import setup, find_packages from imp import load_source setup( name='cmis', version=load_source('', 'cmis/_version.py').__version__, description='A server architecture built on top of a solid foundation ' 'provided by flask, sqlalchemy, and various extensions.', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], author='Concordus Applications', author_email='support@concordusapps.com', url='http://github.com/concordusapps/alchemist', packages=find_packages('.'), entry_points={'pytest11': ['alchemist = alchemist.plugin']}, dependency_links=[ 'git+git://github.com/concordusapps/python-cmislib.git@master' '#egg=cmislib-dev', ], install_requires=[ "cmislib == dev" ], )
Use `imply` instead of `use` and `export` together This commit uses the `api.imply` shorthand to use a package and export its exports.
var path = Npm.require("path"); Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "1.0.3+0.0.42" }); Package._transitional_registerBuildPlugin({ name: "compileHarmony", use: [], sources: [ "plugin/compile-harmony.js" ], npmDependencies: { "traceur": "0.0.42" } }); Package.on_use(function (api) { // The location of this runtime file is not supposed to change: // http://git.io/B2s0Tg var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/"; api.add_files(path.join(dir, "traceur-runtime.js")); // Export `module.exports` and `exports` down the package pipeline api.imply('exports'); }); Package.on_test(function (api) { api.use(['harmony', 'tinytest']); api.add_files([ 'harmony_test_setup.js', 'harmony_tests.js', 'tests/harmony_test_setup.next.js', 'tests/harmony_tests.next.js' ], ["client", "server"]); });
var path = Npm.require("path"); Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "1.0.3+0.0.42" }); Package._transitional_registerBuildPlugin({ name: "compileHarmony", use: [], sources: [ "plugin/compile-harmony.js" ], npmDependencies: { "traceur": "0.0.42" } }); Package.on_use(function (api) { // The location of this runtime file is not supposed to change: // http://git.io/B2s0Tg var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/"; api.add_files(path.join(dir, "traceur-runtime.js")); // Export `module.exports` and `exports` down the package pipeline api.use('exports'); api.export(['module', 'exports']); }); Package.on_test(function (api) { api.use(['harmony', 'tinytest']); api.add_files([ 'harmony_test_setup.js', 'harmony_tests.js', 'tests/harmony_test_setup.next.js', 'tests/harmony_tests.next.js' ], ["client", "server"]); });
Add more robust test case
import test from 'ava' import jsdom from 'jsdom-global' import cxs from '../src' jsdom('<html></html>') test.beforeEach(t => { cxs.clearCache() t.context.style = { display: 'block', textAlign: 'center', fontSize: 48, ':hover': { textDecoration: 'none' }, 'h1': { display: 'inline-block' }, '@media screen': { display: 'table' }, '@keyframes hello': { from: { display: 'block' }, '50%': { display: 'table' }, to: { display: 'inline-block' } } } t.context.cx = cxs(t.context.style) }) test('extracts common declarations', t => { t.plan(2) const rules = cxs.rules t.regex(rules[0].css, /^\.cxs\-display\-block/) t.regex(rules[1].css, /^\.cxs\-text-align-center/) }) test('does not extract common declarations from nested rules', t => { t.plan(3) t.false(/text\-decoration\-none/.test(t.context.cx)) t.false(/inline\-block/.test(t.context.cx)) t.false(/table/.test(t.context.cx)) }) test('extracted declarations are included in className', t => { t.is(t.context.cx.split(' ').length, 3) })
import test from 'ava' import jsdom from 'jsdom-global' import cxs from '../src' jsdom('<html></html>') test.beforeEach(t => { cxs.clearCache() t.context.style = { display: 'block', textAlign: 'center', fontSize: 48, ':hover': { textDecoration: 'none' }, 'h1': { display: 'inline-block' }, '@media screen': { display: 'table' } } t.context.cx = cxs(t.context.style) }) test('extracts common declarations', t => { t.plan(2) const rules = cxs.rules t.regex(rules[0].css, /^\.cxs\-display\-block/) t.regex(rules[1].css, /^\.cxs\-text-align-center/) }) test('does not extract common declarations from nested rules', t => { t.plan(2) t.false(/inline\-block/.test(t.context.cx)) t.false(/table/.test(t.context.cx)) }) test('extracted declarations are included in className', t => { t.is(t.context.cx.split(' ').length, 3) })
Add DWIMy String projection method
package semantics.model; import java.util.regex.Matcher; import java.util.regex.Pattern; import semantics.Individuals; import semantics.KnowBase; public final class Individual { private static final Pattern[] NAME_PATTERNS = { Pattern.compile("<.*#(.*)>"), Pattern.compile("<.*?:(.*)>"), Pattern.compile("<(.*)>"), Pattern.compile(".*?:(.*)"), }; private final KnowBase kb; private final String iri; public Individual(KnowBase kb, String iri) { this.kb = kb; this.iri = iri; } public String getIri() { return iri; } public String getName() { for (Pattern p : NAME_PATTERNS) { Matcher m = p.matcher(iri); if (m.matches()) { return m.group(1); } } return iri; } public Individuals project(Roleish r) { return kb.project(this, r); } public Individuals project(String iri) { return project(new Role(iri)); } @Override public boolean equals(Object other) { if (other instanceof Individual) { Individual i = (Individual) other; return kb.equals(i.kb) && iri.equals(i.iri); } return false; } @Override public int hashCode() { return (kb + "\0" + iri).hashCode(); } }
package semantics.model; import java.util.regex.Matcher; import java.util.regex.Pattern; import semantics.Individuals; import semantics.KnowBase; public final class Individual { private static final Pattern[] NAME_PATTERNS = { Pattern.compile("<.*#(.*)>"), Pattern.compile("<.*?:(.*)>"), Pattern.compile("<(.*)>"), Pattern.compile(".*?:(.*)"), }; private final KnowBase kb; private final String iri; public Individual(KnowBase kb, String iri) { this.kb = kb; this.iri = iri; } public String getIri() { return iri; } public String getName() { for (Pattern p : NAME_PATTERNS) { Matcher m = p.matcher(iri); if (m.matches()) { return m.group(1); } } return iri; } public Individuals project(Roleish r) { return kb.project(this, r); } @Override public boolean equals(Object other) { if (other instanceof Individual) { Individual i = (Individual) other; return kb.equals(i.kb) && iri.equals(i.iri); } return false; } @Override public int hashCode() { return (kb + "\0" + iri).hashCode(); } }
Fix to use indexOf whihc is more commonly available than includes
var Weather = require('../modules/openweathermap'); var express = require('express'); var util = require('util'); var router = express.Router(); //new Weather API using the key defaulted from the environment var weather = new Weather(); /* GET home page. */ router.post('/weather', function(req, res, next) { var zip = req.body.text; var fahrenheit = req.body.command.indexOf('c') == -1; if (!zip || !isValidUSZip(zip.trim())) { res.json({ text: "I'm sorry I didn't understand. Please use a US zip" }); } weather.getWeatherByZip(zip.trim(), function handleResponse(err, result) { if (err) { res.json({ text: "I'm sorry I couldn't process your request. Please try again later" }); } else { res.json({ response_type: "in_channel", text: util.format('Here\'s the weather in %s\n%s°%s %s', result.city, fahrenheit ? result.tempF.toFixed(1) : result.tempC.toFixed(1), fahrenheit ? 'F' : 'C', result.description.join(', ')) }); } }); }); function isValidUSZip(zip) { return /^\d{5}(-\d{4})?$/.test(zip); } module.exports = router;
var Weather = require('../modules/openweathermap'); var express = require('express'); var util = require('util'); var router = express.Router(); //new Weather API using the key defaulted from the environment var weather = new Weather(); /* GET home page. */ router.post('/weather', function(req, res, next) { var zip = req.body.text; var fahrenheit = !req.body.command.includes('c'); if (!zip || !isValidUSZip(zip.trim())) { res.json({ text: "I'm sorry I didn't understand. Please use a US zip" }); } weather.getWeatherByZip(zip.trim(), function handleResponse(err, result) { if (err) { res.json({ text: "I'm sorry I couldn't process your request. Please try again later" }); } else { res.json({ response_type: "in_channel", text: util.format('Here\'s the weather in %s\n%s°%s %s', result.city, fahrenheit ? result.tempF.toFixed(1) : result.tempC.toFixed(1), fahrenheit ? 'F' : 'C', result.description.join(', ')) }); } }); }); function isValidUSZip(zip) { return /^\d{5}(-\d{4})?$/.test(zip); } module.exports = router;
Put some throwing code in the body of the `try`. That encourages Checker Framework to run dataflow over the `catch`: https://github.com/typetools/checker-framework/issues/4265 Depending on how a checker author chooses to implement "caught exceptions are non-null," this change to the sample could demonstrate a problem with the implementation.
/* * Copyright 2020 The JSpecify 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. */ import org.jspecify.annotations.DefaultNonNull; @DefaultNonNull class Catch { void x() { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); // TODO(cpovirk): Edit README to permit referencing java.lang.Exception. Or remove this. } } }
/* * Copyright 2020 The JSpecify 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. */ import org.jspecify.annotations.DefaultNonNull; @DefaultNonNull class Catch { void x() { try { } catch (Exception e) { e.printStackTrace(); // TODO(cpovirk): Edit README to permit referencing java.lang.Exception. Or remove this. } } }
Fix errors with 2/3 FLO support
# -*- coding: utf-8 -*- import click from .compat import StringIO, str, builtin_str import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') @click.argument('input', type=click.File('r'), default='-') @click.argument('output', type=click.File('w'), default='-') def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _input = seria.load(_input) _out = (_input.dump(out_fmt)) output.write(_out) if __name__ == '__main__': cli(out_fmt, input, output)
# -*- coding: utf-8 -*- import click from .compat import StringIO import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') @click.argument('input', type=click.File('rb'), default='-') @click.argument('output', type=click.File('wb'), default='-') def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _serialized_obj = seria.load(_input) output.write(_serialized_obj.dump(out_fmt)) if __name__ == '__main__': cli(out_fmt, input, output)
Remove "Tuvero Basic" maxteams restriction
/** * Basic presets: swiss direct matchings, round similar to chess, and ko * with a matched cadrage. Simple rankings * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function () { var Presets; Presets = { target: "basic", systems: { swiss: { ranking: ["wins", "headtohead", "saldo"], mode: "ranks" }, ko: { mode: "matched" }, round: { ranking: ["wins", "sonneborn", "headtohead", "points"] }, placement: {} }, ranking: { components: ["buchholz", "finebuchholz", "points", "saldo", "sonneborn", "numgames", "wins", "headtohead", "threepoint", "twopoint" ] }, registration: { defaultteamsize: 1, minteamsize: 1, maxteamsize: 3, teamsizeicon: false }, names: { playernameurl: "", dbplayername: "tuverobasicplayers", apitoken: "apitoken", teamsfile: "tuvero-anmeldungen.txt" }, ui: { rankingpoints: false } }; return Presets; });
/** * Basic presets: swiss direct matchings, round similar to chess, and ko * with a matched cadrage. Simple rankings * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function () { var Presets; Presets = { target: "basic", systems: { swiss: { ranking: ["wins", "headtohead", "saldo"], mode: "ranks" }, ko: { mode: "matched" }, round: { ranking: ["wins", "sonneborn", "headtohead", "points"] }, placement: {} }, ranking: { components: ["buchholz", "finebuchholz", "points", "saldo", "sonneborn", "numgames", "wins", "headtohead", "threepoint", "twopoint" ] }, registration: { defaultteamsize: 1, minteamsize: 1, maxteamsize: 1, teamsizeicon: false }, names: { playernameurl: "", dbplayername: "tuverobasicplayers", apitoken: "apitoken", teamsfile: "tuvero-anmeldungen.txt" }, ui: { rankingpoints: false } }; return Presets; });
Add option if name not exists.
var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor; function WebService(currentUser) { this._currentUser = currentUser; this._dependencies = {}; this.runRef = undefined; } WebService.prototype.runWrapper = function () { var self = this; return function (name, allowedTypeAccount, params) { name = name || 'accessDenied'; allowedTypeAccount = allowedTypeAccount || []; params = params || {}; return function (req, res) { params.req = req; params.res = res; self.runRef(name, allowedTypeAccount, params); }; }; }; WebService.prototype.run = function (name, allowedTypeAccount, params) { allowedTypeAccount = allowedTypeAccount || []; params = params || {}; var self = this; var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser); var webServices = require('../ServiceDirectories/Web/Public'); if (permissionsInit.check()) { webServices[name].call(undefined, self._dependencies, params); } else { webServices['accessDenied'].call(undefined, self._dependencies, params); } }; WebService.prototype.addDependency = function (name, value) { this._dependencies[name] = value; }; module.exports.WebService = WebService;
var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor; function WebService(currentUser) { this._currentUser = currentUser; this._dependencies = {}; this.runRef = undefined; } WebService.prototype.runWrapper = function () { var self = this; return function (name, allowedTypeAccount, params) { allowedTypeAccount = allowedTypeAccount || []; params = params || {}; return function (req, res) { params.req = req; params.res = res; self.runRef(name, allowedTypeAccount, params); }; }; }; WebService.prototype.run = function (name, allowedTypeAccount, params) { allowedTypeAccount = allowedTypeAccount || []; params = params || {}; var self = this; var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser); var webServices = require('../ServiceDirectories/Web/Public'); if (permissionsInit.check()) { webServices[name].call(undefined, self._dependencies, params); } else { webServices['accessDenied'].call(undefined, self._dependencies, params); } }; WebService.prototype.addDependency = function (name, value) { this._dependencies[name] = value; }; module.exports.WebService = WebService;
Update tests for handling null city suggestion
import { assert } from 'chai'; import citySuggestionFormatter from 'helpers/citySuggestionFormatter'; describe('citySuggestionFormatter', () => { context('for a null suggestion', () => { const suggestion = null; it('returns an empty string', () => { const actual = citySuggestionFormatter(suggestion); const expected = ''; assert.equal(actual, expected); }); }); context('for a suggestion without name', () => { const suggestion = { zips: [12345, 67890] }; it('returns an empty string', () => { const actual = citySuggestionFormatter(suggestion); const expected = ''; assert.equal(actual, expected); }); }); context('for a suggestion without zips', () => { const suggestion = { name: 'City-Ville' }; it('returns an empty string', () => { const actual = citySuggestionFormatter(suggestion); const expected = ''; assert.equal(actual, expected); }); }); context('for a suggestion with name and zips', () => { const suggestion = { name: 'City-Ville', zips: [12345, 67890] }; it('returns the name joined with the first zip', () => { const actual = citySuggestionFormatter(suggestion); const expected = 'City-Ville - 12345'; assert.equal(actual, expected); }); }); });
import { assert } from 'chai'; import citySuggestionFormatter from 'helpers/citySuggestionFormatter'; describe('citySuggestionFormatter', () => { context('for a suggestion without name', () => { const suggestion = { zips: [12345, 67890] }; it('returns an empty string', () => { const actual = citySuggestionFormatter(suggestion); const expected = ''; assert.equal(actual, expected); }); }); context('for a suggestion without zips', () => { const suggestion = { name: 'City-Ville' }; it('returns an empty string', () => { const actual = citySuggestionFormatter(suggestion); const expected = ''; assert.equal(actual, expected); }); }); context('for a suggestion with name and zips', () => { const suggestion = { name: 'City-Ville', zips: [12345, 67890] }; it('returns the name joined with the first zip', () => { const actual = citySuggestionFormatter(suggestion); const expected = 'City-Ville - 12345'; assert.equal(actual, expected); }); }); });
emoji: Cut misleading ignored reference to an emoji font. Per the docs of the react-native-vector-icons package, this argument is supposed to be the name of a font. But there's no sign of a font by this name actually appearing in the package, so it's hard to see what passing it could actually mean -- instead, it just misleads the reader by suggesting that this font is involved somehow. And, empirically, the behavior is the same when this argument is removed. Tested in the reaction-list screen, in an emulated Pixel 3 running Android 10 and in an emulated iPhone 8 running iOS 13.
/* @flow strict-local */ import React, { PureComponent } from 'react'; import { StyleSheet, Image } from 'react-native'; import { createIconSet } from 'react-native-vector-icons'; import type { ImageEmojiType, Dispatch } from '../types'; import { connect } from '../react-redux'; import { nameToEmojiMap } from './data'; import { getAllImageEmojiByName } from './emojiSelectors'; /* $FlowFixMe: `nameToEmojiMap` is mistyped upstream; elements of `glyphMap` may be either `number` or `string`. */ const UnicodeEmoji = createIconSet(nameToEmojiMap); type SelectorProps = {| imageEmoji: ImageEmojiType | void, |}; type Props = $ReadOnly<{| name: string, dispatch: Dispatch, ...SelectorProps, |}>; // TODO: this only handles Unicode emoji (shipped with the app) // and realm emoji, but not Zulip extra emoji. See our issue #2846. class Emoji extends PureComponent<Props> { styles = StyleSheet.create({ image: { width: 20, height: 20 }, }); render() { const { name, imageEmoji } = this.props; if (imageEmoji) { return <Image style={this.styles.image} source={{ uri: imageEmoji.source_url }} />; } return <UnicodeEmoji name={name} size={20} />; } } export default connect<SelectorProps, _, _>((state, props) => ({ imageEmoji: getAllImageEmojiByName(state)[props.name], }))(Emoji);
/* @flow strict-local */ import React, { PureComponent } from 'react'; import { StyleSheet, Image } from 'react-native'; import { createIconSet } from 'react-native-vector-icons'; import type { ImageEmojiType, Dispatch } from '../types'; import { connect } from '../react-redux'; import { nameToEmojiMap } from './data'; import { getAllImageEmojiByName } from './emojiSelectors'; /* $FlowFixMe: `nameToEmojiMap` is mistyped upstream; elements of `glyphMap` may be either `number` or `string`. */ const UnicodeEmoji = createIconSet(nameToEmojiMap, 'AppleColorEmoji'); type SelectorProps = {| imageEmoji: ImageEmojiType | void, |}; type Props = $ReadOnly<{| name: string, dispatch: Dispatch, ...SelectorProps, |}>; // TODO: this only handles Unicode emoji (shipped with the app) // and realm emoji, but not Zulip extra emoji. See our issue #2846. class Emoji extends PureComponent<Props> { styles = StyleSheet.create({ image: { width: 20, height: 20 }, }); render() { const { name, imageEmoji } = this.props; if (imageEmoji) { return <Image style={this.styles.image} source={{ uri: imageEmoji.source_url }} />; } return <UnicodeEmoji name={name} size={20} />; } } export default connect<SelectorProps, _, _>((state, props) => ({ imageEmoji: getAllImageEmojiByName(state)[props.name], }))(Emoji);
Remove unnecessary librsvg proxy comment
'use strict'; const expect = require('chai').expect; const sinon = require('sinon'); const proxyquire = require('proxyquire'); const Plugin = require('.'); describe('rsvg-brunch', function () { // Brunch will automatically supply the default public directory path if it is // not explicitly overridden by the user const defaultConfig = {paths: {public: 'public'}}; it('should initialize with empty brunch config', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.be.ok; }); it('should initialize with empty plugins config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {}})); expect(plugin).to.be.ok; }); it('should initialize with empty plugin config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {rsvg: {}}})); expect(plugin).to.be.ok; }); it('should require Rsvg module if installed', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.have.property('Rsvg'); }); it('should catch error if system librsvg is not installed', function () { let loggerWarnSpy = sinon.spy(); let ProxiedPlugin = proxyquire('.', { librsvg: null, loggy: {warn: loggerWarnSpy} }); const plugin = new ProxiedPlugin(defaultConfig); expect(plugin).not.to.have.property('Rsvg'); sinon.assert.calledOnce(loggerWarnSpy); }); });
'use strict'; const expect = require('chai').expect; const sinon = require('sinon'); const proxyquire = require('proxyquire'); const Plugin = require('.'); describe('rsvg-brunch', function () { // Brunch will automatically supply the default public directory path if it is // not explicitly overridden by the user const defaultConfig = {paths: {public: 'public'}}; it('should initialize with empty brunch config', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.be.ok; }); it('should initialize with empty plugins config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {}})); expect(plugin).to.be.ok; }); it('should initialize with empty plugin config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {rsvg: {}}})); expect(plugin).to.be.ok; }); it('should require Rsvg module if installed', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.have.property('Rsvg'); }); it('should catch error if system librsvg is not installed', function () { let loggerWarnSpy = sinon.spy(); // Cause require('librsvg').Rsvg to throw an error let ProxiedPlugin = proxyquire('.', { librsvg: null, loggy: {warn: loggerWarnSpy} }); const plugin = new ProxiedPlugin(defaultConfig); expect(plugin).not.to.have.property('Rsvg'); sinon.assert.calledOnce(loggerWarnSpy); }); });
Fix window test border _again_ (more fixed).
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-1, -1, window.width, window.height) glColor3f(0, 1, 0) rect(0, 0, window.width - 1, window.height - 1)
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-1, -1, window.width + 1, window.height - 1) glColor3f(0, 1, 0) rect(0, 0, window.width - 1, window.height - 1)
Add 'type' field to tab enumeration JSON protocol Review URL: https://codereview.chromium.org/12036084 git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@1132 fc8a088e-31da-11de-8fef-1f5ae417a2df
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String faviconUrl(); String title(); String url(); String thumbnailUrl(); // TODO: consider adding enum here String type(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.wip.protocol.input; import java.util.List; import org.chromium.sdk.internal.protocolparser.JsonOptionalField; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; @JsonType(subtypesChosenManually=true) public interface WipTabList { @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException; @JsonType interface TabDescription { String faviconUrl(); String title(); String url(); String thumbnailUrl(); @JsonOptionalField String devtoolsFrontendUrl(); @JsonOptionalField String webSocketDebuggerUrl(); } }
Add ability to save entity
import React, {PropTypes} from 'react'; class CmsApp extends React.Component { constructor(props) { super(props); this.props.actions.addEntity = this.props.actions.addEntity.bind(this); this.save = this.save.bind(this); this.mapEntity = this.mapEntity.bind(this); } save() { console.log(this.props.cmsAppState); this.props.actions.addEntity(this.props.cmsAppState); } toggle() { this.props.actions.toggleEntity(this.props.cmsAppState); } mapEntity(entity, index) { return <form key={index}><input type="text" value={entity.text} onChange={this.save} /><input type="submit" onClick={this.save} /></form>; } render() { return ( <div> {this.props.cmsAppState.map(this.mapEntity)} </div> ); } } CmsApp.propTypes = { actions: PropTypes.object.isRequired, cmsAppState: PropTypes.array.isRequired }; export default CmsApp;
import React, {PropTypes} from 'react'; class CmsApp extends React.Component { constructor(props) { super(props); this.props.actions.addEntity = this.props.actions.addEntity.bind(this); this.save = this.save.bind(this); this.mapEntity = this.mapEntity.bind(this); } save() { this.props.actions.addEntity(this.props.cmsAppState); } toggle() { this.props.actions.toggleEntity(this.props.cmsAppState); } mapEntity(entity, index) { return <form key={index}><input type="text" value={entity.text} onChange={this.save} /></form>; } render() { return ( <div> {this.props.cmsAppState.map(this.mapEntity)} </div> ); } } CmsApp.propTypes = { actions: PropTypes.object.isRequired, cmsAppState: PropTypes.array.isRequired }; export default CmsApp;
Test that regular users can send test emails
from django.test import TestCase from django.core.urlresolvers import reverse from common.util import create_admin, create_user class TestEmailRendering(TestCase): def setUp(self): self.user = create_user(username='user', password='password') self.admin = create_admin(username='admin', password='password') def test_can_get_an_example_email(self): response = self.client.get(reverse('example_email')) self.assertEqual(response.status_code, 200) self.assertContains(response, "Example email") self.assertContains(response, "The email title") def test_can_load_email_sender_if_admin(self): self.client.login(username='admin', password='password') response = self.client.get(reverse('email_sender_test')) self.assertEqual(response.status_code, 200) def test_regular_users_dont_have_access_to_tester(self): self.client.login(username='user', password='password') response = self.client.get(reverse('email_sender_test')) self.assertEqual(response.status_code, 404)
from django.test import TestCase from django.core.urlresolvers import reverse from common.util import create_admin, create_user class TestEmailRendering(TestCase): def setUp(self): self.user = create_user(username='user', password='password') self.admin = create_admin(username='admin', password='password') def test_can_get_an_example_email(self): response = self.client.get(reverse('example_email')) self.assertEqual(response.status_code, 200) self.assertContains(response, "Example email") self.assertContains(response, "The email title") def test_can_load_email_sender_if_admin(self): self.client.login(username='admin', password='password') response = self.client.get(reverse('email_sender_test')) self.assertEqual(response.status_code, 200)
Use S3 Static website hosting instead As best practice on AWS, you should use the static website hosting feature instead of making your bucket become public. With the static website hosting feature, you could also utilise its redirection feature to utilise CDN like AWS Cloudfront to serve public traffic to your S3 bucket. For more information, please read: https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html
<?php /* * This file is part of flagrow/upload. * * Copyright (c) Flagrow. * * http://flagrow.github.io * * For the full copyright and license information, please view the license.md * file that was distributed with this source code. */ namespace Flagrow\Upload\Adapters; use Flagrow\Upload\Contracts\UploadAdapter; use Flagrow\Upload\File; use Illuminate\Support\Arr; class AwsS3 extends Flysystem implements UploadAdapter { /** * @param File $file */ protected function generateUrl(File $file) { $region = $this->adapter->getClient()->getRegion(); $bucket = $this->adapter->getBucket(); $baseUrl = in_array($region, [null, 'us-east-1']) ? sprintf('http://%s.s3-website-us-east-1.amazonaws.com/', $bucket) : sprintf('http://%s.s3-website-%s.amazonaws.com/', $bucket, $region); $file->url = sprintf( $baseUrl . '%s', Arr::get($this->meta, 'path', $file->path) ); } }
<?php /* * This file is part of flagrow/upload. * * Copyright (c) Flagrow. * * http://flagrow.github.io * * For the full copyright and license information, please view the license.md * file that was distributed with this source code. */ namespace Flagrow\Upload\Adapters; use Flagrow\Upload\Contracts\UploadAdapter; use Flagrow\Upload\File; use Illuminate\Support\Arr; class AwsS3 extends Flysystem implements UploadAdapter { /** * @param File $file */ protected function generateUrl(File $file) { $region = $this->adapter->getClient()->getRegion(); $bucket = $this->adapter->getBucket(); $baseUrl = in_array($region, [null, 'us-east-1']) ? 'https://s3.amazonaws.com/' : sprintf('https://s3-%s.amazonaws.com/', $region); $file->url = sprintf( $baseUrl . '%s/%s', $bucket, Arr::get($this->meta, 'path', $file->path) ); } }
Fix version check in light of shelljs changes
#!/usr/bin/env node /* eslint-disable strict */ /* eslint-disable no-console */ /* eslint-disable prefer-template */ 'use strict'; // A simple check that node + npm versions // meet the expected minimums. const exec = require('shelljs').exec; const chalk = require('chalk'); const semver = require('semver'); const MIN_NODE_VERSION = 4; const MIN_NPM_VERSION = 3; const NODE_VERSION = process.versions.node; const NPM_VERSION = exec('npm --version', {silent: true}).stdout; let versionCheckPassed = true; if (semver.major(NODE_VERSION) < MIN_NODE_VERSION) { console.log(chalk.red('Node version must be at least: ' + MIN_NODE_VERSION)); versionCheckPassed = false; } if (semver.major(NPM_VERSION) < MIN_NPM_VERSION) { console.log(chalk.red('NPM version must be at least: ' + MIN_NPM_VERSION)); versionCheckPassed = false; } if (versionCheckPassed === false) { process.exit(1); }
#!/usr/bin/env node /* eslint-disable strict */ /* eslint-disable no-console */ /* eslint-disable prefer-template */ 'use strict'; // A simple check that node + npm versions // meet the expected minimums. const exec = require('shelljs').exec; const chalk = require('chalk'); const semver = require('semver'); const MIN_NODE_VERSION = 4; const MIN_NPM_VERSION = 3; const NODE_VERSION = process.versions.node; const NPM_VERSION = exec('npm --version', {silent: true}).output; let versionCheckPassed = true; if (semver.major(NODE_VERSION) < MIN_NODE_VERSION) { console.log(chalk.red('Node version must be at least: ' + MIN_NODE_VERSION)); versionCheckPassed = false; } if (semver.major(NPM_VERSION) < MIN_NPM_VERSION) { console.log(chalk.red('NPM version must be at least: ' + MIN_NPM_VERSION)); versionCheckPassed = false; } if (versionCheckPassed === false) { process.exit(1); }
Include Mail 1.1.3 with PHP 5. git-svn-id: 4b064e69dc630d28214c1e1442d27300cccf8e9a@155591 c90b9560-bf6c-de11-be94-00142212c4b1
<?php /* This is a list of packages and versions * that will be used to create the PEAR folder * in the windows snapshot. * See win32/build/mkdist.php for more details * $Id$ */ $packages = array( "PEAR" => "1.3.1", "Mail" => "1.1.3", "Net_SMTP" => "1.2.5", "Net_Socket" => "1.0.1", "PHPUnit" => "2.0.0beta1", "Console_Getopt" => "1.2", "DB" => "1.6.2", "HTTP" => "1.2.3", "Archive_Tar" => "1.1", "Pager" => "1.0.8", "HTML_Template_IT" => "1.1", "XML_Parser" => "1.0.1", "XML_RPC" => "1.1.0", "Net_UserAgent_Detect" => "1.0", "PEAR_Frontend_Web" => "0.3" ); ?>
<?php /* This is a list of packages and versions * that will be used to create the PEAR folder * in the windows snapshot. * See win32/build/mkdist.php for more details * $Id$ */ $packages = array( "PEAR" => "1.3.1", "Mail" => "1.1.2", "Net_SMTP" => "1.2.5", "Net_Socket" => "1.0.1", "PHPUnit" => "2.0.0beta1", "Console_Getopt" => "1.2", "DB" => "1.6.2", "HTTP" => "1.2.3", "Archive_Tar" => "1.1", "Pager" => "1.0.8", "HTML_Template_IT" => "1.1", "XML_Parser" => "1.0.1", "XML_RPC" => "1.1.0", "Net_UserAgent_Detect" => "1.0", "PEAR_Frontend_Web" => "0.3" ); ?>
Remove unnecessary code for print debug
""""Test adapter specific config options.""" from pprint import pprint from test.integration.base import DBTIntegrationTest, use_profile import textwrap import yaml class TestBigqueryAdapterSpecific(DBTIntegrationTest): @property def schema(self): return "bigquery_test_022" @property def models(self): return "adapter-specific-models" @property def profile_config(self): return self.bigquery_profile() @property def project_config(self): return yaml.safe_load(textwrap.dedent('''\ config-version: 2 models: test: materialized: table expiring_table: hours_to_expiration: 4 ''')) @use_profile('bigquery') def test_bigquery_hours_to_expiration(self): _, stdout = self.run_dbt_and_capture(['--debug', 'run']) self.assertIn( 'expiration_timestamp=TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL ' '4 hour)', stdout)
""""Test adapter specific config options.""" from pprint import pprint from test.integration.base import DBTIntegrationTest, use_profile import textwrap import yaml class TestBigqueryAdapterSpecific(DBTIntegrationTest): @property def schema(self): return "bigquery_test_022" @property def models(self): return "adapter-specific-models" @property def profile_config(self): return self.bigquery_profile() @property def project_config(self): return yaml.safe_load(textwrap.dedent('''\ config-version: 2 models: test: materialized: table expiring_table: hours_to_expiration: 4 ''')) @use_profile('bigquery') def test_bigquery_hours_to_expiration(self): _, stdout = self.run_dbt_and_capture(['--debug', 'run']) pprint(stdout) self.assertIn( 'expiration_timestamp=TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL ' '4 hour)', stdout)
Add a system for tests to register objects for deletion. They should be deleted no matter the outcome of the test.
import os import random from unittest2 import TestCase from chef.api import ChefAPI TEST_ROOT = os.path.dirname(os.path.abspath(__file__)) def test_chef_api(): return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests') class ChefTestCase(TestCase): """Base class for Chef unittests.""" def setUp(self): super(ChefTestCase, self).setUp() self.api = test_chef_api() self.api.set_default() self.objects = [] def tearDown(self): for obj in self.objects: try: obj.delete() except ChefError, e: print e # Continue running def register(self, obj): self.objects.append(obj) def random(self, length=8, alphabet='0123456789abcdef'): return ''.join(random.choice(alphabet) for _ in xrange(length))
import os import random from unittest2 import TestCase from chef.api import ChefAPI TEST_ROOT = os.path.dirname(os.path.abspath(__file__)) def test_chef_api(): return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests') class ChefTestCase(TestCase): """Base class for Chef unittests.""" def setUp(self): super(ChefTestCase, self).setUp() self.api = test_chef_api() self.api.set_default() def random(self, length=8, alphabet='0123456789abcdef'): return ''.join(random.choice(alphabet) for _ in xrange(length))
Correct deleting FactoryMuffin Facades after test classes
<?php namespace RCatlin\Blog\Test; use Doctrine\ORM\EntityManager; use League\FactoryMuffin\Facade as FactoryMuffin; /** * Loads Facades using league\factory-muffin. Meant to be used in Integration Tests * that extend AbstractIntegrationTest. */ trait LoadsFactoryMuffinFactories { public static function setUpBeforeClass() { parent::setUpBeforeClass(); FactoryMuffin::loadFactories(__DIR__ . '/Factory'); /** @var EntityManager $entityManager */ $entityManager = self::$entityManager; FactoryMuffin::setCustomSaver(function ($object) use ($entityManager) { $entityManager->persist($object); $entityManager->flush($object); return true; }); FactoryMuffin::setCustomDeleter(function ($object) use ($entityManager) { if (!$entityManager->contains($object)) { return true; } $entityManager->remove($object); $entityManager->flush(); return true; }); } public static function tearDownAfterClass() { parent::tearDownAfterClass(); FactoryMuffin::deleteSaved(); } }
<?php namespace RCatlin\Blog\Test; use League\FactoryMuffin\Facade as FactoryMuffin; /** * Loads Facades using league\factory-muffin. Meant to be used in Integration Tests * that extend AbstractIntegrationTest. */ trait LoadsFactoryMuffinFactories { public static function setUpBeforeClass() { parent::setUpBeforeClass(); FactoryMuffin::loadFactories(__DIR__ . '/Factory'); $entityManager = self::$entityManager; FactoryMuffin::setCustomSaver(function ($object) use ($entityManager) { $entityManager->persist($object); $entityManager->flush($object); return true; }); } public static function tearDownBeforeClass() { $entityManager = self::$entityManager; FactoryMuffin::setCustomDeleter(function ($object) use ($entityManager) { $entityManager->remove($object); $entityManager->flush(); }); FactoryMuffin::deleteSaved(); parent::tearDownAfterClass(); } }
:lipstick: Make background tasks always visible under their full name.
<?php namespace Assistant\Module\Common\Task; use Monolog\Logger; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; abstract class AbstractTask extends Command { public const IGNORED_PARAMETERS = [ 'help', 'ansi', 'no-ansi', 'no-interaction', 'quiet', 'verbose', 'version' ]; protected InputInterface $input; protected OutputInterface $output; public function __construct(protected Logger $logger) { parent::__construct(); } protected function initialize(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; $this->logger->pushProcessor(function ($record) { $taskName = static::getDefaultName(); $record['context']['command'] = $taskName; $record['extra']['task'] = $taskName; return $record; }); } protected static function getInputParams(InputInterface $input): array { $params = array_merge($input->getArguments(), $input->getOptions()); $withoutIgnoredParams = array_diff_key($params, array_flip(self::IGNORED_PARAMETERS)); return $withoutIgnoredParams; } }
<?php namespace Assistant\Module\Common\Task; use Monolog\Logger; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; abstract class AbstractTask extends Command { public const IGNORED_PARAMETERS = [ 'help', 'ansi', 'no-ansi', 'no-interaction', 'quiet', 'verbose', 'version' ]; protected InputInterface $input; protected OutputInterface $output; public function __construct(protected Logger $logger) { parent::__construct(); } protected function initialize(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; $this->logger->pushProcessor(function ($record) { $record['extra']['task'] = $this->getName(); return $record; }); } protected static function getInputParams(InputInterface $input): array { $params = array_merge($input->getArguments(), $input->getOptions()); $withoutIgnoredParams = array_diff_key($params, array_flip(self::IGNORED_PARAMETERS)); return $withoutIgnoredParams; } }
Remove Parser, export Encoder and Decoder
/** * Library version. */ exports.version = '0.0.1'; /** * Constructors. */ exports.Batch = require('./batch'); exports.Decoder = require('./decoder'); exports.Encoder = require('./encoder'); exports.Socket = require('./sockets/sock'); exports.Queue = require('./sockets/queue'); exports.PubSocket = require('./sockets/pub'); exports.SubSocket = require('./sockets/sub'); exports.PushSocket = require('./sockets/push'); exports.PullSocket = require('./sockets/pull'); exports.EmitterSocket = require('./sockets/emitter'); /** * Socket types. */ exports.types = { stream: exports.Socket, queue: exports.Queue, pub: exports.PubSocket, sub: exports.SubSocket, push: exports.PushSocket, pull: exports.PullSocket, emitter: exports.EmitterSocket }; /** * Codecs. */ exports.codec = require('./codecs'); /** * Return a new socket of the given `type`. * * @param {String} type * @param {Object} options * @return {Socket} * @api public */ exports.socket = function(type, options){ var fn = exports.types[type]; if (!fn) throw new Error('invalid socket type "' + type + '"'); return new fn(options); };
/** * Library version. */ exports.version = '0.0.1'; /** * Constructors. */ exports.Batch = require('./batch'); exports.Parser = require('./parser'); exports.Socket = require('./sockets/sock'); exports.Queue = require('./sockets/queue'); exports.PubSocket = require('./sockets/pub'); exports.SubSocket = require('./sockets/sub'); exports.PushSocket = require('./sockets/push'); exports.PullSocket = require('./sockets/pull'); exports.EmitterSocket = require('./sockets/emitter'); /** * Socket types. */ exports.types = { stream: exports.Socket, queue: exports.Queue, pub: exports.PubSocket, sub: exports.SubSocket, push: exports.PushSocket, pull: exports.PullSocket, emitter: exports.EmitterSocket }; /** * Codecs. */ exports.codec = require('./codecs'); /** * Return a new socket of the given `type`. * * @param {String} type * @param {Object} options * @return {Socket} * @api public */ exports.socket = function(type, options){ var fn = exports.types[type]; if (!fn) throw new Error('invalid socket type "' + type + '"'); return new fn(options); };
Remove tensorflow as dependency for now
# -*- coding: utf-8 -*- from setuptools import setup import ogres requirements = [] # Requires tensorflow, but no easy install script exist version = ogres.__version__ setup( name="ogres", version=version, url="https://github.com/butternutdog/ogres", download_url="https://github.com/butternutdog/ogres/tarball/{0}".format(version), license="MIT", author="Martin Singh-Blom, Jonny Reichwald", author_email="ogres@butternutdog.com", maintainer="ogres@butternutdog.com", description="Thin tensorflow wrapper. Requires tensorflow", long_description=None, packages=["ogres"], install_requires=requirements, scripts=[], platforms="any", zip_safe=True, classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", ] )
# -*- coding: utf-8 -*- from setuptools import setup import ogres requirements = ["tensorflow>=0.10"] version = ogres.__version__ setup( name="ogres", version=version, url="https://github.com/butternutdog/ogres", download_url="https://github.com/butternutdog/ogres/tarball/{0}".format(version), license="MIT", author="Martin Singh-Blom, Jonny Reichwald", author_email="ogres@butternutdog.com", maintainer="ogres@butternutdog.com", description="Thin tensorflow wrapper. Requires tensorflow", long_description=None, packages=["ogres"], install_requires=requirements, scripts=[], platforms="any", zip_safe=True, classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", ] )
Send an empty list instead of None if no projects selected for homepage.
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = Project.objects.none() return self
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = None return self
Replace all occurrences of dot, not just the first
trackerdash.views.ResultTablePane = Backbone.View.extend({ el: '.result-table-pane', initialize: function (settings) { this.results = settings.percentErrorByDataset; if (this.results === undefined) { console.error('No error percentages defined.'); } this.render(); }, render: function () { _.each(this.results, function (result) { result.id = result.dataset.replace(/\./g, "_"); }); var resultsByDataset = _.groupBy(this.results, function (result) { return result.dataset; }); this.$el.html(jade.templates.tablePane({ resultsByDataset: resultsByDataset })); this.$el.promise().done(_.bind(function () { _.each(this.results, function (result) { new trackerdash.views.ErrorBulletWidget({ el: '#' + result.id + '-' + result.metric + ' svg', result: result }); }); }, this)); } });
trackerdash.views.ResultTablePane = Backbone.View.extend({ el: '.result-table-pane', initialize: function (settings) { this.results = settings.percentErrorByDataset; if (this.results === undefined) { console.error('No error percentages defined.'); } this.render(); }, render: function () { _.each(this.results, function (result) { result.id = result.dataset.replace(".","_"); }); var resultsByDataset = _.groupBy(this.results, function (result) { return result.dataset; }); this.$el.html(jade.templates.tablePane({ resultsByDataset: resultsByDataset })); this.$el.promise().done(_.bind(function () { _.each(this.results, function (result) { new trackerdash.views.ErrorBulletWidget({ el: '#' + result.id + '-' + result.metric + ' svg', result: result }); }); }, this)); } });
Write iface choice to file This seems unnecessary but I can't see a way to pass a string back from python, because of the prompt.
#apt-get install python-pip #pip install netifaces import netifaces def select_iface(iface): try: iface = int(iface) if(iface < 0): raise IndexError return netifaces.interfaces()[iface] except IndexError: print "Number provided was too big or small" return [] except ValueError: print "Please enter an interface number" return [] print "Please choose a network interface to run the honeypot on:\r\n" i = 0 for ifaces in netifaces.interfaces(): print "\t[",i,"]",ifaces,"(",netifaces.ifaddresses(ifaces)[netifaces.AF_INET],")" i = i+1 print "\r\n" found = [] while(not found): found=select_iface(raw_input('Chosen interface: ')) f = open(os.path.expanduser('~/.honey_iface'), 'w') f.write(found)
#apt-get install python-pip #pip install netifaces import netifaces def select_iface(iface): try: iface = int(iface) if(iface < 0): raise IndexError return netifaces.interfaces()[iface] except IndexError: print "Number provided was too big or small" return [] except ValueError: print "Please enter an interface number" return [] print "Please choose a network interface to run the honeypot on:\r\n" i = 0 for ifaces in netifaces.interfaces(): print "\t[",i,"]",ifaces,"(",netifaces.ifaddresses(ifaces)[netifaces.AF_INET],")" i = i+1 print "\r\n" found = [] while(not found): found=select_iface(raw_input('Chosen interface: ')) print found
Use formatted price instead of price
<?php class Product { private $_name; private $_price; private $_url; public function __construct($data) { $this->_parseData($data); } public function getName() { return $this->_name; } public function getPrice() { return $this->_price; } public function getUrl() { return $this->_url; } private function _parseData($data) { if (isset($data['product'])) { if (isset($data['product']['name'])) { $this->_name = $data['product']['name']; } if (isset($data['product']['formattedPrice'])) { $this->_price = $data['product']['formattedPrice']; } if (isset($data['product']['url'])) { $this->_url = $data['product']['url']; } } } }
<?php class Product { private $_name; private $_price; private $_url; public function __construct($data) { $this->_parseData($data); } public function getName() { return $this->_name; } public function getPrice() { return $this->_price; } public function getUrl() { return $this->_url; } private function _parseData($data) { if (isset($data['product'])) { if (isset($data['product']['name'])) { $this->_name = $data['product']['name']; } if (isset($data['product']['price'])) { $this->_price = $data['product']['price']; } if (isset($data['product']['url'])) { $this->_url = $data['product']['url']; } } } }
Switch logger to default to dynmap-specific logger
package org.dynmap; import java.util.logging.Level; import java.util.logging.Logger; public class Log { protected static Logger log = Logger.getLogger("Dynmap"); protected static String prefix = ""; public static boolean verbose = false; public static void setLogger(Logger logger, String pre) { log = logger; if((pre != null) && (pre.length() > 0)) prefix = pre + " "; else prefix = ""; } public static void info(String msg) { log.log(Level.INFO, prefix + msg); } public static void verboseinfo(String msg) { if(verbose) log.log(Level.INFO, prefix + msg); } public static void severe(Throwable e) { log.log(Level.SEVERE, prefix + "Exception occured: ", e); } public static void severe(String msg) { log.log(Level.SEVERE, prefix + msg); } public static void severe(String msg, Throwable e) { log.log(Level.SEVERE, prefix + msg, e); } public static void warning(String msg) { log.log(Level.WARNING, prefix + msg); } public static void warning(String msg, Throwable e) { log.log(Level.WARNING, prefix + msg, e); } }
package org.dynmap; import java.util.logging.Level; import java.util.logging.Logger; public class Log { protected static Logger log = Logger.getLogger("Minecraft"); protected static String prefix = "[dynmap] "; public static boolean verbose = false; public static void setLogger(Logger logger, String pre) { log = logger; if((pre != null) && (pre.length() > 0)) prefix = pre + " "; else prefix = ""; } public static void info(String msg) { log.log(Level.INFO, prefix + msg); } public static void verboseinfo(String msg) { if(verbose) log.log(Level.INFO, prefix + msg); } public static void severe(Throwable e) { log.log(Level.SEVERE, prefix + "Exception occured: ", e); } public static void severe(String msg) { log.log(Level.SEVERE, prefix + msg); } public static void severe(String msg, Throwable e) { log.log(Level.SEVERE, prefix + msg, e); } public static void warning(String msg) { log.log(Level.WARNING, prefix + msg); } public static void warning(String msg, Throwable e) { log.log(Level.WARNING, prefix + msg, e); } }
Clean this up a little. Needs name as well to differentiate torgets
package main import ( "fmt" "time" metrics "github.com/rcrowley/go-metrics" ) type ChanGroup struct { Name string points []chan []interface{} depthGauges []metrics.Gauge } func NewChanGroup(name string, chanCap int) *ChanGroup { group := &ChanGroup{Name: name} group.points = make([]chan []interface{}, numSeries) group.depthGauges = make([]metrics.Gauge, numSeries) for i := 0; i < numSeries; i++ { group.points[i] = make(chan []interface{}, chanCap) group.depthGauges[i] = metrics.NewRegisteredGauge( fmt.Sprintf("lumbermill.points.pending.%s.%s", seriesNames[i], name), metrics.DefaultRegistry, ) } go group.Sample(10 * time.Second) return group } // Update depth guages every so often func (g *ChanGroup) Sample(every time.Duration) { for { time.Sleep(every) for i, gauge := range g.depthGauges { gauge.Update(int64(len(g.points[i]))) } } }
package main import ( "fmt" "time" metrics "github.com/rcrowley/go-metrics" ) type ChanGroup struct { Name string points []chan []interface{} depthGauges []metrics.Gauge } func NewChanGroup(name string, chanCap int) *ChanGroup { group := &ChanGroup{Name: name} group.points = make([]chan []interface{}, numSeries) group.depthGauges = make([]metrics.Gauge, numSeries) for i := 0; i < numSeries; i++ { group.points[i] = make(chan []interface{}, chanCap) group.depthGauges[i] = metrics.NewGauge() metrics.DefaultRegistry.Register( fmt.Sprintf("lumbermill.points.%s.pending", seriesNames[i]), group.depthGauges[i], ) } go group.Sample(10 * time.Second) return group } // Update depth guages every so often func (g *ChanGroup) Sample(every time.Duration) { for { time.Sleep(every) for i, gauge := range g.depthGauges { gauge.Update(int64(len(g.points[i]))) } } }
Rename 'category' to 'level' and update filters
<?php class Vocabulary extends Model { public function get_set() { return $this->belongs_to('Set'); } /** * Filters */ public static function active($orm) { return $orm->where_gte('level', 0)->order_by_asc('id'); } public static function inactive($orm) { return $orm->where_lt('level', 0)->order_by_asc('id'); } public static function due($orm) { return $orm->where_lte('due', date('Y-m-d H:i:s'))->order_by_asc('id'); } public static function learned_today($orm) { return $orm->where('init_date', date('Y-m-d')); } }
<?php class Vocabulary extends Model { public function get_set() { return $this->belongs_to('Set'); } /** * Filters */ public static function active($orm) { return $orm->where_gte('category', 1)->order_by_asc('id'); } public static function inactive($orm) { return $orm->where_lte('category', 0)->order_by_asc('id'); } public static function due($orm) { return $orm->where_lte('due', date('Y-m-d H:i:s'))->order_by_asc('id'); } public static function learned_today($orm) { return $orm->where('init_date', date('Y-m-d')); } }
Improve slider handling and updates
import Component from '@ember/component'; import { computed } from '@ember/object'; import { notEmpty, or } from '@ember/object/computed'; export default Component.extend({ classNames: ['upf-slider'], classNameBindings: ['color', 'active'], value: or('options.value', '0'), active: notEmpty('options.value'), color: computed('value', 'active', 'options.value', function() { if(!this.active) { return; } if (this.value <= this.options.lowValue) { return this.options.lowClass; } else if (this.value <= this.options.mediumValue) { return this.options.mediumClass; } return this.options.highClass; }), didInsertElement() { this.$('.slider').ionRangeSlider({ skin: 'round', min: this.options.min, max: this.options.max, from: this.options.value || this.options.max/2, hide_min_max: true, onChange: (data) => { if(!this.active) { this.toggleProperty('active'); } this.set('value', data.from); }, onFinish: (data) => { this.onChange(data.from); }, prettify: this.formatValue || null }); } });
import Component from '@ember/component'; import { computed } from '@ember/object'; export default Component.extend({ classNames: ['upf-slider'], classNameBindings: ['color'], value: 0, active: false, color: computed('value', 'active', function() { if(!this.active) { return; } if (this.value <= this.options.lowValue) { return this.options.lowClass; } else if (this.value <= this.options.mediumValue) { return this.options.mediumClass; } return this.options.highClass; }), didInsertElement() { this.$('.slider').ionRangeSlider({ skin: 'round', min: this.options.min, max: this.options.max, from: this.options.max/2, hide_min_max: true, onChange: (data) => { if(!this.active) { this.toggleProperty('active'); } this.set('value', data.from); this.onChange(data.from); }, prettify: this.formatValue || null }); } });
Fix migration to create cookie token table
<?php use Phinx\Migration\AbstractMigration; class CreateCookieTokens extends AbstractMigration{ public function change(){ try { $sql = ''; $sql = $sql.'CREATE TABLE `cookie_tokens` ('; $sql = $sql.' `id` integer(11) UNSIGNED NOT NULL AUTO_INCREMENT,'; $sql = $sql.' `selector` char(12),'; $sql = $sql.' `hashedValidator` char(64),'; $sql = $sql.' `user_id` integer(11) UNSIGNED NOT NULL UNSIGNED,'; $sql = $sql.' `expires` datetime,'; $sql = $sql.' PRIMARY KEY (`id`)'; $sql = $sql.') ENGINE=InnoDB DEFAULT CHARSET=utf8;'; $row = $this->fetchRow($sql); }catch(Exception $e){ } } }
<?php use Phinx\Migration\AbstractMigration; class CreateCookieTokens extends AbstractMigration{ public function change(){ try { $sql = ''; $sql = $sql.'CREATE TABLE `cookie_tokens` ('; $sql = $sql.' `id` integer(11) not null UNSIGNED AUTO_INCREMENT,'; $sql = $sql.' `selector` char(12),'; $sql = $sql.' `hashedValidator` char(64),'; $sql = $sql.' `user_id` integer(11) not null UNSIGNED,'; $sql = $sql.' `expires` datetime,'; $sql = $sql.' PRIMARY KEY (`id`)'; $sql = $sql.') ENGINE=InnoDB DEFAULT CHARSET=utf8;'; $row = $this->fetchRow($sql); }catch(Exception $e){ } } }
Set ssl to false per default
<?php return array( /* |-------------------------------------------------------------------------- | Settings |-------------------------------------------------------------------------- | | Configure the CMS here | */ 'settings' => array( 'log' => false, // Logs the application performance 'ssl' => false, // Force to use https:// requests in the backend ), 'email' => array( 'from' => array('address' => null, 'name' => null), ), /* |-------------------------------------------------------------------------- | Names |-------------------------------------------------------------------------- | | Define all kinds of names here | */ 'names' => array( 'cms' => 'larapress', ), /* |-------------------------------------------------------------------------- | URL Configuration |-------------------------------------------------------------------------- | | Define larapress related urls here | */ 'urls' => array( 'backend' => 'admin' ), );
<?php return array( /* |-------------------------------------------------------------------------- | Settings |-------------------------------------------------------------------------- | | Configure the CMS here | */ 'settings' => array( 'log' => false, // Logs the application performance 'ssl' => true, // Force to use https:// requests in the backend ), 'email' => array( 'from' => array('address' => null, 'name' => null), ), /* |-------------------------------------------------------------------------- | Names |-------------------------------------------------------------------------- | | Define all kinds of names here | */ 'names' => array( 'cms' => 'larapress', ), /* |-------------------------------------------------------------------------- | URL Configuration |-------------------------------------------------------------------------- | | Define larapress related urls here | */ 'urls' => array( 'backend' => 'admin' ), );
Fix the error message when the name is taken
'use strict'; import jwt from 'jwt-simple'; import { userModel } from '../../../models/index'; import { secret } from '../../../config/config'; import { buildResponse } from '../../../utils/responseService'; export const saveUser = (req, res) => { userModel.findOne({name: req.body.name}) .then(user => { if (user) { throw new Error('That name is already taken'); } else { const user = new userModel({ name: req.body.name, fullname: req.body.fullname, password: req.body.password, initials: req.body.initials, email: req.body.email }); return user.save(); } }) .then(user => buildResponse(200, jwt.encode(user._id, secret), res)) .catch(err => buildResponse(500, err.message, res)); };
'use strict'; import jwt from 'jwt-simple'; import { userModel } from '../../../models/index'; import { secret } from '../../../config/config'; import { buildResponse } from '../../../utils/responseService'; export const saveUser = (req, res) => { userModel.findOne({name: req.body.name}) .then(user => { if (user) { buildResponse(400, 'That name is already taken', res); } else { const user = new userModel({ name: req.body.name, fullname: req.body.fullname, password: req.body.password, initials: req.body.initials, email: req.body.email }); return user.save(); } }) .then(user => buildResponse(200, jwt.encode(user._id, secret), res)) .catch(err => buildResponse(500, err, res)); };
Fix the location path of OpenIPSL
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
Change command option, need to specify file name now
#!/usr/bin/python import serial import string import io import time import sys if __name__ == '__main__': port = "/dev/ttyUSB0" baudrate = "57600" second = 0.001 if (len(sys.argv) < 4 ): print("Usage: \n./serial_dump.py /dev/ttyUSB0 57600 file_name 0.01") exit() elif (len(sys.argv) == 4): port = sys.argv[1] baudrate = sys.argv[2] file_name = sys.argv[3] elif (len(sys.argv) == 5): port = sys.argv[1] baudrate = sys.argv[2] file_name = sys.argv[3] second = float(sys.argv[4]) print( "open {0}, buadrate {1}, delay in {2} seconds".format(port,baudrate,second)) ser = serial.Serial(port, baudrate); with open(file_name,"rb") as f: string = f.read() for byte in string: ser.write(byte) print_byte = ":".join("{:02x}".format(ord(c)) for c in byte) print ("{0} ".format(print_byte)) time.sleep(second) ser.close()
#!/usr/bin/python import serial import string import io import time import sys if __name__ == '__main__': port = "/dev/ttyUSB0" baudrate = "57600" second = 0.1 if (len(sys.argv) < 3): print("Usage: serial_dump.py /dev/ttyUSB0 57600") exit() elif (len(sys.argv) == 3): port = sys.argv[1] baudrate = sys.argv[2] elif (len(sys.argv) == 4): port = sys.argv[1] baudrate = sys.argv[2] second = float(sys.argv[3]) print( "open {0}, buadrate {1}, delay in {2} seconds".format(port,baudrate,second)) ser = serial.Serial(port, baudrate); with open("gps.log","rb") as f: string = f.read() for byte in string: ser.write(byte) print_byte = ":".join("{:02x}".format(ord(c)) for c in byte) print ("{0} ".format(print_byte)) time.sleep(second) ser.close()
Remove duplicate assignment of goEvidence.
package uk.ac.ebi.quickgo.annotation.service.converter; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.model.Annotation; import java.util.ArrayList; /** * Concrete implementation of the {@link AnnotationDocConverter}. * * @author Tony Wardell * Date: 26/04/2016 * Time: 16:52 */ public class AnnotationDocConverterImpl implements AnnotationDocConverter { @Override public Annotation convert(AnnotationDocument annotationDocument) { Annotation annotation = new Annotation(); annotation.id = annotationDocument.id; annotation.geneProductId = annotationDocument.geneProductId; annotation.qualifier = annotationDocument.qualifier; annotation.goId = annotationDocument.goId; annotation.goEvidence = annotationDocument.goEvidence; annotation.ecoId = annotationDocument.ecoId; annotation.reference = annotationDocument.reference; annotation.assignedBy = annotationDocument.assignedBy; if(annotationDocument.withFrom != null) { annotation.withFrom = new ArrayList<>(annotationDocument.withFrom); } if(annotationDocument.extensions != null) { annotation.extensions = new ArrayList<>(annotationDocument.extensions); } return annotation; } }
package uk.ac.ebi.quickgo.annotation.service.converter; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.model.Annotation; import java.util.ArrayList; /** * Concrete implementation of the {@link AnnotationDocConverter}. * * @author Tony Wardell * Date: 26/04/2016 * Time: 16:52 */ public class AnnotationDocConverterImpl implements AnnotationDocConverter { @Override public Annotation convert(AnnotationDocument annotationDocument) { Annotation annotation = new Annotation(); annotation.id = annotationDocument.id; annotation.geneProductId = annotationDocument.geneProductId; annotation.qualifier = annotationDocument.qualifier; annotation.goId = annotationDocument.goId; annotation.goEvidence = annotationDocument.goEvidence; annotation.ecoId = annotationDocument.ecoId; annotation.reference = annotationDocument.reference; annotation.assignedBy = annotationDocument.assignedBy; if(annotationDocument.withFrom != null) { annotation.withFrom = new ArrayList<>(annotationDocument.withFrom); } if(annotationDocument.extensions != null) { annotation.extensions = new ArrayList<>(annotationDocument.extensions); } annotation.goEvidence = annotationDocument.goEvidence; return annotation; } }
Fix search by adding trait_type_id to path
$(document).ready(function(){ //autocomplete for trait search $("#search_trait").autocomplete({ position: { my: "right top", at: "right bottom" }, source: function (request, response) { var search = request.term; $.ajax({ url: WebRoot.concat("/ajax/listing/Traits"), data: {term: request.term, search: search, limit: 500, dbversion: DbVersion}, dataType: "json", success: function (data) { response(data); } }); }, minLength: 3 }); $("#search_trait").data("ui-autocomplete")._renderItem = function (ul, item) { var li = $("<li>") .append("<a href='"+WebRoot+"/"+DbVersion+"/trait/details/byId/"+item.trait_type_id+"'><span style='display:inline-block; width: 100%; font-style: italic;'>" + item.name + "</span></a>") .appendTo(ul); return li; }; });
$(document).ready(function(){ //autocomplete for trait search $("#search_trait").autocomplete({ position: { my: "right top", at: "right bottom" }, source: function (request, response) { var search = request.term; $.ajax({ url: WebRoot.concat("/ajax/listing/Traits"), data: {term: request.term, search: search, limit: 500, dbversion: DbVersion}, dataType: "json", success: function (data) { response(data); } }); }, minLength: 3 }); $("#search_trait").data("ui-autocomplete")._renderItem = function (ul, item) { var li = $("<li>") .append("<a href='"+WebRoot+"/"+DbVersion+"/trait/details/byId/"+item.type_cvterm_id+"'><span style='display:inline-block; width: 100%; font-style: italic;'>" + item.name + "</span></a>") .appendTo(ul); return li; }; });
Add low and high options to AdditiveGaussian
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import numpy as np from chainerrl import explorer class AdditiveGaussian(explorer.Explorer): """Additive Gaussian noise to actions. Each action must be numpy.ndarray. Args: scale (float or array_like of floats): Scale parameter. """ def __init__(self, scale, low=None, high=None): self.scale = scale self.low = low self.high = high def select_action(self, t, greedy_action_func, action_value=None): a = greedy_action_func() noise = np.random.normal( scale=self.scale, size=a.shape).astype(np.float32) if self.low is not None or self.high is not None: return np.clip(a + noise, self.low, self.high) else: return a + noise def __repr__(self): return 'AdditiveGaussian(scale={})'.format(self.scale)
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import numpy as np from chainerrl import explorer class AdditiveGaussian(explorer.Explorer): """Additive Gaussian noise to actions. Each action must be numpy.ndarray. Args: scale (float or array_like of floats): Scale parameter. """ def __init__(self, scale): self.scale = scale def select_action(self, t, greedy_action_func, action_value=None): a = greedy_action_func() noise = np.random.normal( scale=self.scale, size=a.shape).astype(np.float32) return a + noise def __repr__(self): return 'AdditiveGaussian(scale={})'.format(self.scale)
Fix args in entry point
import sys import serial from blueplayer import blueplayer def main(): args = sys.argv[1:] # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyAMA0" else: port = args[0] player = None with serial.Serial(port) as serial_port: try: player = blueplayer.BluePlayer(serial_port) player.start() except KeyboardInterrupt as ex: print("\nBluePlayer cancelled by user") except Exception as ex: print("How embarrassing. The following error occurred {}".format(ex)) finally: if player: player.end() player.stop() if __name__ == "__main__": main()
import sys import serial from blueplayer import blueplayer def main(args): # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyAMA0" else: port = args[0] player = None with serial.Serial(port) as serial_port: try: player = blueplayer.BluePlayer(serial_port) player.start() except KeyboardInterrupt as ex: print("\nBluePlayer cancelled by user") except Exception as ex: print("How embarrassing. The following error occurred {}".format(ex)) finally: if player: player.end() player.stop() if __name__ == "__main__": main(sys.argv[1:])
Use the base Language.getMimeTypes implementation.
/* * Copyright (C) 2016 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.lang; import com.intellij.lang.Language; import org.jetbrains.annotations.NotNull; public class XQuery extends Language { public static final XQuery INSTANCE = new XQuery(); private XQuery() { super("XQuery", "application/xquery"); } @Override public boolean isCaseSensitive() { return true; } }
/* * Copyright (C) 2016 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.lang; import com.intellij.lang.Language; import org.jetbrains.annotations.NotNull; public class XQuery extends Language { public static final String[] MIME_TYPES = new String[] { "application/xquery" }; public static final XQuery INSTANCE = new XQuery(); private XQuery() { super("XQuery", "application/xquery"); } @Override public boolean isCaseSensitive() { return true; } @NotNull @Override public String[] getMimeTypes() { return MIME_TYPES; } }
Update concatenation algorithm to prevent strings larger than the max length From https://github.com/ljharb/proposal-string-pad-left-right/commit/7b6261b9a23cbc00daf0b232c1b40243adcce7d8
'use strict'; var bind = require('function-bind'); var ES = require('es-abstract/es7'); var slice = bind.call(Function.call, String.prototype.slice); module.exports = function padLeft(maxLength) { var O = ES.RequireObjectCoercible(this); var S = ES.ToString(O); var stringLength = ES.ToLength(S.length); var fillString; if (arguments.length > 1) { fillString = arguments[1]; } var F = typeof fillString === 'undefined' ? '' : ES.ToString(fillString); if (F === '') { F = ' '; } var intMaxLength = ES.ToLength(maxLength); if (intMaxLength <= stringLength) { return S; } var fillLen = intMaxLength - stringLength; while (F.length < fillLen) { var fLen = F.length; var remainingCodeUnits = fillLen - fLen; F += fLen > remainingCodeUnits ? slice(F, 0, remainingCodeUnits) : F; } var truncatedStringFiller = F.length > fillLen ? slice(F, 0, fillLen) : F; return truncatedStringFiller + S; };
'use strict'; var bind = require('function-bind'); var ES = require('es-abstract/es7'); var slice = bind.call(Function.call, String.prototype.slice); module.exports = function padLeft(maxLength) { var O = ES.RequireObjectCoercible(this); var S = ES.ToString(O); var stringLength = ES.ToLength(S.length); var fillString; if (arguments.length > 1) { fillString = arguments[1]; } var F = typeof fillString === 'undefined' ? '' : ES.ToString(fillString); if (F === '') { F = ' '; } var intMaxLength = ES.ToLength(maxLength); if (intMaxLength <= stringLength) { return S; } var fillLen = intMaxLength - stringLength; while (F.length < fillLen) { F += F; } var truncatedStringFiller = F.length > fillLen ? slice(F, 0, fillLen) : F; return truncatedStringFiller + S; };
Make the log work when deploy Zaqar with uwsgi The zaqar-wsgi runs under uwsgi by devstack can't print any WARNING, DEBUG, ERROR or INFO log now. This path add the log initialization for uwsgi boot. Change-Id: Ifcd6be908442275d2acbde2562e593b2ca87b277 Cloese-bug: #1645492
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from oslo_log import log from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF log.register_options(conf) conf(project='zaqar', prog='zaqar-queues', args=[]) log.setup(conf, 'zaqar') boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
# Copyright (c) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """WSGI App for WSGI Containers This app should be used by external WSGI containers. For example: $ gunicorn zaqar.transport.wsgi.app:app NOTE: As for external containers, it is necessary to put config files in the standard paths. There's no common way to specify / pass configuration files to the WSGI app when it is called from other apps. """ from oslo_config import cfg from zaqar import bootstrap # Use the global CONF instance conf = cfg.CONF conf(project='zaqar', prog='zaqar-queues', args=[]) boot = bootstrap.Bootstrap(conf) conf.drivers.transport = 'wsgi' app = boot.transport.app
Fix GitLab profile_url (html_url -> web_url)
# -*- coding: utf-8 -*- from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class GitLabAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('web_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url') def to_str(self): dflt = super(GitLabAccount, self).to_str() return self.account.extra_data.get('name', dflt) class GitLabProvider(OAuth2Provider): id = 'gitlab' name = 'GitLab' account_class = GitLabAccount def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('username'), name=data.get('name'), ) provider_classes = [GitLabProvider]
# -*- coding: utf-8 -*- from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class GitLabAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('html_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url') def to_str(self): dflt = super(GitLabAccount, self).to_str() return self.account.extra_data.get('name', dflt) class GitLabProvider(OAuth2Provider): id = 'gitlab' name = 'GitLab' account_class = GitLabAccount def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('username'), name=data.get('name'), ) provider_classes = [GitLabProvider]
Fix enable action on plugins
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.plugins import plugins from sentry.web.frontend.base import ProjectView class ProjectPluginEnableView(ProjectView): required_scope = 'project:write' def post(self, request, organization, team, project, slug): try: plugin = plugins.get(slug) except KeyError: return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug])) if plugin.is_enabled(project): return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug])) plugin.enable(project=project) return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.plugins import plugins from sentry.web.frontend.base import ProjectView class ProjectPluginEnableView(ProjectView): required_scope = 'project:write' def post(self, request, organization, team, project, slug): try: plugin = plugins.get(slug) except KeyError: return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug])) if not plugin.is_enabled(project): return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug])) plugin.enable(project=project) return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
Use new react root api
import { ApolloProvider } from "@apollo/client" import API from "api" import "bootstrap/dist/css/bootstrap.css" import { jumpToTop } from "components/Page" import "locale-compare-polyfill" import App from "pages/App" import React from "react" import { createRoot } from "react-dom/client" import { Provider } from "react-redux" import { BrowserRouter, Route } from "react-router-dom" import { persistStore } from "redux-persist" import { PersistGate } from "redux-persist/lib/integration/react" import "./bootstrapOverrides.css" import "./index.css" import configureStore from "./store/configureStore" const store = configureStore() const persistor = persistStore(store) window.onerror = function(message, url, lineNumber, columnNumber) { API.logOnServer("ERROR", url, lineNumber + ":" + columnNumber, message) return false } const root = createRoot(document.getElementById("root")) root.render( <Provider store={store}> <PersistGate persistor={persistor}> <ApolloProvider client={API.client}> <BrowserRouter onUpdate={jumpToTop}> <Route path="/" component={App} /> </BrowserRouter> </ApolloProvider> </PersistGate> </Provider> )
import { ApolloProvider } from "@apollo/client" import API from "api" import "bootstrap/dist/css/bootstrap.css" import { jumpToTop } from "components/Page" import "locale-compare-polyfill" import App from "pages/App" import React from "react" import ReactDOM from "react-dom" import { Provider } from "react-redux" import { BrowserRouter, Route } from "react-router-dom" import { persistStore } from "redux-persist" import { PersistGate } from "redux-persist/lib/integration/react" import "./bootstrapOverrides.css" import "./index.css" import configureStore from "./store/configureStore" const store = configureStore() const persistor = persistStore(store) window.onerror = function(message, url, lineNumber, columnNumber) { API.logOnServer("ERROR", url, lineNumber + ":" + columnNumber, message) return false } ReactDOM.render( <Provider store={store}> <PersistGate persistor={persistor}> <ApolloProvider client={API.client}> <BrowserRouter onUpdate={jumpToTop}> <Route path="/" component={App} /> </BrowserRouter> </ApolloProvider> </PersistGate> </Provider>, document.getElementById("root") )
Fix user documentation in Capturista.
from django.db import models from django.conf import settings from django.contrib.auth.models import Group from .utils import CAPTURISTA_GROUP class Capturista(models.Model): """ Extension of Django's User Model for Capturistas. We extend the Django User Model to identify Capturistas since they have relations with other models and close interaction with the API. Attributes: ---------- user : django.contrib.auth.models.User The django User related to Capturista (i.e. contains the actual user information). activo : BooleanField Indicates whether the profile is active or not. """ user = models.OneToOneField(settings.AUTH_USER_MODEL) activo = models.BooleanField(default=True) def save(self, *args, **kwargs): """ Override the save method to add the capturista group. """ user_group = Group.objects.get_or_create(name=CAPTURISTA_GROUP)[0] self.user.groups.add(user_group) return super(Capturista, self).save(*args, **kwargs)
from django.db import models from django.conf import settings from django.contrib.auth.models import Group from .utils import CAPTURISTA_GROUP class Capturista(models.Model): """ Extension of Django's User Model for Capturistas. We extend the Django User Model to identify Capturistas since they have relations with other models and close interaction with the API. Attributes: ---------- user : django.contrib.auth.models.User A mock user to use across all tests. activo : BooleanField Indicates whether the profile is active or not. """ user = models.OneToOneField(settings.AUTH_USER_MODEL) activo = models.BooleanField(default=True) def save(self, *args, **kwargs): """ Override the save method to add the capturista group. """ user_group = Group.objects.get_or_create(name=CAPTURISTA_GROUP)[0] self.user.groups.add(user_group) return super(Capturista, self).save(*args, **kwargs)
Fix PHPMD detection of excessive whitespaces
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\SamlBundle\Metadata; class MetadataConfiguration { /** * @var string */ public $entityIdRoute; /** * @var bool */ public $isSp; /** * @var string */ public $assertionConsumerRoute; /** * @var bool */ public $isIdP; /** * @var string */ public $ssoRoute; /** * @var string */ public $idpCertificate; /** * @var string */ public $publicKey; /** * @var string */ public $privateKey; }
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\SamlBundle\Metadata; class MetadataConfiguration { /** * @var string */ public $entityIdRoute; /** * @var bool */ public $isSp; /** * @var string */ public $assertionConsumerRoute; /** * @var bool */ public $isIdP; /** * @var string */ public $ssoRoute; /** * @var string */ public $idpCertificate; /** * @var string */ public $publicKey; /** * @var string */ public $privateKey; }
Handle unknown gene in dense matrix.
'use strict'; var multi = require('./multi'); var parsePos = require('./parsePos'); var fieldTypeSelector = x => x.fieldType; var columnFieldTypeSelector = x => x.column.fieldType; // XXX check for null field[0] is an odd artifact of denseMatrix transform which // overwrites fields with probes, if the server returns probes. If a gene is not // recognized, the probe list is empty. Needs a better semantics. var annotationSelector = ({fields, refGene}) => parsePos(fields[0] || '') ? 'chrom' : (refGene ? 'gene' : null); var widget = { cmp: multi(fieldTypeSelector), index: multi(x => x), transform: multi(fieldTypeSelector), avg: multi(fieldTypeSelector), download: multi(columnFieldTypeSelector), specialDownload: multi(columnFieldTypeSelector), column: multi(columnFieldTypeSelector), legend: multi(columnFieldTypeSelector), pdf: multi(fieldTypeSelector), annotation: multi(annotationSelector) }; widget.index.dflt = () => null; widget.avg.dflt = () => null; widget.annotation.dflt = () => null; module.exports = widget;
'use strict'; var multi = require('./multi'); var parsePos = require('./parsePos'); var fieldTypeSelector = x => x.fieldType; var columnFieldTypeSelector = x => x.column.fieldType; var annotationSelector = ({fields, refGene}) => parsePos(fields[0]) ? 'chrom' : (refGene ? 'gene' : null); var widget = { cmp: multi(fieldTypeSelector), index: multi(x => x), transform: multi(fieldTypeSelector), avg: multi(fieldTypeSelector), download: multi(columnFieldTypeSelector), specialDownload: multi(columnFieldTypeSelector), column: multi(columnFieldTypeSelector), legend: multi(columnFieldTypeSelector), pdf: multi(fieldTypeSelector), annotation: multi(annotationSelector) }; widget.index.dflt = () => null; widget.avg.dflt = () => null; widget.annotation.dflt = () => null; module.exports = widget;
Fix episode count increment bug
import abc import six @six.add_metaclass(abc.ABCMeta) class Learner(object): def __init__(self, env, n_episodes=1000, verbose=True): self.env = env self.n_episodes = n_episodes self.verbose = verbose self.cur_episode = 1 def learn(self): for _ in range(self.n_episodes): if self.verbose: print('Episode {self.cur_episode} / {self.n_episodes}'.format(self=self)) self.env.reset() self.episode() self.cur_episode += 1 def reset(self): self.cur_episode = 1 @abc.abstractmethod def episode(self): pass
import abc import six @six.add_metaclass(abc.ABCMeta) class Learner(object): def __init__(self, env, n_episodes=1000, verbose=True): self.env = env self.n_episodes = n_episodes self.verbose = verbose self.cur_episode = 1 def learn(self): for _ in range(self.n_episodes): if self.verbose: print('Episode {self.cur_episode} / {self.n_episodes}'.format(self=self)) self.env.reset() self.episode() self.cur_episode += 1 def reset(self): self.cur_episode = 1 @abc.abstractmethod def episode(self): pass
Fix constant to be static
package konstructs.api.messages; /** * GlobalConfig is a message that informs the plugin of the current values of * the global server config. These values are used by the server to manage * overall behaviour of plugins and is informal. */ public class GlobalConfig { public final static float DEFAULT_SIMULATION_SPEED = 1.0f; private final float simulationSpeed; /** * Construct an immutable GlobalConfig message * @param simulationSpeed The speed multiplier currently in use. 1.0 is normal speed. */ public GlobalConfig(float simulationSpeed) { this.simulationSpeed = simulationSpeed; } /** * Get the simulation speed multiplier currently in use. 1.0 is normal speed. * @return The simulation speed multiplier */ public float getSimulationSpeed() { return simulationSpeed; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GlobalConfig that = (GlobalConfig) o; return Float.compare(that.simulationSpeed, simulationSpeed) == 0; } @Override public int hashCode() { return (simulationSpeed != +0.0f ? Float.floatToIntBits(simulationSpeed) : 0); } @Override public String toString() { return "GlobalConfig(" + "simulationSpeed=" + simulationSpeed + ')'; } }
package konstructs.api.messages; /** * GlobalConfig is a message that informs the plugin of the current values of * the global server config. These values are used by the server to manage * overall behaviour of plugins and is informal. */ public class GlobalConfig { public final float DEFAULT_SIMULATION_SPEED = 1.0f; private final float simulationSpeed; /** * Construct an immutable GlobalConfig message * @param simulationSpeed The speed multiplier currently in use. 1.0 is normal speed. */ public GlobalConfig(float simulationSpeed) { this.simulationSpeed = simulationSpeed; } /** * Get the simulation speed multiplier currently in use. 1.0 is normal speed. * @return The simulation speed multiplier */ public float getSimulationSpeed() { return simulationSpeed; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GlobalConfig that = (GlobalConfig) o; return Float.compare(that.simulationSpeed, simulationSpeed) == 0; } @Override public int hashCode() { return (simulationSpeed != +0.0f ? Float.floatToIntBits(simulationSpeed) : 0); } @Override public String toString() { return "GlobalConfig(" + "simulationSpeed=" + simulationSpeed + ')'; } }
Fix styling issues for travis tests
'use strict'; var $ = require('jquery'); var Clipboard = require('clipboard'); var setTooltip = function (elm, message) { $(elm).tooltip('hide') .attr('title', message) .tooltip('show'); }; var hideTooltip = function (elm) { setTimeout(function() { $(elm).tooltip('hide'); }, 2000); }; var makeClient = function(elm) { var $elm = $(elm); var client = new Clipboard(elm); client.on('success', function(e){ setTooltip(e.trigger, 'Copied!'); hideTooltip(e.trigger); }); client.on('error', function(e){ setTooltip(e.trigger, 'Copy failed!'); hideTooltip(e.trigger); }); return client; }; module.exports = makeClient;
'use strict'; var $ = require('jquery'); var Clipboard = require('clipboard'); var setTooltip = function (elm, message) { $(elm).tooltip('hide') .attr('title', message) .tooltip('show'); } var hideTooltip = function (elm) { setTimeout(function() { $(elm).tooltip('hide'); }, 2000); } var makeClient = function(elm) { var $elm = $(elm); var client = new Clipboard(elm); client.on('success', function(e){ setTooltip(e.trigger, 'Copied!'); hideTooltip(e.trigger); }); client.on('error', function(e){ setTooltip(e.trigger, 'Copy failed!'); hideTooltip(e.trigger); }); return client; }; module.exports = makeClient;
Fix error when activating on empty editor
'use babel' import { dirname, basename } from 'path' function getPath (path) { let [projectPath, filePath] = atom.project.relativizePath(path) if (!projectPath) { projectPath = dirname(filePath) filePath = basename(filePath) } return { projectPath, filePath } } function getActiveFile () { let editor = atom.workspace.getActivePaneItem() if (editor) { if (editor.file) { return editor.file.path } else if (editor.buffer && editor.buffer.file) { return editor.buffer.file.path } } } function getUserConfig (projectPath) { try { return require(projectPath + '/bs-config.js') } catch(err) { return {} } } function onlineConfig (value) { switch (value) { case 0: return false break; case 1: return undefined break; case 2: return true break; } } export { getPath, getActiveFile, getUserConfig, onlineConfig }
'use babel' import { dirname, basename } from 'path' function getPath (path) { let [projectPath, filePath] = atom.project.relativizePath(path) if (!projectPath) { projectPath = dirname(filePath) filePath = basename(filePath) } return { projectPath, filePath } } function getActiveFile () { let editor = atom.workspace.getActivePaneItem() if (editor.file) { return editor.file.path } else if (editor.buffer && editor.buffer.file) { return editor.buffer.file.path } } function getUserConfig (projectPath) { try { return require(projectPath + '/bs-config.js') } catch(err) { return {} } } function onlineConfig (value) { switch (value) { case 0: return false break; case 1: return undefined break; case 2: return true break; } } export { getPath, getActiveFile, getUserConfig, onlineConfig }
Raise if response is not 200
import logging, email, yaml from django.utils import simplejson as json from google.appengine.ext import webapp, deferred from google.appengine.ext.webapp.mail_handlers import InboundMailHandler from google.appengine.api.urlfetch import fetch from google.appengine.api.urlfetch import Error as FetchError settings = yaml.load(open('settings.yaml')) def callback(raw): result = {'email': {'raw': raw}} response = fetch(settings['outbound_url'], payload=json.dumps(result), method="POST", headers={ 'Authorization': settings['api_key'], 'Content-Type': 'application/json' }, deadline=10 ) logging.info(response.status_code) if response.status_code != 200: raise FetchError() class InboundHandler(InboundMailHandler): def receive(self, message): logging.info("Received a message from: " + message.sender) deferred.defer(callback, message.original.as_string(True), _queue='inbound')
import logging, email, yaml from django.utils import simplejson as json from google.appengine.ext import webapp, deferred from google.appengine.ext.webapp.mail_handlers import InboundMailHandler from google.appengine.api.urlfetch import fetch settings = yaml.load(open('settings.yaml')) def callback(raw): result = {'email': {'raw': raw}} fetch(settings['outbound_url'], payload=json.dumps(result), method="POST", headers={ 'Authorization': settings['api_key'], 'Content-Type': 'application/json' } ) class InboundHandler(InboundMailHandler): def receive(self, message): logging.info("Received a message from: " + message.sender) deferred.defer(callback, message.original.as_string(True), _queue='inbound')
Add geo property to place type
<?php namespace JsonLd\ContextTypes; class Place extends Thing { /** * Property structure * * @var array */ protected $extendedStructure = [ 'address' => PostalAddress::class, 'review' => Review::class, 'aggregateRating' => AggregateRating::class, 'geo' => GeoCoordinates::class, ]; /** * Constructor. Merges extendedStructure up * * @param array $attributes * @param array $extendedStructure */ public function __construct(array $attributes, array $extendedStructure = []) { parent::__construct($attributes, array_merge($this->structure, $this->extendedStructure, $extendedStructure)); } }
<?php namespace JsonLd\ContextTypes; class Place extends Thing { /** * Property structure * * @var array */ protected $extendedStructure = [ 'address' => PostalAddress::class, 'review' => Review::class, 'aggregateRating' => AggregateRating::class, ]; /** * Constructor. Merges extendedStructure up * * @param array $attributes * @param array $extendedStructure */ public function __construct(array $attributes, array $extendedStructure = []) { parent::__construct($attributes, array_merge($this->structure, $this->extendedStructure, $extendedStructure)); } }
Insert a space when displaying the repositories
package ch.cern.cvmfs.model; public class RepositoryDescription { private String name; private String fqrn; private String url; public RepositoryDescription(String name, String fqrn, String url) { this.name = name; this.fqrn = fqrn; this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFqrn() { return fqrn; } public void setFqrn(String fqrn) { this.fqrn = fqrn; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return name + " (" + fqrn + ")"; } }
package ch.cern.cvmfs.model; public class RepositoryDescription { private String name; private String fqrn; private String url; public RepositoryDescription(String name, String fqrn, String url) { this.name = name; this.fqrn = fqrn; this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFqrn() { return fqrn; } public void setFqrn(String fqrn) { this.fqrn = fqrn; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return name + "(" + fqrn + ")"; } }
Remove test code. Ready for prod
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventValue: 1 }); }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventValue: 0 }); });
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'Feedback testing from chris - yes response', eventValue: 1 }); console.log('Yes: ' + window.location.href) }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'Feedback testing from chris - no response', eventValue: 0 }); console.log('No: ' + window.location.href) });
Fix the content-type check in the webservice
'use strict'; var joblint = require('joblint'); module.exports = defineController; function defineController (app) { app.all('/ws', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); app.post('/ws', requireUrlEncodedPostBody, requireUnemptyJobSpec, function (req, res) { res.jsonp(joblint(req.body.spec)); }); app.all('/ws', function (req, res) { return res.jsonp(405, { error: 'Method not allowed, POST request expected' }); }); } function requireUrlEncodedPostBody (req, res, next) { if (!req.is('application/x-www-form-urlencoded')) { return res.jsonp(400, { error: 'Request must have a content-type of "application/x-www-form-urlencoded"' }); } next(); } function requireUnemptyJobSpec (req, res, next) { if (!req.body.spec || !req.body.spec.trim()) { return res.jsonp(400, { error: 'Spec must be a non-empty string' }); } next(); }
'use strict'; var joblint = require('joblint'); module.exports = defineController; function defineController (app) { app.all('/ws', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); app.post('/ws', requireUrlEncodedPostBody, requireUnemptyJobSpec, function (req, res) { res.jsonp(joblint(req.body.spec)); }); app.all('/ws', function (req, res) { return res.jsonp(405, { error: 'Method not allowed, POST request expected' }); }); } function requireUrlEncodedPostBody (req, res, next) { if (req.headers['content-type'] !== 'application/x-www-form-urlencoded') { return res.jsonp(400, { error: 'Request must have a content-type of "application/x-www-form-urlencoded"' }); } next(); } function requireUnemptyJobSpec (req, res, next) { if (!req.body.spec || !req.body.spec.trim()) { return res.jsonp(400, { error: 'Spec must be a non-empty string' }); } next(); }
Update dashboard description to show that only the most recent articles are synced.
@extends('layouts.master') @section('content') <section class="main-inner"> <h2>Dashboard</h2> <div class="subscribe"> <a class="button subscribe-button" href="{{ str_replace('http://', 'itpc://', route('podcast', array('id' => $user->id, 'secret' => $user->secret()))) }}">Subscribe with iTunes</a> <a class="subscribe-link" href="{{ route('podcast', array('id' => $user->id, 'secret' => $user->secret())) }}">Subscribe with RSS</a> </div> <p>Most recent 20 unread articles are automatically fetched, convert to podcast episodes and added to your feed every hour.</p> <p>Once you've listened to them, you'll need to manually mark them as read in <a href="http://getpocket.com">Pocket</a>.</p> @if (count($items) > 0) <h3>Articles</h3> <p>These articles are currently in your feed.</p> @include('partials.items', array('items' => $items)) <p><a class="button" href="{{ route('pocket.synchronise') }}">Update</a></p> @else <p><a class="button" href="{{ route('pocket.synchronise') }}">Get pocket articles</a></p> @endif </section> @endsection
@extends('layouts.master') @section('content') <section class="main-inner"> <h2>Dashboard</h2> <div class="subscribe"> <a class="button subscribe-button" href="{{ str_replace('http://', 'itpc://', route('podcast', array('id' => $user->id, 'secret' => $user->secret()))) }}">Subscribe with iTunes</a> <a class="subscribe-link" href="{{ route('podcast', array('id' => $user->id, 'secret' => $user->secret())) }}">Subscribe with RSS</a> </div> <p>Articles are automatically fetched, convert to podcast episodes and added to your feed every hour.</p> <p>Once you've listened to them, you'll need to manually mark them as read in <a href="http://getpocket.com">Pocket</a>.</p> @if (count($items) > 0) <h3>Articles</h3> <p>These articles are currently in your feed.</p> @include('partials.items', array('items' => $items)) <p><a class="button" href="{{ route('pocket.synchronise') }}">Update</a></p> @else <p><a class="button" href="{{ route('pocket.synchronise') }}">Get pocket articles</a></p> @endif </section> @endsection
Add a method to get the biggest block id Necessary to set the number of bits per block used in the ChunkSection implementation, and in the ChunkData packet.
package org.mcphoton.impl.block; import com.electronwill.utils.IndexMap; import java.util.HashMap; import java.util.Map; import org.mcphoton.block.BlockRegistry; import org.mcphoton.block.BlockType; /** * * @author TheElectronWill */ public class PhotonBlockRegistry implements BlockRegistry { private final IndexMap<BlockType> idMap = new IndexMap<>(); private final Map<String, BlockType> nameMap = new HashMap<>(); @Override public synchronized void register(BlockType type) { int id = idMap.size(); type.initializeId(id); idMap.put(id, type); nameMap.put(type.getUniqueName(), type); } @Override public synchronized void register(BlockType type, int id) { type.initializeId(id); idMap.put(id, type); nameMap.put(type.getUniqueName(), type); } @Override public synchronized BlockType getRegistered(int id) { return idMap.get(id); } @Override public synchronized BlockType getRegistered(String name) { return nameMap.get(name); } @Override public synchronized boolean isRegistered(int id) { return idMap.containsKey(id); } @Override public synchronized boolean isRegistered(String name) { return nameMap.containsKey(name); } public int getBiggestBlockId() { return Math.max(0, idMap.array().length - 1); } }
package org.mcphoton.impl.block; import com.electronwill.utils.IndexMap; import java.util.HashMap; import java.util.Map; import org.mcphoton.block.BlockRegistry; import org.mcphoton.block.BlockType; /** * * @author TheElectronWill */ public class PhotonBlockRegistry implements BlockRegistry { private final IndexMap<BlockType> idMap = new IndexMap<>(); private final Map<String, BlockType> nameMap = new HashMap<>(); @Override public synchronized void register(BlockType type) { int id = idMap.size(); type.initializeId(id); idMap.put(id, type); nameMap.put(type.getUniqueName(), type); } @Override public synchronized void register(BlockType type, int id) { type.initializeId(id); idMap.put(id, type); nameMap.put(type.getUniqueName(), type); } @Override public synchronized BlockType getRegistered(int id) { return idMap.get(id); } @Override public synchronized BlockType getRegistered(String name) { return nameMap.get(name); } @Override public synchronized boolean isRegistered(int id) { return idMap.containsKey(id); } @Override public synchronized boolean isRegistered(String name) { return nameMap.containsKey(name); } }
Increment version number in tarball
from setuptools import setup setup( name='runcalc', version='0.1.1', description='Running pace calculator', author='Mike Patek', author_email='mpatek@gmail.com', url='https://github.com/mpatek/runcalc', download_url='https://github.com/mpatek/runcalc/tarball/0.1.1', packages=['runcalc'], include_package_data=True, entry_points={ 'console_scripts': [ 'runcalc=runcalc.cli:cli' ] }, install_requires=['click'], setup_requires=['pytest-runner'], tests_require=['pytest'], keywords=['running', 'exercise', 'cli'], )
from setuptools import setup setup( name='runcalc', version='0.1.1', description='Running pace calculator', author='Mike Patek', author_email='mpatek@gmail.com', url='https://github.com/mpatek/runcalc', download_url='https://github.com/mpatek/runcalc/tarball/0.1', packages=['runcalc'], include_package_data=True, entry_points={ 'console_scripts': [ 'runcalc=runcalc.cli:cli' ] }, install_requires=['click'], setup_requires=['pytest-runner'], tests_require=['pytest'], keywords=['running', 'exercise', 'cli'], )
Replace line endings to lf and add default param as empty string for `handlerName`
import forEach from 'lodash/collection/forEach'; import isEmpty from 'lodash/lang/isEmpty'; import isFunction from 'lodash/lang/isFunction'; import snakeCase from 'lodash/string/snakeCase'; import { Store, toImmutable } from 'nuclear-js'; export default function createStore(initialState, handlers) { const immutableState = toImmutable(initialState); const spec = { getInitialState() { return immutableState; }, initialize() { if (!isEmpty(handlers)) { forEach(handlers, (handler, handlerName = '') => { const ACTION_NAME = snakeCase(handlerName).toUpperCase(); if (!ACTION_NAME) { throw new Error('Frux#createStore: handler must be a named function.'); } if (isFunction(handler)) { this.on(ACTION_NAME, (currentState, payload) => { return handler.call(null, currentState, payload, immutableState); }); } }); } } }; return new Store(spec); }
import forEach from 'lodash/collection/forEach'; import isEmpty from 'lodash/lang/isEmpty'; import isFunction from 'lodash/lang/isFunction'; import snakeCase from 'lodash/string/snakeCase'; import { Store, toImmutable } from 'nuclear-js'; export default function createStore(initialState, handlers) { const immutableState = toImmutable(initialState); const spec = { getInitialState() { return immutableState; }, initialize() { if (!isEmpty(handlers)) { forEach(handlers, (handler, handlerName) => { const ACTION_NAME = snakeCase(handlerName || '').toUpperCase(); if (!ACTION_NAME) { throw new Error('Frux#createStore: handler must be a named function.'); } if (isFunction(handler)) { this.on(ACTION_NAME, (currentState, payload) => { return handler.call(null, currentState, payload, immutableState); }); } }); } } }; return new Store(spec); }
Add console logging upon haiku trigger
const Discord = require('discord.js'); const { ChannelProcessor } = require('./channelProcessor'); const {discordApiToken } = require('./secrets.js'); const client = new Discord.Client(); const channelProcessorMap = {}; client.on('ready', () => { console.log('Bot is ready'); }); client.on('message', (message) => { const channel = message.channel; const channelID = message.channel.id; if(channelProcessorMap[channelID] == null) { const newChannelProcessor = new ChannelProcessor(channelID); newChannelProcessor.setOnHaikuFunction((haiku) => { console.log( `Haiku triggered: author: ${haiku.author} lines: ${haiku.lines}`); channel.send( `${haiku.author} has created a beautiful Haiku! ${haiku.lines[0]} ${haiku.lines[1]} ${haiku.lines[2]}`); }); channelProcessorMap[channelID] = newChannelProcessor; } channelProcessorMap[channelID].processMessage(message); }); client.login(discordApiToken);
const Discord = require('discord.js'); const { ChannelProcessor } = require('./channelProcessor'); const {discordApiToken } = require('./secrets.js'); const client = new Discord.Client(); const channelProcessorMap = {}; client.on('ready', () => { console.log('Bot is ready'); }); client.on('message', (message) => { const channel = message.channel; const channelID = message.channel.id; if(channelProcessorMap[channelID] == null) { const newChannelProcessor = new ChannelProcessor(channelID); newChannelProcessor.setOnHaikuFunction((haiku) => { channel.send( `${haiku.author} has created a beautiful Haiku! ${haiku.lines[0]} ${haiku.lines[1]} ${haiku.lines[2]}`); }); channelProcessorMap[channelID] = newChannelProcessor; } channelProcessorMap[channelID].processMessage(message); }); client.login(discordApiToken);
Change verbage on program profile info. Fixes issue 1601.
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange 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. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Organizations Review Student Applications Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Students Matched to Mentors Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange 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. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Application Review Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Student Application Matched Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
[FLINK-8022][kafka-tests] Disable at-least-once tests for Kafka 0.9 For some reasons this test is sometimes failing in Kafka09 while the same code works in Kafka010. Disabling this test because everything indicates those failures might be caused by unfixed bugs in Kafka 0.9 branch This closes #5316.
/* * 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.flink.streaming.connectors.kafka; /** * IT cases for the {@link FlinkKafkaProducer09}. */ @SuppressWarnings("serial") public class Kafka09ProducerITCase extends KafkaProducerTestBase { @Override public void testExactlyOnceRegularSink() throws Exception { // Kafka09 does not support exactly once semantic } @Override public void testExactlyOnceCustomOperator() throws Exception { // Kafka09 does not support exactly once semantic } @Override public void testOneToOneAtLeastOnceRegularSink() throws Exception { // For some reasons this test is sometimes failing in Kafka09 while the same code works in Kafka010. Disabling // this test because everything indicates those failures might be caused by unfixed bugs in Kafka 0.9 branch } @Override public void testOneToOneAtLeastOnceCustomOperator() throws Exception { // Disable this test since FlinkKafka09Producer doesn't support custom operator mode } }
/* * 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.flink.streaming.connectors.kafka; /** * IT cases for the {@link FlinkKafkaProducer09}. */ @SuppressWarnings("serial") public class Kafka09ProducerITCase extends KafkaProducerTestBase { @Override public void testExactlyOnceRegularSink() throws Exception { // Kafka08 does not support exactly once semantic } @Override public void testExactlyOnceCustomOperator() throws Exception { // Kafka08 does not support exactly once semantic } @Override public void testOneToOneAtLeastOnceCustomOperator() throws Exception { // Disable this test since FlinkKafka09Producer doesn't support custom operator mode } }
Fix a STUPID issue with the forum seeder
<?php use Illuminate\Database\Seeder; class ForumSeeder extends Seeder { public function run() { $faker = Faker\Factory::create(); for ($t = 1; $t <= 10; $t++) { factory('App\Data\Topic')->create(); } for ($d = 1; $d <= 50; $d++) { $discussion = factory('App\Data\Discussion')->create([ 'user_id' => $faker->numberBetween(1, 100), 'topic_id' => $faker->numberBetween(1, 10), ]); for ($r = 0; $r <= $faker->numberBetween(0, 10); $r++) { factory('App\Data\Reply')->create([ 'discussion_id' => $discussion->id, 'user_id' => $faker->numberBetween(1, 100), ]); } } } }
<?php use Illuminate\Database\Seeder; class ForumSeeder extends Seeder { public function run() { $faker = Faker\Factory::create(); for ($t = 1; $t <= 10; $t++) { factory('App\Data\Topic')->create(); } for ($d = 1; $d <= 50; $d++) { $discussion = factory('App\Data\Discussion')->create([ 'user_id' => $faker->numberBetween(1, 102), 'topic_id' => $faker->numberBetween(1, 10), ]); for ($r = 0; $r <= $faker->numberBetween(0, 10); $r++) { factory('App\Data\Reply')->create([ 'discussion_id' => $discussion->id, 'user_id' => $faker->numberBetween(1, 102), ]); } } } }
Fix random module's help message
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds %s random tracks to the queue" % self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10))
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds 10 random tracks to the queue")
Set default output to root
import java.io.File; /** * Each instance of this class represents a You-Get process. * * @author Zhen Chen * */ public class YouGet implements Downloader { private static final String LOCATION = "E:/软件/You-Get/"; private static String executable; private String outputPath; private String outputFilename; public static final void setExecutable() throws NoExecutableFileFoundException { try { executable = Helper.getFirstExecutablePath(LOCATION); } catch (NoExecutableFileFoundException e) { throw new NoExecutableFileFoundException("No YouGet program found in the given path: " + LOCATION, e); } } /** * Set the default output path to the root. */ YouGet() { this.outputPath = "/"; } YouGet(String outputPath) { this.outputPath = outputPath; } public static final String getLocation() { return LOCATION; } public static final String getExecutable() { return executable; } public void download() { // TODO } }
import java.io.File; /** * Each instance of this class represents a You-Get process. * * @author Zhen Chen * */ public class YouGet implements Downloader { private static final String LOCATION = "E:/软件/You-Get/"; private static String executable; private String outputPath; private String outputFilename; public static final void setExecutable() throws NoExecutableFileFoundException { try { executable = Helper.getFirstExecutablePath(LOCATION); } catch (NoExecutableFileFoundException e) { throw new NoExecutableFileFoundException("No YouGet program found in the given path: " + LOCATION, e); } } YouGet() { } YouGet(String outputPath) { this.outputPath = outputPath; } public static final String getLocation() { return LOCATION; } public static final String getExecutable() { return executable; } public void download() { // TODO } }
Put main bot setup code inside main function
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() def main(): args = parse_arguments() bot_info = config.bots[args.botname] client_id = bot_info['client_id'] token = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( client_id, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(token) if __name__ == '__main__': main()
import argparse import discord from discord.ext import commands import config from cmd import general, emotes _DESCRIPTION = '''quack''' def parse_arguments(): parser = argparse.ArgumentParser(description="quack") parser.add_argument('-b', '--botname', required=True, choices=config.bots.keys(), help="Name of bot in config file") return parser.parse_args() args = parse_arguments() bot_info = config.bots[args.botname] CLIENT_ID = bot_info['client_id'] TOKEN = bot_info['token'] bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) # Register commands to bot general.register(bot) emotes.register(bot) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url( CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) bot.run(TOKEN)
Allow the SASL credentials provider to provide extra configuration Some mechanisms might require external configuration data so we should provide an optional API to allow that to be gathered from a mechanism.
/* * 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.qpid.proton4j.engine.sasl.client; import java.security.Principal; import java.util.Collections; import java.util.Map; /** * Interface for a supplier of login credentials used by the SASL Authenticator to * select and configure the client SASL mechanism. */ public interface SaslCredentialsProvider { String vhost(); String username(); String password(); Principal localPrincipal(); @SuppressWarnings("unchecked") default Map<String, Object> options() { return Collections.EMPTY_MAP; } }
/* * 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.qpid.proton4j.engine.sasl.client; import java.security.Principal; /** * Interface for a supplier of login credentials used by the SASL Authenticator to * select and configure the client SASL mechanism. */ public interface SaslCredentialsProvider { String vhost(); String username(); String password(); Principal localPrincipal(); }
Update expected http status code in test
from .initial_data import users from yunity.utils.tests.comparison import DeepMatcher response = { "http_status": 200, "response": { "participants": [users[0].id, users[1].id, users[2].id], "name": "New funny name", "message": { "content": "Hello user 1", "sender": users[0].id, "created_at": DeepMatcher.DATETIME_AROUND_NOW, "id": "AnyInt", "type": "TEXT" }, "id": "AnyInt" } }
from .initial_data import users from yunity.utils.tests.comparison import DeepMatcher response = { "http_status": 201, "response": { "participants": [users[0].id, users[1].id, users[2].id], "name": "New funny name", "message": { "content": "Hello user 1", "sender": users[0].id, "created_at": DeepMatcher.DATETIME_AROUND_NOW, "id": "AnyInt", "type": "TEXT" }, "id": "AnyInt" } }
Debug Google Cloud Run support
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask app = Flask(__name__) # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
Change mention of client to browser to match src structure
import Buttons from './Buttons.react'; import Component from 'react-pure-render/component'; import DocumentTitle from 'react-document-title'; import List from './List.react'; import NewTodo from './NewTodo.react'; import React, {PropTypes} from 'react'; import fetch from '../../common/components/fetch'; import {fetchUserTodos} from '../../common/todos/actions'; // This decorator (higher order component) fetches todos both in browser and // on server side. It's true isomorphic data fetching and rendering. @fetch(fetchUserTodos) export default class Page extends Component { static propTypes = { actions: PropTypes.object, msg: PropTypes.object, todos: PropTypes.object } render() { const {actions, msg: {todos: msg}, todos: {newTodo, list}} = this.props; return ( <DocumentTitle title={msg.title}> <div className="todos-page"> <NewTodo {...{actions, msg, newTodo}} /> <List {...{actions, list, msg}} /> <Buttons clearAllEnabled={list.size > 0} {...{actions, msg}} /> </div> </DocumentTitle> ); } }
import Buttons from './Buttons.react'; import Component from 'react-pure-render/component'; import DocumentTitle from 'react-document-title'; import List from './List.react'; import NewTodo from './NewTodo.react'; import React, {PropTypes} from 'react'; import fetch from '../../common/components/fetch'; import {fetchUserTodos} from '../../common/todos/actions'; // This decorator (higher order component) fetches todos both on client and // server side. It's true isomorphic data fetching and rendering. @fetch(fetchUserTodos) export default class Page extends Component { static propTypes = { actions: PropTypes.object, msg: PropTypes.object, todos: PropTypes.object } render() { const {actions, msg: {todos: msg}, todos: {newTodo, list}} = this.props; return ( <DocumentTitle title={msg.title}> <div className="todos-page"> <NewTodo {...{actions, msg, newTodo}} /> <List {...{actions, list, msg}} /> <Buttons clearAllEnabled={list.size > 0} {...{actions, msg}} /> </div> </DocumentTitle> ); } }
Add more info to the AuthController
'use strict'; var authController = {}; var UserCollection = require('../models').collections.UserCollection; var User = require('../models').models.User; authController.getUser = function (req, res) { var userId = null; if (req.user && req.user.get('id') && typeof req.user.get('id') === 'number') { userId = req.user.get('id'); } res.json({ userId: userId, userName: req.user.get('username'), email: req.user.get('email'), }); }; authController.logout = function (req, res) { res.logout(); res.status(200).end(); }; authController.login = function (req, res) { res.redirect('/#/home'); }; authController.signup = function (req, res) { var email = req.body.email || req.param('email'); var password = req.body.password || req.param('password'); if (!email || !password) { res.status(400).end(); // Client Error return; } new UserCollection() .query('where', 'email', '=', email) .fetchOne() .then(function (user) { if (user !== null) { res.redirect('/#/home'); return; } new User({ email: email, password: password }).save() .then(function () { res.redirect('/#/home'); }); }); }; module.exports = authController;
var authController = {}; var UserCollection = require('../models').collections.UserCollection; var User = require('../models').models.User; authController.getUser = function (req, res) { var userId = null; if (req.user && req.user.get('id') && typeof req.user.get('id') === 'number') { userId = req.user.get('id'); } res.json({ userId: userId, }); }; authController.logout = function (req, res) { res.logout(); res.status(200).end(); }; authController.login = function (req, res) { res.redirect('/#/home'); }; authController.signup = function (req, res) { var email = req.body.email || req.param('email'); var password = req.body.password || req.param('password'); if (!email || !password) { res.status(400).end(); // Client Error return; } new UserCollection() .query('where', 'email', '=', email) .fetchOne() .then(function (user) { if (user !== null) { res.redirect('/#/home'); return; } var user = new User({ email: email, password: password }).save() .then(function (userModel) { res.redirect('/#/home'); }); }); }; module.exports = authController;
Add badge text to signify that livereload is on
// State, contains tabs which have livereloading enabled. let enabledTabs = [] const toolbarButtonHandler = tab => { enabledTabs.push(tab) browser.browserAction.setBadgeText({ text: "ON", tabId: tab.id }) browser.browserAction.setBadgeBackgroundColor({ color: "#1496bb", tabId: tab.id }) return browser.tabs.executeScript(tab.id, { file: 'livereload-script-tag-injector.js' }) } const tabRemovedHandler = id => { const newState = enabledTabs.filter(et => et.id !== id) enabledTabs = newState } const tabChangedHandler = (id, changedInfo) => { const et = enabledTabs.find(et => et.id === id) if (!et || changedInfo.status === 'loading') { return } browser.tabs.executeScript(et.id, { file: 'livereload-script-tag-injector.js' }) } browser.browserAction.onClicked.addListener(toolbarButtonHandler) browser.tabs.onRemoved.addListener(tabRemovedHandler) browser.tabs.onUpdated.addListener(tabChangedHandler)
// State, contains tabs which have livereloading enabled. let enabledTabs = [] const toolbarButtonHandler = tab => { enabledTabs.push(tab) browser.tabs.executeScript(tab.id, { file: 'livereload-script-tag-injector.js' }) } const tabRemovedHandler = id => { const newState = enabledTabs.filter(et => et.id !== id) enabledTabs = newState } const tabChangedHandler = (id, changedInfo) => { const et = enabledTabs.find(et => et.id === id) if (!et || changedInfo.status === 'loading') { return } browser.tabs.executeScript(et.id, { file: 'livereload-script-tag-injector.js' }) } browser.browserAction.onClicked.addListener(toolbarButtonHandler) browser.tabs.onRemoved.addListener(tabRemovedHandler) browser.tabs.onUpdated.addListener(tabChangedHandler)
Modify encoding for open README to prevent ascii errors
#!/usr/bin/env python3 from setuptools import setup, find_packages with open("README.md", encoding='utf8') as fh: long_description = fh.read() setup( name='malwareconfig', version='1.0.3', author='Kevin Breen', author_email='thehermit@malwareconfig.com', description="Malware Config Extraction", long_description=long_description, long_description_content_type="text/markdown", url='https://malwareconfig.com', license='GNU V3', zip_safe=False, packages=find_packages(), include_package_data=True, install_requires=[ 'pefile', 'pbkdf2', 'javaobj-py3', 'pycrypto', 'androguard' ], scripts=['malconf'], package_data={'': ['*.yar', 'README.md, LICENSE']} )
#!/usr/bin/env python from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='malwareconfig', version='1.0.3', author='Kevin Breen', author_email='thehermit@malwareconfig.com', description="Malware Config Extraction", long_description=long_description, long_description_content_type="text/markdown", url='https://malwareconfig.com', license='GNU V3', zip_safe=False, packages=find_packages(), include_package_data=True, install_requires=[ 'pefile', 'pbkdf2', 'javaobj-py3', 'pycrypto', 'androguard' ], scripts=['malconf'], package_data={'': ['*.yar', 'README.md, LICENSE']} )
Add a bit of logging
/* eslint-env mocha */ const assert = require('assert') const cm = require('cucumber-messages').io.cucumber.messages const Gherkin = require('../src/Gherkin') describe('Gherkin', () => { it('parses gherkin from the file system', async () => { const messages = await streamToArray( Gherkin.fromPaths(['testdata/good/minimal.feature']) ) assert.strictEqual(messages.length, 3) }) it('parses gherkin from STDIN', async () => { const source = cm.Source.fromObject({ uri: 'test.feature', data: `Feature: Minimal Scenario: minimalistic Given the minimalism `, media: cm.Media.fromObject({ encoding: 'UTF-8', contentType: 'text/x.cucumber.gherkin+plain', }), }) const messages = await streamToArray(Gherkin.fromSources([source])) console.log('Messages', messages) assert.strictEqual(messages.length, 3) }) }) function streamToArray(readableStream) { return new Promise((resolve, reject) => { const items = [] readableStream.on('data', items.push.bind(items)) readableStream.on('error', reject) readableStream.on('end', () => resolve(items)) }) }
/* eslint-env mocha */ const assert = require('assert') const cm = require('cucumber-messages').io.cucumber.messages const Gherkin = require('../src/Gherkin') describe('Gherkin', () => { it('parses gherkin from the file system', async () => { const messages = await streamToArray( Gherkin.fromPaths(['testdata/good/minimal.feature']) ) assert.strictEqual(messages.length, 3) }) it('parses gherkin from STDIN', async () => { const source = cm.Source.fromObject({ uri: 'test.feature', data: `Feature: Minimal Scenario: minimalistic Given the minimalism `, media: cm.Media.fromObject({ encoding: 'UTF-8', contentType: 'text/x.cucumber.gherkin+plain', }), }) const messages = await streamToArray(Gherkin.fromSources([source])) assert.strictEqual(messages.length, 3) }) }) function streamToArray(readableStream) { return new Promise((resolve, reject) => { const items = [] readableStream.on('data', items.push.bind(items)) readableStream.on('error', reject) readableStream.on('end', () => resolve(items)) }) }
Remove unneeded list creation to add single item
package com.github.mobile.android; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.util.Log; import com.google.inject.Module; import java.util.List; /** * Main GitHub application */ public class GitHubApplication extends Application { private static final String TAG = "GHA"; /** * Create main application */ public GitHubApplication() { } /** * Create main application * * @param context */ public GitHubApplication(Context context) { attachBaseContext(context); } /** * Create main application * * @param instrumentation */ public GitHubApplication(Instrumentation instrumentation) { attachBaseContext(instrumentation.getTargetContext()); } /** * Add modules * * @param modules */ protected void addApplicationModules(List<Module> modules) { Log.d(TAG, "Adding application modules..."); modules.add(new GitHubModule()); } }
package com.github.mobile.android; import static java.util.Arrays.asList; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.util.Log; import com.google.inject.Module; import java.util.List; /** * Main GitHub application */ public class GitHubApplication extends Application { private static final String TAG = "GHA"; /** * Create main application */ public GitHubApplication() { } /** * Create main application * * @param context */ public GitHubApplication(Context context) { attachBaseContext(context); } /** * Create main application * * @param instrumentation */ public GitHubApplication(Instrumentation instrumentation) { attachBaseContext(instrumentation.getTargetContext()); } protected void addApplicationModules(List<Module> modules) { Log.i(TAG, "Adding application modules..."); modules.addAll(asList(new GitHubModule())); } }
Fix StringStream to conform to latest pypy Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, size): raise StreamError("StringStream is immutable") def tell(self): return self.pos def seek(self, offset, whence): if whence == 0: self.pos = max(0, offset) elif whence == 1: self.pos = max(0, self.pos + offset) elif whence == 2: self.pos = max(0, self.max + offset) else: raise StreamError("seek(): whence must be 0, 1 or 2") def read(self, n): assert isinstance(n, int) end = self.pos + n assert end >= 0 data = self._string[self.pos:end] self.pos += len(data) return data
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, size): raise StreamError("StringStream is immutable") def peek(self): if self.pos < self.max: return self._string[self.pos:] else: return '' def tell(self): return self.pos def seek(self, offset, whence): if whence == 0: self.pos = max(0, offset) elif whence == 1: self.pos = max(0, self.pos + offset) elif whence == 2: self.pos = max(0, self.max + offset) else: raise StreamError("seek(): whence must be 0, 1 or 2") def read(self, n): assert isinstance(n, int) end = self.pos + n data = self._string[self.pos:end] self.pos += len(data) return data
Fix fs.exists to existsSync where necessary
var fs = require("fs"); var path = require("path"); var Helper = module.exports = { getConfig: function () { var filename = process.env.SHOUT_CONFIG; if(!filename || !fs.existsSync(filename)) { filename = this.resolveHomePath("config.js"); if(!fs.existsSync(filename)) { filename = path.resolve(__dirname, "..", "config"); } } return require(filename); }, getHomeDirectory: function () { return ( (process.env.SHOUT_CONFIG && fs.existsSync(process.env.SHOUT_CONFIG) && this.getConfig().home) || process.env.SHOUT_HOME || path.resolve(process.env.HOME, ".shout") ); }, resolveHomePath: function () { var fragments = [ Helper.HOME ].concat([].slice.apply(arguments)); return path.resolve.apply(path, fragments); } }; Helper.HOME = Helper.getHomeDirectory()
var fs = require("fs"); var path = require("path"); var Helper = module.exports = { getConfig: function () { var filename = process.env.SHOUT_CONFIG; if(!filename || !fs.exists(filename)) { filename = this.resolveHomePath("config.js"); if(!fs.exists(filename)) { filename = path.resolve(__dirname, "..", "config"); } } return require(filename); }, getHomeDirectory: function () { return ( (process.env.SHOUT_CONFIG && fs.exists(process.env.SHOUT_CONFIG) && this.getConfig().home) || process.env.SHOUT_HOME || path.resolve(process.env.HOME, ".shout") ); }, resolveHomePath: function () { var fragments = [ Helper.HOME ].concat([].slice.apply(arguments)); return path.resolve.apply(path, fragments); } }; Helper.HOME = Helper.getHomeDirectory()
Use HostAddressOpt for opts that accept IP and hostnames Some configuration options were accepting both IP addresses and hostnames. Since there was no specific OSLO opt type to support this, we were using ``StrOpt``. The change [1] that added support for ``HostAddressOpt`` type was merged in Ocata and became available for use with oslo version 3.22. This patch changes the opt type of configuration options to use this more relevant opt type - HostAddressOpt. [1] I77bdb64b7e6e56ce761d76696bc4448a9bd325eb Change-Id: Id179ad55d4344a7dc2214896290890862b560e0c
# Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_config import cfg from magnum.i18n import _ service_opts = [ cfg.HostAddressOpt('host', help=_('Name of this node. This can be an opaque ' 'identifier. It is not necessarily a hostname, ' 'FQDN, or IP address. However, the node name ' 'must be valid within an AMQP key, and if using ' 'ZeroMQ, a valid hostname, FQDN, or IP ' 'address.')), ] def register_opts(conf): conf.register_opts(service_opts) def list_opts(): return { "DEFAULT": service_opts }
# Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_config import cfg from magnum.i18n import _ service_opts = [ cfg.StrOpt('host', help=_('Name of this node. This can be an opaque identifier. ' 'It is not necessarily a hostname, FQDN, or IP address. ' 'However, the node name must be valid within ' 'an AMQP key, and if using ZeroMQ, a valid ' 'hostname, FQDN, or IP address.')), ] def register_opts(conf): conf.register_opts(service_opts) def list_opts(): return { "DEFAULT": service_opts }
Add return types to tests and final|internal|private methods
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ExpressionLanguage\Tests\Fixtures; use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; use Symfony\Component\ExpressionLanguage\ExpressionPhpFunction; class TestProvider implements ExpressionFunctionProviderInterface { public function getFunctions(): array { return [ new ExpressionFunction('identity', function ($input) { return $input; }, function (array $values, $input) { return $input; }), ExpressionFunction::fromPhp('strtoupper'), ExpressionFunction::fromPhp('\strtolower'), ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\Fixtures\fn_namespaced', 'fn_namespaced'), ]; } } function fn_namespaced() { return true; }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\ExpressionLanguage\Tests\Fixtures; use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; use Symfony\Component\ExpressionLanguage\ExpressionPhpFunction; class TestProvider implements ExpressionFunctionProviderInterface { public function getFunctions() { return [ new ExpressionFunction('identity', function ($input) { return $input; }, function (array $values, $input) { return $input; }), ExpressionFunction::fromPhp('strtoupper'), ExpressionFunction::fromPhp('\strtolower'), ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\Fixtures\fn_namespaced', 'fn_namespaced'), ]; } } function fn_namespaced() { return true; }
Trim whitespace and remove \n from item name. Newlines in item name complicate formatting. Replace them with spaces.
import _request from 'request-promise' import cheerio from 'cheerio' const jar = _request.jar() const request = _request.defaults({ headers: {'Content-Type': 'application/json'}, jar, }) const SCV='https://www.alza.sk/Services/EShopService.svc/' export function* login(credentials) { return yield request.post(`${SCV}LoginUser`, {body: JSON.stringify(credentials)}) } export function* addToCart({url, count}) { const id = url.match(/(d|dq=)(\d*)(\.htm)?$/)[2] return yield request.post(`${SCV}OrderCommodity`, {body: JSON.stringify( {id, count} )}) } export function* getInfo(url) { const $ = cheerio.load(yield request(url)) const name = $('h1[itemprop="name"]').text().trim().replace(/\s+/g, ' ') const price = parseFloat( $('span.price_withoutVat').text() .replace(/[^\d,]/g, '') .replace(/,/g, '.') ) const description = $('div.nameextc').text() return {name, price, description} }
import _request from 'request-promise' import cheerio from 'cheerio' const jar = _request.jar() const request = _request.defaults({ headers: {'Content-Type': 'application/json'}, jar, }) const SCV='https://www.alza.sk/Services/EShopService.svc/' export function* login(credentials) { return yield request.post(`${SCV}LoginUser`, {body: JSON.stringify(credentials)}) } export function* addToCart({url, count}) { const id = url.match(/(d|dq=)(\d*)(\.htm)?$/)[2] return yield request.post(`${SCV}OrderCommodity`, {body: JSON.stringify( {id, count} )}) } export function* getInfo(url) { const $ = cheerio.load(yield request(url)) const name = $('h1[itemprop="name"]').text() const price = parseFloat( $('span.price_withoutVat').text() .replace(/[^\d,]/g, '') .replace(/,/g, '.') ) const description = $('div.nameextc').text() return {name, price, description} }
Change username input to use blueprint
// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container } from 'rebass'; import { actions } from '../../redux/players'; import { InputGroup, Button, Classes, Intent } from '@blueprintjs/core'; import HomeLayout from './components/HomeLayout'; class SplashScreen extends Component { _username = ''; play = e => { e.preventDefault(); if (this._username !== undefined) { this.props.chooseUsername(this._username); } }; render() { return ( <HomeLayout> <Container> <form onSubmit={this.play}> <InputGroup placeholder="Username" onChange={e => (this._username = e.target.value)} rightElement={this.renderSubmit()} /> </form> </Container> </HomeLayout> ); } renderSubmit = () => ( <Button className={Classes.MINIMAL} onClick={this.play} intent={Intent.PRIMARY} rightIconName="arrow-right" /> ); } const mapDispatchToProps = { chooseUsername: actions.chooseUsername, }; export default connect(null, mapDispatchToProps)(SplashScreen);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Button, Container, Input } from 'rebass'; import { actions } from '../../redux/players'; import HomeLayout from './components/HomeLayout'; class SplashScreen extends Component { play = e => { if (this._username !== undefined) { this.props.chooseUsername(this._username); } }; render() { return ( <HomeLayout> <Container> <Input name="username" label="Username" placeholder="Username" hideLabel onChange={e => (this._username = e.target.value)} /> <Button backgroundColor="primary" color="white" big onClick={this.play}> PLAY NOW! </Button> </Container> </HomeLayout> ); } } const mapStateToProps = state => ({}); const mapDispatchToProps = { chooseUsername: actions.chooseUsername, }; export default connect(mapStateToProps, mapDispatchToProps)(SplashScreen);
Add javadoc to the Jackson Module Repository Signed-off-by: Clement Escoffier <6397137e57d1f87002962a37058f2a1c76fca9db@gmail.com>
/* * #%L * Wisdom-Framework * %% * Copyright (C) 2013 - 2014 Wisdom Framework * %% * 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. * #L% */ package org.wisdom.api.content; import com.fasterxml.jackson.databind.Module; /** * A service exposed by the content manager to let applications register custom JSON serializer and deserializer * (also call module). * <p/> * Users must not forget to call {@link #unregister(com.fasterxml.jackson.databind.Module)} for each module they * registered. */ public interface JacksonModuleRepository { /** * Registers a module. * Don't forget to unregister the module when leaving. * * @param module the module */ public void register(Module module); /** * Un-registers a module * * @param module the module */ public void unregister(Module module); }
/* * #%L * Wisdom-Framework * %% * Copyright (C) 2013 - 2014 Wisdom Framework * %% * 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. * #L% */ package org.wisdom.api.content; import com.fasterxml.jackson.databind.Module; /** * A service exposed by the content manager to let applications register custom JSON serializer and deserializer. */ public interface JacksonModuleRepository { public void register(Module module); public void unregister(Module module); }
Add initials and lower random number
var _ = require('underscore'); module.exports = function(name) { var nameConversions = [ initials = /^(\w).*\s(\w).*$/ firstInitialAndLastName = /^(\w).*\s(\w+)$/, firstAndLastName = /^(\w+)\s(\w+)$/, firstNameAndLastInitial = /^(\w+)\s(\w).+$/ ]; var emailDelimiters = [ contiguous = "$1$2", dot = "$1.$2", dash = "$1-$2", underscore = "$1_$2", reversed = "$2$1", reversedDot = "$2.$1", reversedDash = "$2-$1", reversedUnderscore = "$2_$1", justLastName = "$2", justFirstName = "$1", ]; return name.toLowerCase().replace( _.shuffle(nameConversions)[0], _.shuffle(emailDelimiters)[0] ) + randomSuffix(); }; // Generate the random chance that a random number will be affixed to the end function randomSuffix() { var randomChance = Math.round(Math.random()); if ( randomChance ) { return Math.floor(Math.random()*101); } else { return ""; } }
var _ = require('underscore'); module.exports = function(name) { var nameConversions = [ firstInitialAndLastName = /^(\w).*\s(\w+)$/, firstAndLastName = /^(\w+)\s(\w+)$/, firstNameAndLastInitial = /^(\w+)\s(\w).+$/ ]; var emailDelimiters = [ contiguous = "$1$2", dot = "$1.$2", dash = "$1-$2", underscore = "$1_$2", reversed = "$2$1", reversedDot = "$2.$1", reversedDash = "$2-$1", reversedUnderscore = "$2_$1", justLastName = "$2", justFirstName = "$1", ]; return name.toLowerCase().replace( _.shuffle(nameConversions)[0], _.shuffle(emailDelimiters)[0] ) + randomSuffix(); }; // Generate the random chance that a random number will be affixed to the end function randomSuffix() { var randomChance = Math.round(Math.random()); if ( randomChance ) { return Math.floor(Math.random()*1001); } else { return ""; } }
Fix failing Firefox Hello test
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.firefox.hello import HelloPage @pytest.mark.smoke @pytest.mark.nondestructive def test_play_video(base_url, selenium): page = HelloPage(base_url, selenium).open() video = page.play_video() assert video.is_displayed video.close() @pytest.mark.skip_if_not_firefox @pytest.mark.smoke @pytest.mark.nondestructive def test_try_hello_button_is_displayed(base_url, selenium): page = HelloPage(base_url, selenium).open() assert page.is_try_hello_button_displayed @pytest.mark.skip_if_firefox @pytest.mark.smoke @pytest.mark.nondestructive def test_download_button_is_displayed(base_url, selenium): page = HelloPage(base_url, selenium).open() assert page.is_download_button_displayed assert not page.is_try_hello_button_displayed
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.firefox.hello import HelloPage @pytest.mark.smoke @pytest.mark.nondestructive def test_play_video(base_url, selenium): page = HelloPage(base_url, selenium).open() video = page.play_video() assert video.is_displayed video.close() @pytest.mark.skip_if_not_firefox @pytest.mark.smoke @pytest.mark.nondestructive def test_try_hello_button_is_displayed(base_url, selenium): page = HelloPage(base_url, selenium).open() assert page.is_try_hello_button_displayed assert not page.is_download_button_displayed @pytest.mark.skip_if_firefox @pytest.mark.smoke @pytest.mark.nondestructive def test_download_button_is_displayed(base_url, selenium): page = HelloPage(base_url, selenium).open() assert page.is_download_button_displayed assert not page.is_try_hello_button_displayed