text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix render function so 404 body is not ignored by slim
<?php namespace SlimJson; use Slim\Slim; class View extends \Slim\View { /** * @param int|string $status * @param array|null $data * @return void */ public function render($status, $data = null) { $app = Slim::getInstance(); $response = $this->all(); $status = \intval($status); $app->response()->status($status); if ($app->config(Config::Status)) { $response['_status'] = $status; } if (isset($response['flash']) && \is_object($response['flash'])) { $flash = $this->data->flash->getMessages(); if (count($flash)) { $response['flash'] = $flash; } else { unset($response['flash']); } } $app->response()->header('Content-Type', 'application/json'); $body = json_encode($response, $app->config(Config::JsonEncodeOptions))); if($status == 404){ return $body; }else{ $app->response()->body($body); } }
<?php namespace SlimJson; use Slim\Slim; class View extends \Slim\View { /** * @param int|string $status * @param array|null $data * @return void */ public function render($status, $data = null) { $app = Slim::getInstance(); $response = $this->all(); $status = \intval($status); $app->response()->status($status); if ($app->config(Config::Status)) { $response['_status'] = $status; } if (isset($response['flash']) && \is_object($response['flash'])) { $flash = $this->data->flash->getMessages(); if (count($flash)) { $response['flash'] = $flash; } else { unset($response['flash']); } } $app->response()->header('Content-Type', 'application/json'); $app->response()->body(json_encode($response, $app->config(Config::JsonEncodeOptions))); } }
Change camera angle from 115 to 125 degrees.
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.stuy.subsystems; import edu.stuy.RobotMap; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.command.Subsystem; /** * * @author Yulli */ public class Camera extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. private static final int LOWER_ANGLE = 125; private static final int UPPER_ANGLE = 180; Servo camServo; public Camera(){ camServo = new Servo(RobotMap.CAMERA_SERVO); } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void switchView(boolean down){ if(down){ camServo.setAngle(LOWER_ANGLE); } else { camServo.setAngle(UPPER_ANGLE); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.stuy.subsystems; import edu.stuy.RobotMap; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.command.Subsystem; /** * * @author Yulli */ public class Camera extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. private static final int LOWER_ANGLE = 115; private static final int UPPER_ANGLE = 180; Servo camServo; public Camera(){ camServo = new Servo(RobotMap.CAMERA_SERVO); } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void switchView(boolean down){ if(down){ camServo.setAngle(LOWER_ANGLE); } else { camServo.setAngle(UPPER_ANGLE); } } }
Add photoUrl to sample data
import { connect } from 'react-redux'; import Matches from '../components/Matches.jsx'; import { unmountMatch, removeMatch, incrementOffset, addMatches } from '../actions/index.js'; const mapStateToProps = (state) => ( { matches: state.matches.values, offset: state.matches.offset, selfId: state.profile.id, } ); const mapDispatchToProps = (dispatch) => ( { onConnectClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onHideClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onLoadMoreClick: (selfId, offset) => { //use the offset to get additional matches from db, then dispatch(addMatches([{firstName: 'Velvet', lastName: 'Underground', canTeach: [['English', 'native']], willLearn: [['German', 'advanced']], description: 'hi there', photoUrl: 'http://watchmojo.com/uploads/blipthumbs/M-RR-Top10-Velvet-Underground-Songs-480p30_480.jpg'}])); dispatch(incrementOffset(20)); }, } ); export default connect(mapStateToProps, mapDispatchToProps)(Matches);
import { connect } from 'react-redux'; import Matches from '../components/Matches.jsx'; import { unmountMatch, removeMatch, incrementOffset, addMatches } from '../actions/index.js'; const mapStateToProps = (state) => ( { matches: state.matches.values, offset: state.matches.offset, selfId: state.profile.id, } ); const mapDispatchToProps = (dispatch) => ( { onConnectClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onHideClick: (id) => { dispatch(unmountMatch(id)); setTimeout( () => { dispatch(removeMatch(id)); }, 120 ); }, onLoadMoreClick: (selfId, offset) => { //use the offset to get additional matches from db, then dispatch(addMatches([{firstName: 'Velvet', lastName: 'Underground', canTeach: [['English', 'native']], willLearn: [['German', 'advanced']], description: 'hi there'}])); dispatch(incrementOffset(20)); }, } ); export default connect(mapStateToProps, mapDispatchToProps)(Matches);
Reduce fontSize so that it's not too big..
export default { data: () => ({ videoHeight: 0 }), mounted () { this.setHeight() window.addEventListener('resize', this.setHeight) }, beforeDestroy () { window.removeEventListener('resize', this.setHeight) }, methods: { getHeight () { return document.getElementsByTagName('video')[0].clientHeight }, setHeight () { this.videoHeight = this.getHeight() }, getStyle (cue) { return { [cue.vert]: cue.line + '%', left: cue.position + '%', transform: `translate(${cue.align}%, 0)${cue.rotate || ''}`, 'text-align': cue.textAlign, // We reduce the size a bit so that it's not too big on the screen :< 'font-size': Math.round(0.90 * cue.fontSize * this.videoHeight) + 'px' } } } }
export default { data: () => ({ videoHeight: 0 }), mounted () { this.setHeight() window.addEventListener('resize', this.setHeight) }, beforeDestroy () { window.removeEventListener('resize', this.setHeight) }, methods: { getHeight () { return document.getElementsByTagName('video')[0].clientHeight }, setHeight () { this.videoHeight = this.getHeight() }, getStyle (cue) { return { [cue.vert]: cue.line + '%', left: cue.position + '%', transform: `translate(${cue.align}%, 0)${cue.rotate || ''}`, 'text-align': cue.textAlign, 'font-size': Math.round(cue.fontSize * this.videoHeight) + 'px' } } } }
Insert plain.tex into REPL state
from nex.state import GlobalState from nex.reader import Reader from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber from nex.box_writer import write_to_dvi_file from nex.utils import TidyEnd reader = Reader() state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) reader.insert_file('/Users/ejm/projects/nex/tex/plain.tex') state.execute_commands(command_grabber, banisher, reader) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer write_to_dvi_file(state, 'repl.dvi', write_pdf=True)
from nex.state import GlobalState from nex.reader import Reader, EndOfFile from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber from nex.box_writer import write_to_file from nex.utils import TidyEnd reader = Reader() state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/example/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer write_to_file(state, 'done.dvi')
Remove typecast on setting Response
<?php namespace Expressly\Event; use Buzz\Message\Response; use Symfony\Component\EventDispatcher\Event; class ResponseEvent extends Event { private $response; public function getResponse() { return $this->response; } public function setResponse($response) { $this->response = $response; return $this; } public function isSuccessful() { if (!$this->response instanceof Response) { return false; } return $this->response->isSuccessful(); } public function getContent() { if (!$this->response instanceof Response) { return null; } $content = $this->response->getContent(); if (is_array($content)) { return $content; } $json = json_decode($content, true); return (json_last_error() == JSON_ERROR_NONE) ? $json : $content; } }
<?php namespace Expressly\Event; use Buzz\Message\Response; use Symfony\Component\EventDispatcher\Event; class ResponseEvent extends Event { private $response; public function getResponse() { return $this->response; } public function setResponse(Response $response) { $this->response = $response; return $this; } public function isSuccessful() { if (!$this->response instanceof Response) { return false; } return $this->response->isSuccessful(); } public function getContent() { if (!$this->response instanceof Response) { return null; } $content = $this->response->getContent(); if (is_array($content)) { return $content; } $json = json_decode($content, true); return (json_last_error() == JSON_ERROR_NONE) ? $json : $content; } }
Increase timeout for changes to properly close
import test from 'tape' import { connection } from '../config/rethinkdb' import './server/helpers/config' import './server/helpers/createStore' import './server/helpers/renderApp' import './server/config/rethinkdb' import './server/routes/errors' import './server/routes/main' import './server/routes/search' import './server/routes/sockets' import './client/main' import './client/helpers/actions' import './client/helpers/reducers' import './client/helpers/history' import './client/helpers/snippet' import './client/containers/bkmrkd' import './client/containers/toaster' import './client/components/toast' import './client/components/colophon' import './client/components/bookmark' import './client/components/bookmarks' import './client/components/searchForm' import './client/components/search' test.onFinish(() => { // give time for the socket to close out setTimeout(() => { connection.close() }, 5000) })
import test from 'tape' import { connection } from '../config/rethinkdb' import './server/helpers/config' import './server/helpers/createStore' import './server/helpers/renderApp' import './server/config/rethinkdb' import './server/routes/errors' import './server/routes/main' import './server/routes/search' import './server/routes/sockets' import './client/main' import './client/helpers/actions' import './client/helpers/reducers' import './client/helpers/history' import './client/helpers/snippet' import './client/containers/bkmrkd' import './client/containers/toaster' import './client/components/toast' import './client/components/colophon' import './client/components/bookmark' import './client/components/bookmarks' import './client/components/searchForm' import './client/components/search' test.onFinish(() => { // give time for the socket to close out setTimeout(() => { connection.close() }, 1000) })
Add helper method to count number of matches
<?php abstract class AlgorithmMM extends Algorithm { /** * Origianl graph * * @var Graph */ protected $graph; /** * The given graph where the algorithm should operate on * * @param Graph $graph * @throws Exception if the given graph is not balanced */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * Get the count of edges that are in the match * * @throws Exception * @return AlgorithmMCF $this (chainable) * @uses AlgorithmMM::createGraph() * @uses Graph::getNumberOfEdges() */ public function getNumberOfMatches(){ return $this->createGraph()->getNumberOfEdges(); } /** * create new resulting graph with minimum-cost flow on edges * * @throws Exception if the graph has not enough capacity for the minimum-cost flow * @return Graph */ abstract public function createGraph(); }
<?php abstract class AlgorithmMM extends Algorithm { /** * Origianl graph * * @var Graph */ protected $graph; /** * The given graph where the algorithm should operate on * * @param Graph $graph * @throws Exception if the given graph is not balanced */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * Get the count of edges that are in the matchin * * @throws Exception * @return AlgorithmMCF $this (chainable) */ public function getMatchingValue(){ // TODO count the matching edges return null; } /** * create new resulting graph with minimum-cost flow on edges * * @throws Exception if the graph has not enough capacity for the minimum-cost flow * @return Graph */ abstract public function createGraph(); }
Move makeconf state tests to pytest
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret # 'absent' function tests: 1 def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
Remove 'about' button from CKEditor
CKEDITOR.plugins.addExternal( 'cortex_media_insert', '/assets/ckeditor/plugins/cortex_media_insert/' ); CKEDITOR.editorConfig = function( config ) { config.extraPlugins = 'cortex_media_insert'; config.toolbarGroups = [ { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] }, { name: 'forms', groups: [ 'forms' ] }, { name: 'styles', groups: [ 'styles' ] }, { name: 'colors', groups: [ 'colors' ] }, { name: 'tools', groups: [ 'tools' ] }, { name: 'others', groups: [ 'others' ] }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] }, { name: 'links', groups: [ 'links' ] }, { name: 'insert', groups: [ 'insert' ] } ]; config.removeButtons = 'Image,Save,NewPage,Preview,Print,Templates,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,ShowBlocks,About'; };
CKEDITOR.plugins.addExternal( 'cortex_media_insert', '/assets/ckeditor/plugins/cortex_media_insert/' ); CKEDITOR.editorConfig = function( config ) { config.extraPlugins = 'cortex_media_insert'; config.toolbarGroups = [ { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] }, { name: 'forms', groups: [ 'forms' ] }, { name: 'styles', groups: [ 'styles' ] }, { name: 'colors', groups: [ 'colors' ] }, { name: 'tools', groups: [ 'tools' ] }, { name: 'others', groups: [ 'others' ] }, { name: 'about', groups: [ 'about' ] }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] }, { name: 'links', groups: [ 'links' ] }, { name: 'insert', groups: [ 'insert' ] } ]; config.removeButtons = 'Image,Save,NewPage,Preview,Print,Templates,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,ShowBlocks,About'; };
Test of invalid equality test
"""Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase from raco.expression import TypeSafetyViolation from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema) def invalid_eq(self): query = """ X = [FROM SCAN(public:adhoc:mytable) AS X EMIT clong=cstring]; STORE(X, OUTPUT); """ with self.assertRaises(TypeSafetyViolation): self.check_scheme(query, None)
"""Various tests of type safety.""" import unittest from raco.fakedb import FakeDatabase from raco.scheme import Scheme from raco.myrial.myrial_test import MyrialTestCase from collections import Counter class TypeTests(MyrialTestCase): schema = Scheme( [("clong", "LONG_TYPE"), ("cint", "INT_TYPE"), ("cstring", "STRING_TYPE"), ("cfloat", "DOUBLE_TYPE")]) def setUp(self): super(TypeTests, self).setUp() self.db.ingest("public:adhoc:mytable", Counter(), TypeTests.schema) def noop_test(self): query = """ X = SCAN(public:adhoc:mytable); STORE(X, OUTPUT); """ self.check_scheme(query, TypeTests.schema)
Fix misspellings in python marconiclient Fix misspellings detected by: * pip install misspellings * git ls-files | grep -v locale | misspellings -f - Change-Id: I4bbc0ba5be154950a160871ef5675039697f2314 Closes-Bug: #1257295
# 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. import abc import six @six.add_metaclass(abc.ABCMeta) class AuthBackend(object): def __init__(self, conf): self.conf = conf @abc.abstractmethod def authenticate(self, api_version, request): """Authenticates the user in the selected backend. Auth backends will have to manipulate the request and prepare it to send the auth information back to Marconi's instance. :params api_version: Marconi's API version. :params request: Request Spec instance that can be manipulated by the backend if the authentication succeeds. :returns: The modified request spec. """ class NoAuth(AuthBackend): """No Auth Plugin.""" def authenticate(self, api_version, req): return req
# 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. import abc import six @six.add_metaclass(abc.ABCMeta) class AuthBackend(object): def __init__(self, conf): self.conf = conf @abc.abstractmethod def authenticate(self, api_version, request): """Authenticates the user in the selected backend. Auth backends will have to manipulate the request and prepare it to send the auth information back to Marconi's instance. :params api_version: Marconi's API verison. :params request: Request Spec instance that can be manipulated by the backend if the authentication succeeds. :returns: The modified request spec. """ class NoAuth(AuthBackend): """No Auth Plugin.""" def authenticate(self, api_version, req): return req
Add user variables to bot game playing status
package com.avairebot.orion.scheduler; import com.avairebot.orion.Orion; import com.avairebot.orion.contracts.scheduler.Job; import net.dv8tion.jda.core.entities.Game; public class ChangeGameJob extends Job { private int index = 0; public ChangeGameJob(Orion orion) { super(orion); } @Override public void run() { if (orion.config.getPlaying().size() <= index) { index = 0; } orion.getJDA().getPresence().setGame( Game.of(formatGame(orion.config.getPlaying().get(index++))) ); } private String formatGame(String game) { game = game.replaceAll("%users%", "" + orion.getJDA().getUsers().size()); game = game.replaceAll("%guilds%", "" + orion.getJDA().getGuilds().size()); if (orion.getJDA().getShardInfo() != null) { game = game.replaceAll("%shard-id%", "" + orion.getJDA().getShardInfo().getShardId()); game = game.replaceAll("%shard-total%", "" + orion.getJDA().getShardInfo().getShardTotal()); } return game; } }
package com.avairebot.orion.scheduler; import com.avairebot.orion.Orion; import com.avairebot.orion.contracts.scheduler.Job; import net.dv8tion.jda.core.entities.Game; public class ChangeGameJob extends Job { private int index = 0; public ChangeGameJob(Orion orion) { super(orion); } @Override public void run() { if (orion.config.getPlaying().size() <= index) { index = 0; } orion.getJDA().getPresence().setGame( Game.of(orion.config.getPlaying().get(index++)) ); } }
Send emails once we have them
var email = new (require('./emailer'))(), backdrop = new (require('./integrations/backdrop'))(), stagecraft = new (require('./integrations/stagecraft'))(), message = new (require('./message'))(), Q = require('q'), queue = []; // Query backdrop for out of date datasets backdrop.getDataSets().then(function (data) { // console.log('datasets', data); // Got some datasets, now find emails for them data.data_sets.forEach( function (dataSet) { // Set email message dataSet.message = message.dataSetReminder(dataSet); // Queue up email query for this dataset queue.push(stagecraft.queryEmail(dataSet)); }); // When all the email queries are finished, send some notifications return Q.all(queue).then( function (dataSets) { console.log(dataSets); dataSets.forEach( function (dataSet) { email.send({ to: dataSet.emails.toString(), subject: 'Datasets out of date', text: dataSet.message }); }); }); }).fail(function (err) { throw err; }).done();
var email = new (require('./emailer'))(), backdrop = new (require('./integrations/backdrop'))(), stagecraft = new (require('./integrations/stagecraft'))(), message = new (require('./message'))(), Q = require('q'), queue = []; // Query backdrop for out of date datasets backdrop.getDataSets().then(function (data) { // console.log('datasets', data); // Got some datasets, now find emails for them data.data_sets.forEach( function (dataSet) { // Set email message dataSet.message = message.dataSetReminder(dataSet); // Queue up email query for this dataset queue.push(stagecraft.queryEmail(dataSet)); }); // When all the email queries are finished, send some notifications return Q.all(queue).then( function (dataSets) { console.log(dataSets); // email.send({ // to: config.notificationsEmail, // subject: 'Datasets out of date', // text: 'There are ' + data.message + '\n\n' + JSON.stringify(data.data_sets) // }); }); }).fail(function (err) { throw err; }).done();
Fix transitions between header menu styles
/** * cbpAnimatedHeader.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2013, Codrops * http://www.codrops.com */ var cbpAnimatedHeader = (function() { var docElem = document.documentElement, header = document.querySelector( '.navbar-fixed-top' ), didScroll = false, changeHeaderOn = 750; function init() { window.addEventListener( 'scroll', function( event ) { if( !didScroll ) { didScroll = true; setTimeout( scrollPage, 250 ); } }, false ); } function scrollPage() { var sy = scrollY(); if ( sy >= changeHeaderOn ) { classie.add( header, 'navbar-shrink' ); } else { classie.remove( header, 'navbar-shrink' ); } didScroll = false; } function scrollY() { return window.pageYOffset || docElem.scrollTop; } init(); })();
/** * cbpAnimatedHeader.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2013, Codrops * http://www.codrops.com */ var cbpAnimatedHeader = (function() { var docElem = document.documentElement, header = document.querySelector( '.navbar-fixed-top' ), didScroll = false, changeHeaderOn = 300; function init() { window.addEventListener( 'scroll', function( event ) { if( !didScroll ) { didScroll = true; setTimeout( scrollPage, 250 ); } }, false ); } function scrollPage() { var sy = scrollY(); if ( sy >= changeHeaderOn ) { classie.add( header, 'navbar-shrink' ); } else { classie.remove( header, 'navbar-shrink' ); } didScroll = false; } function scrollY() { return window.pageYOffset || docElem.scrollTop; } init(); })();
Fix ImportError and use bytes in outstream
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer except ImportError: from http.server import BaseHTTPRequestHandler, HTTPServer class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type','text/plain') self.end_headers() self.wfile.write(b'Hello GCP dev!') return def run(): print('Server is starting...') server_address = ('0.0.0.0', 80) server = HTTPServer(server_address, SimpleHTTPRequestHandler) print('Started. Press Ctrl + C to stop') server.serve_forever() if __name__ == '__main__': run()
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type','text/plain') self.end_headers() self.wfile.write('Hello GCP dev!') return def run(): print('Server is starting...') server_address = ('0.0.0.0', 80) server = HTTPServer(server_address, SimpleHTTPRequestHandler) print('Started. Press Ctrl + C to stop') server.serve_forever() if __name__ == '__main__': run()
Use trashed() to check if deleted
{{-- Copyright 2016 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} @php if ($post->trashed()) { $deleteString = 'restore'; $iconClass = 'fa-undo'; } else { $deleteString = 'delete'; $iconClass = 'fa-trash'; } @endphp <a title="{{ trans('forum.post.actions.'.$deleteString) }}" data-tooltip-position="left center" href="{{ route("forum.posts.$deleteString", $post) }}" class="btn-circle js-post-delete-toggle" data-remote="true" data-method="post" data-confirm="{{ trans("forum.post.confirm_".$deleteString) }}" > <i class="fa {{ $iconClass }}"></i> </a>
{{-- Copyright 2016 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} @php $deleteString = $post->deleted_at ? 'restore' : 'delete' @endphp <a title="{{ trans('forum.post.actions.'.$deleteString) }}" data-tooltip-position="left center" href="{{ route("forum.posts.$deleteString", $post) }}" class="btn-circle js-post-delete-toggle" data-remote="true" data-method="post" data-confirm="{{ trans("forum.post.confirm_".$deleteString) }}" > <i class="fa fa-{{ $post->deleted_at ? 'undo' : 'trash' }}"></i> </a>
Fix the same typo in GrabLaunchpadBugs
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() tasks.register(GrabMiroBugs) tasks.register(GrabLaunchpadBugs)
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_project) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() tasks.register(GrabMiroBugs) tasks.register(GrabLaunchpadBugs)
Support --name options to filter spec files
'use strict'; var jest = require('jest-cli'), gutil = require('gulp-util'), through = require('through2'); module.exports = function (options) { options = options || {}; return through.obj(function (file, enc, cb) { options.rootDir = options.rootDir || file.path; var cliOptions = {config: options}; for(var i = 0, j = process.argv.length; i < j; i++) { if(process.argv[i].indexOf('--name=') === 0) { var value = process.argv[i].substring('--name='.length); cliOptions.testPathPattern = new RegExp(value); } } jest.runCLI(cliOptions, options.rootDir, function (success) { if(!success) { cb(new gutil.PluginError('gulp-jest', { message: "Tests Failed" })); } else { cb(); } }.bind(this)); }); };
'use strict'; var jest = require('jest-cli'), gutil = require('gulp-util'), through = require('through2'); module.exports = function (options) { options = options || {}; return through.obj(function (file, enc, cb) { options.rootDir = options.rootDir || file.path; jest.runCLI({ config: options }, options.rootDir, function (success) { if(!success) { cb(new gutil.PluginError('gulp-jest', { message: "Tests Failed" })); } else { cb(); } }.bind(this)); }); };
Fix symlink lookup: excludePattern shoud be used as path so it doesn't recurse into excludes paths
<?php namespace Kwf\FileWatcher\Helper; use Symfony\Component\Finder\Finder; class Links { public static function followLinks(array $paths, $excludePatterns) { $finder = new Finder(); $finder->directories(); foreach ($excludePatterns as $excludePattern) { $finder->notPath($excludePattern); } foreach ($paths as $p) { $finder->in($p); } foreach ($finder as $i) { if ($i->isLink()) { $realPath = $i->getRealPath(); foreach ($paths as $k=>$p2) { if (substr($realPath, 0, strlen($p2)+1) == $p2.'/') { continue 2; } } $paths[] = $realPath; } } return $paths; } }
<?php namespace Kwf\FileWatcher\Helper; use Symfony\Component\Finder\Finder; class Links { public static function followLinks(array $paths, $excludePatterns) { $finder = new Finder(); $finder->directories(); foreach ($excludePatterns as $excludePattern) { $finder->notName($excludePattern); } foreach ($paths as $p) { $finder->in($p); } foreach ($finder as $i) { if ($i->isLink()) { $realPath = $i->getRealPath(); foreach ($paths as $k=>$p2) { if (substr($realPath, 0, strlen($p2)+1) == $p2.'/') { continue 2; } } $paths[] = $realPath; } } return $paths; } }
Add space in the error message.
/* * Copyright 2014 Josef Hardi <josef.hardi@gmail.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 io.github.johardi.r2rmlparser.exception; import io.github.johardi.r2rmlparser.util.StringUtils; public class InvalidPropertyAttributeException extends JR2RmlParserRuntimeException { private static final long serialVersionUID = 1681949L; private String mPropertyLabel; private String mExceptionDetail; public InvalidPropertyAttributeException(String propertyLabel) { mPropertyLabel = propertyLabel; } public void setExceptionDetail(String detail) { mExceptionDetail = detail; } @Override public String getMessage() { StringBuilder sb = new StringBuilder(); sb.append("Invalid property attribute for "); sb.append("\"").append(mPropertyLabel).append("\""); if (!StringUtils.isEmpty(mExceptionDetail)) { sb.append(" "); sb.append(mExceptionDetail); } return sb.toString(); } }
/* * Copyright 2014 Josef Hardi <josef.hardi@gmail.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 io.github.johardi.r2rmlparser.exception; import io.github.johardi.r2rmlparser.util.StringUtils; public class InvalidPropertyAttributeException extends JR2RmlParserRuntimeException { private static final long serialVersionUID = 1681949L; private String mPropertyLabel; private String mExceptionDetail; public InvalidPropertyAttributeException(String propertyLabel) { mPropertyLabel = propertyLabel; } public void setExceptionDetail(String detail) { mExceptionDetail = detail; } @Override public String getMessage() { StringBuilder sb = new StringBuilder(); sb.append("Invalid property attribute for"); sb.append("\"").append(mPropertyLabel).append("\""); if (!StringUtils.isEmpty(mExceptionDetail)) { sb.append(" "); sb.append(mExceptionDetail); } return sb.toString(); } }
Add a new method in interface also
<?php /* * @author Mirel Nicu Mitache <mirel.mitache@gmail.com> * @package MPF Framework * @link http://www.mpfframework.com * @category core package * @version 1.0 * @since MPF Framework Version 1.0 * @copyright Copyright &copy; 2011 Mirel Mitache * @license http://www.mpfframework.com/licence * * This file is part of MPF Framework. * * MPF Framework is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MPF Framework is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MPF Framework. If not, see <http://www.gnu.org/licenses/>. */ namespace mpf\interfaces; interface ActiveUserInterface extends LogAwareObjectInterface { public static function get(); public function isGuest(); public function login($user, $password); public function logout(); public function getRights(); public function hasAnyOfThisRights($rights); public function hasRight($right); }
<?php /* * @author Mirel Nicu Mitache <mirel.mitache@gmail.com> * @package MPF Framework * @link http://www.mpfframework.com * @category core package * @version 1.0 * @since MPF Framework Version 1.0 * @copyright Copyright &copy; 2011 Mirel Mitache * @license http://www.mpfframework.com/licence * * This file is part of MPF Framework. * * MPF Framework is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MPF Framework is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MPF Framework. If not, see <http://www.gnu.org/licenses/>. */ namespace mpf\interfaces; interface ActiveUserInterface extends LogAwareObjectInterface { public static function get(); public function isGuest(); public function login($user, $password); public function logout(); public function getRights(); }
Create new instances of strings, and truncate length of message contents This should drastically reduce memory consumption. The new strings need to be created because the groups matched from regexps are just pointers into the original string, meaning we left the whole old HTML string around forever...
/* * MailMessage.java - This class holds an abstract base class for implementing a mailinglist-specific * message with required identifiers and content. * * Copyright (C) 2010 Magnus Hagander <magnus@hagander.net> * * This software is released under the BSD license. */ package net.hagander.mailinglistmoderator.backend; /** * * @author Magnus Hagander <magnus@hagander.net> * * This base class is simply a container for some common properties. */ public abstract class MailMessage { private String sender; private String subject; private String content; private statuslevel status = statuslevel.Defer; public enum statuslevel { Accept, Reject, Defer }; public MailMessage(String sender, String subject, String content) { /* * Create new strings to de-couple from large strings being returned * in regex matches. We do this here to get it in a centralized location, * even if it means we might duplicate once or twice too many. * Also, limit the length of the content to 255 bytes. */ this.sender = new String(sender); this.subject = new String(subject); if (content.length() > 255) this.content = new String(content.substring(0,255)); else this.content = new String(content); } public String getSender() { return sender; } public String getSubject() { return subject; } public String getContent() { return content; } public void setStatus(statuslevel status) { this.status = status; } public statuslevel getStatus() { return status; } }
/* * MailMessage.java - This class holds an abstract base class for implementing a mailinglist-specific * message with required identifiers and content. * * Copyright (C) 2010 Magnus Hagander <magnus@hagander.net> * * This software is released under the BSD license. */ package net.hagander.mailinglistmoderator.backend; /** * * @author Magnus Hagander <magnus@hagander.net> * * This base class is simply a container for some common properties. */ public abstract class MailMessage { private String sender; private String subject; private String content; private statuslevel status = statuslevel.Defer; public enum statuslevel { Accept, Reject, Defer }; public MailMessage(String sender, String subject, String content) { this.sender = sender; this.subject = subject; this.content = content; } public String getSender() { return sender; } public String getSubject() { return subject; } public String getContent() { return content; } public void setStatus(statuslevel status) { this.status = status; } public statuslevel getStatus() { return status; } }
Change of function to error_reporting
<?php /** * Main Controller * * @package MagicPHP * @author André Ferreira <andrehrf@gmail.com> * @link https://github.com/magicphp/magicphp MagicPHP(tm) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ if($_SERVER["REMOTE_ADDR"] == "127.0.0.1" || $_SERVER["REMOTE_ADDR"] == "::1"){ ini_set("display_errors", "on"); error_reporting(E_ERROR); } if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php")) require_once(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php"); require_once(__DIR__ . DIRECTORY_SEPARATOR . "bootstrap.php"); Bootstrap::Start(); if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "routes.php")) require_once(__DIR__ . DIRECTORY_SEPARATOR . "routes.php"); Bootstrap::AutoLoad("settings"); Routes::Parse();
<?php /** * Main Controller * * @package MagicPHP * @author André Ferreira <andrehrf@gmail.com> * @link https://github.com/magicphp/magicphp MagicPHP(tm) * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ if($_SERVER["REMOTE_ADDR"] == "127.0.0.1" || $_SERVER["REMOTE_ADDR"] == "::1"){ ini_set("display_errors", "on"); error_log(E_ERROR); } if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php")) require_once(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php"); require_once(__DIR__ . DIRECTORY_SEPARATOR . "bootstrap.php"); Bootstrap::Start(); if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "routes.php")) require_once(__DIR__ . DIRECTORY_SEPARATOR . "routes.php"); Bootstrap::AutoLoad("settings"); Routes::Parse();
Print error stack on error.
const Promise = require('bluebird'); const argvSplit = require('argv-split'); const execa = require('execa'); const fs = Promise.promisifyAll(require('fs')); const path = require('path'); function history(histFile) { histFile = histFile || path.join(os.homedir(), '.zsh_history'); return execa(path.join(__dirname, 'history.sh'), [histFile]) .then(result => { return fs.readFileAsync(result.stdout, 'utf-8'); }) .then(history => { return history.trim().split('\n').map(parseLine); }) .catch(error => { throw new Error(`Unable to read history from \`${histFile}\`.\n${error.stack}`); }); }; function parseLine(line) { const parts = line.match(/^ *(\d+) (\d+) (\d+):(\d+) (\S+) ?(.*)?/); return { time: new Date(parseInt(parts[2]) * 1000), executionTime: parseInt(parts[3]) * 60 + parseInt(parts[4]), command: parts[5], arguments: argvSplit(parts[6] || ''), }; }; module.exports = history;
const Promise = require('bluebird'); const argvSplit = require('argv-split'); const execa = require('execa'); const fs = Promise.promisifyAll(require('fs')); const path = require('path'); function history(histFile) { histFile = histFile || path.join(os.homedir(), '.zsh_history'); return execa(path.join(__dirname, 'history.sh'), [histFile]) .then(result => { return fs.readFileAsync(result.stdout, 'utf-8'); }) .then(history => { return history.trim().split('\n').map(parseLine); }) .catch(error => { throw new Error(`Unable to read history from \`${histFile}\`.`); }); }; function parseLine(line) { const parts = line.match(/^ *(\d+) (\d+) (\d+):(\d+) (\S+) ?(.*)?/); return { time: new Date(parseInt(parts[2]) * 1000), executionTime: parseInt(parts[3]) * 60 + parseInt(parts[4]), command: parts[5], arguments: argvSplit(parts[6] || ''), }; }; module.exports = history;
Add test for unicode characters
#!/usr/bin/env python import unittest import mlbgame class TestObject(unittest.TestCase): def test_object(self): data = { 'string': 'string', 'int': '10', 'float': '10.1', 'unicode': u'\xe7\x8c\xab' } obj = mlbgame.object.Object(data) self.assertIsInstance(obj.string, str) self.assertIsInstance(obj.int, int) self.assertIsInstance(obj.float, float) self.assertIsInstance(obj.unicode, unicode) self.assertEqual(obj.string, 'string') self.assertEqual(obj.int, 10) self.assertEqual(obj.float, 10.1) self.assertEqual(obj.unicode, u'\xe7\x8c\xab')
#!/usr/bin/env python import unittest import mlbgame class TestObject(unittest.TestCase): def test_object(self): data = { 'string': 'string', 'int': '10', 'float': '10.1' } obj = mlbgame.object.Object(data) self.assertIsInstance(obj.string, str) self.assertIsInstance(obj.int, int) self.assertIsInstance(obj.float, float) self.assertEqual(obj.string, 'string') self.assertEqual(obj.int, 10) self.assertEqual(obj.float, 10.1)
Modify Transactions tests into a single ordered test, as ordering of separate test methods is unpredictable
package org.wildfly.swarm.it.transactions; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.wildfly.swarm.it.AbstractIntegrationTest; import static org.fest.assertions.Assertions.assertThat; /** * @author Bob McWhirter * @author Ken Finnigan */ @RunWith(Arquillian.class) public class TransactionsApplicationIT extends AbstractIntegrationTest { @Drone WebDriver browser; @Test public void testTransactions() { browser.navigate().to("http://localhost:8080/"); assertThat(browser.getPageSource()).contains("Active"); browser.navigate().to("http://localhost:8080/begincommit"); assertThat(browser.getPageSource()).contains("Transaction begun ok and committed ok" ); browser.navigate().to("http://localhost:8080/beginrollback"); assertThat(browser.getPageSource()).contains("Transaction begun ok and rolled back ok" ); } }
package org.wildfly.swarm.it.transactions; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.wildfly.swarm.it.AbstractIntegrationTest; import static org.fest.assertions.Assertions.assertThat; /** * @author Bob McWhirter */ @RunWith(Arquillian.class) public class TransactionsApplicationIT extends AbstractIntegrationTest { @Drone WebDriver browser; @Test public void testActive() { browser.navigate().to("http://localhost:8080/"); assertThat(browser.getPageSource()).contains("Active"); } @Test public void testBeginCommit() { browser.navigate().to("http://localhost:8080/begincommit"); assertThat(browser.getPageSource()).contains("Transaction begun ok and committed ok" ); } @Test public void testBeginRollback() { browser.navigate().to("http://localhost:8080/beginrollback"); assertThat(browser.getPageSource()).contains("Transaction begun ok and rolled back ok" ); } }
Add the known remotes as a property of the module.
whitelist.knownRemotes = { '207.97.227.253', '50.57.128.197', '108.171.174.178' }; function whitelist( options ) { options = options || {}; var ips = options.ips || []; if( !ips.length || options.known ) { ips.concat( whitelist.knownRemotes ); } return function( req, res, next ) { var err; if( ips.indexOf( req.socket.remoteAddress ) < 0 ) { err = new Error( '[bait] whitelist: Remote is not whitelisted (' + req.socket.remoteAddress + ').' ); err.status = 403; } next( err ); }; }; module.exports = whitelist;
var knownRemotes = { '207.97.227.253', '50.57.128.197', '108.171.174.178' }; module.exports = function whitelist( options ) { options = options || {}; var ips = options.ips || []; if( !ips.length || options.known ) { ips.concat( knownRemotes ); } return function( req, res, next ) { var err; if( ips.indexOf( req.socket.remoteAddress ) < 0 ) { err = new Error( '[bait] whitelist: Remote is not whitelisted (' + req.socket.remoteAddress + ').' ); err.status = 403; } next( err ); }; };
Fix wrong error message beingg print when the file has a syntax error Fixes #137
package read import ( "fmt" "os" "path/filepath" "runtime" "github.com/go-task/task/internal/taskfile" "gopkg.in/yaml.v2" ) // Taskfile reads a Taskfile for a given directory func Taskfile(dir string) (*taskfile.Taskfile, error) { path := filepath.Join(dir, "Taskfile.yml") if _, err := os.Stat(path); err != nil { return nil, fmt.Errorf(`No Taskfile.yml found. Use "task --init" to create a new one`) } t, err := readTaskfile(path) if err != nil { return nil, err } path = filepath.Join(dir, fmt.Sprintf("Taskfile_%s.yml", runtime.GOOS)) if _, err = os.Stat(path); err == nil { osTaskfile, err := readTaskfile(path) if err != nil { return nil, err } if err = taskfile.Merge(t, osTaskfile); err != nil { return nil, err } } for name, task := range t.Tasks { task.Task = name } return t, nil } func readTaskfile(file string) (*taskfile.Taskfile, error) { f, err := os.Open(file) if err != nil { return nil, err } var t taskfile.Taskfile return &t, yaml.NewDecoder(f).Decode(&t) }
package read import ( "fmt" "os" "path/filepath" "runtime" "github.com/go-task/task/internal/taskfile" "gopkg.in/yaml.v2" ) // Taskfile reads a Taskfile for a given directory func Taskfile(dir string) (*taskfile.Taskfile, error) { path := filepath.Join(dir, "Taskfile.yml") t, err := readTaskfile(path) if err != nil { return nil, fmt.Errorf(`No Taskfile.yml found. Use "task --init" to create a new one`) } path = filepath.Join(dir, fmt.Sprintf("Taskfile_%s.yml", runtime.GOOS)) if _, err = os.Stat(path); err == nil { osTaskfile, err := readTaskfile(path) if err != nil { return nil, err } if err = taskfile.Merge(t, osTaskfile); err != nil { return nil, err } } for name, task := range t.Tasks { task.Task = name } return t, nil } func readTaskfile(file string) (*taskfile.Taskfile, error) { f, err := os.Open(file) if err != nil { return nil, err } var t taskfile.Taskfile return &t, yaml.NewDecoder(f).Decode(&t) }
Studio: Fix removal of selection builder
/* * Axelor Business Solutions * * Copyright (C) 2021 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.axelor.studio.db.repo; import com.axelor.inject.Beans; import com.axelor.studio.db.SelectionBuilder; import com.axelor.studio.service.builder.SelectionBuilderService; public class SelectionBuilderRepo extends SelectionBuilderRepository { @Override public SelectionBuilder save(SelectionBuilder selectionBuilder) { Beans.get(SelectionBuilderService.class).build(selectionBuilder); return super.save(selectionBuilder); } @Override public void remove(SelectionBuilder selectionBuilder) { Beans.get(SelectionBuilderService.class) .removeSelection(null, SelectionBuilderService.SELECTION_PREFIX + selectionBuilder.getName().replace(" ", "-")); super.remove(selectionBuilder); } }
/* * Axelor Business Solutions * * Copyright (C) 2021 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.axelor.studio.db.repo; import com.axelor.inject.Beans; import com.axelor.studio.db.SelectionBuilder; import com.axelor.studio.service.builder.SelectionBuilderService; public class SelectionBuilderRepo extends SelectionBuilderRepository { @Override public SelectionBuilder save(SelectionBuilder selectionBuilder) { Beans.get(SelectionBuilderService.class).build(selectionBuilder); return super.save(selectionBuilder); } @Override public void remove(SelectionBuilder selectionBuilder) { Beans.get(SelectionBuilderService.class) .removeSelection(null, SelectionBuilderService.SELECTION_PREFIX + selectionBuilder.getId()); super.remove(selectionBuilder); } }
Clone the App with the current Context in the handler This makes it work on App Engine
package twitter import ( "gnd.la/app" ) // Handler represents a function type which receives the // result of authenticating a Twitter user. type Handler func(*app.Context, *User, *Token) // AuthHandler takes a Handler a returns a app.Handler which // can be added to a app. When users are directed to this // handler, they're first asked to authenticate with Twitter. // If the user accepts, Handler is called with a non-nil user // and a non-nil token. Otherwise, Handler is called with // both parameters set to nil. func AuthHandler(twApp *App, handler Handler) app.Handler { return func(ctx *app.Context) { token := ctx.FormValue("oauth_token") verifier := ctx.FormValue("oauth_verifier") cloned := twApp.Clone(ctx) if token != "" && verifier != "" { at, err := cloned.Exchange(token, verifier) if err != nil { panic(err) } user, err := cloned.Verify(at) if err != nil { panic(err) } handler(ctx, user, at) } else if denied := ctx.FormValue("denied"); denied != "" { purgeToken(denied) handler(ctx, nil, nil) } else { callback := ctx.URL().String() auth, err := cloned.Authenticate(callback) if err != nil { panic(err) } ctx.Redirect(auth, false) } } }
package twitter import ( "gnd.la/app" ) // Handler represents a function type which receives the // result of authenticating a Twitter user. type Handler func(*app.Context, *User, *Token) // AuthHandler takes a Handler a returns a app.Handler which // can be added to a app. When users are directed to this // handler, they're first asked to authenticate with Twitter. // If the user accepts, Handler is called with a non-nil user // and a non-nil token. Otherwise, Handler is called with // both parameters set to nil. func AuthHandler(twApp *App, handler Handler) app.Handler { return func(ctx *app.Context) { token := ctx.FormValue("oauth_token") verifier := ctx.FormValue("oauth_verifier") if token != "" && verifier != "" { at, err := twApp.Exchange(token, verifier) if err != nil { panic(err) } user, err := twApp.Verify(at) if err != nil { panic(err) } handler(ctx, user, at) } else if denied := ctx.FormValue("denied"); denied != "" { purgeToken(denied) handler(ctx, nil, nil) } else { callback := ctx.URL().String() auth, err := twApp.Authenticate(callback) if err != nil { panic(err) } ctx.Redirect(auth, false) } } }
Improve hot loading compile time
var config = require('./webpack.config.js'); var webpack = require('webpack'); var webpackDevServer = require('webpack-dev-server'); var compiler; var server; // Source maps config.devtool = 'eval'; config.output.publicPath = '/dist/'; // Remove minification to speed things up. config.plugins.splice(1, 2); // Add Hot Loader server entry points. config.entry.app.unshift( 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/dev-server' ); // Add HMR plugin config.plugins.unshift(new webpack.HotModuleReplacementPlugin()); // Add React Hot loader config.module.loaders[0].loaders.unshift('react-hot'); compiler = webpack(config); server = new webpackDevServer(compiler, { publicPath: config.output.publicPath, hot: true }); server.listen(8080);
var config = require('./webpack.config.js'); var webpack = require('webpack'); var webpackDevServer = require('webpack-dev-server'); var compiler; var server; // Source maps config.devtool = 'source-map'; config.output.publicPath = '/dist/'; // Remove minification to speed things up. config.plugins.splice(1, 2); // Add Hot Loader server entry points. config.entry.app.unshift( 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/dev-server' ); // Add HMR plugin config.plugins.unshift(new webpack.HotModuleReplacementPlugin()); // Add React Hot loader config.module.loaders[0].loaders.unshift('react-hot'); compiler = webpack(config); server = new webpackDevServer(compiler, { publicPath: config.output.publicPath, hot: true }); server.listen(8080);
Simplify rpc tests using return promise instead of done callback
var assert = require('assert'); var producer = require('../index')().producer; var consumer = require('../index')().consumer; var uuid = require('node-uuid'); var fixtures = { queues: ['rpc-queue-0'] }; describe('Producer/Consumer RPC messaging:', function() { before(function (done) { return consumer.connect() .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(function () { return producer.connect(); }) .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(done); }); it('should be able to create a consumer that returns a message if called as RPC [rpc-queue-0]', function () { return consumer.consume(fixtures.queues[0], function () { return 'Power Ranger Red'; }) .then(function(created) { assert(created === true); }); }); it('should be able to produce a RPC message and get a response [rpc-queue-0]', function () { return producer.produce(fixtures.queues[0], { msg: uuid.v4() }, { rpc: true }) .then(function (response) { assert.equal(response, 'Power Ranger Red'); }); }); });
var assert = require('assert'); var producer = require('../index')().producer; var consumer = require('../index')().consumer; var uuid = require('node-uuid'); var fixtures = { queues: ['rpc-queue-0'] }; describe('Producer/Consumer RPC messaging:', function() { before(function (done) { return consumer.connect() .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(function () { return producer.connect(); }) .then(function (_channel) { assert(_channel !== undefined); assert(_channel !== null); }) .then(done); }); it('should be able to create a consumer that returns a message if called as RPC [rpc-queue-0]', function (done) { consumer.consume(fixtures.queues[0], function () { return 'Power Ranger Red'; }) .then(function(created) { assert.equal(created, true); }) .then(done); }); it('should be able to produce a RPC message and get a response [rpc-queue-0]', function (done) { producer.produce(fixtures.queues[0], { msg: uuid.v4() }) .then(function (response) { assert.equal(response, 'Power Ranger Red'); }) .then(done); }); });
Throw exception if we can't parse url
<?php namespace PhpBrew\Downloader; use RuntimeException; class UrlDownloader { public $logger; public function __construct($logger) { $this->logger = $logger; } /** * @param string $url * @return string downloaded file (basename) */ public function download($url) { $this->logger->info("===> Downloading from $url"); $info = parse_url($url); if ( false == $info ) { throw new RuntimeException("Can not parse url"); } $basename = basename( $info['path'] ); // curl is faster than php system( 'curl -C - -# -O ' . $url ) !== false or die('Download failed.'); $this->logger->info("===> $basename downloaded."); if( ! file_exists($basename) ) { throw Exception("Download failed."); } return $basename; // return the filename } }
<?php namespace PhpBrew\Downloader; class UrlDownloader { public $logger; public function __construct($logger) { $this->logger = $logger; } /** * @param string $url * @return string downloaded file (basename) */ public function download($url) { $this->logger->info("===> Downloading from $url"); $info = parse_url($url); $basename = basename( $info['path'] ); // curl is faster than php system( 'curl -C - -# -O ' . $url ) !== false or die('Download failed.'); $this->logger->info("===> $basename downloaded."); if( ! file_exists($basename) ) { throw Exception("Download failed."); } return $basename; // return the filename } }
Fix import path to match rename
from twisted.internet import reactor, defer from twisted.internet.protocol import ClientCreator from twisted.protocols import amp from diceserver import Sum, Divide def doMath(): d1 = ClientCreator(reactor, amp.AMP).connectTCP( '127.0.0.1', 1234).addCallback( lambda p: p.callRemote(Sum, a=13, b=81)).addCallback( lambda result: result['total']) def trapZero(result): result.trap(ZeroDivisionError) print "Divided by zero: returning INF" return 1e1000 d2 = ClientCreator(reactor, amp.AMP).connectTCP( '127.0.0.1', 1234).addCallback( lambda p: p.callRemote(Divide, numerator=1234, denominator=0)).addErrback(trapZero) def done(result): print 'Done with math:', result defer.DeferredList([d1, d2]).addCallback(done) if __name__ == '__main__': doMath() reactor.run()
from twisted.internet import reactor, defer from twisted.internet.protocol import ClientCreator from twisted.protocols import amp from ampserver import Sum, Divide def doMath(): d1 = ClientCreator(reactor, amp.AMP).connectTCP( '127.0.0.1', 1234).addCallback( lambda p: p.callRemote(Sum, a=13, b=81)).addCallback( lambda result: result['total']) def trapZero(result): result.trap(ZeroDivisionError) print "Divided by zero: returning INF" return 1e1000 d2 = ClientCreator(reactor, amp.AMP).connectTCP( '127.0.0.1', 1234).addCallback( lambda p: p.callRemote(Divide, numerator=1234, denominator=0)).addErrback(trapZero) def done(result): print 'Done with math:', result defer.DeferredList([d1, d2]).addCallback(done) if __name__ == '__main__': doMath() reactor.run()
Adjust OSI classifers, description and keywords. - Upgrade OSI develoment status to '4 - beta'. - Change intended audience to 'Science/Research'. - Update description. - Update keywords.
import sys from setuptools import setup, find_packages if sys.version_info < (2, 7, 0): print("Error: signac requires python version >= 2.7.x.") sys.exit(1) setup( name='signac', version='0.2.8', packages=find_packages(), zip_safe=True, author='Carl Simon Adorf', author_email='csadorf@umich.edu', description="Simple data management framework.", keywords='simulation database index collaboration workflow', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering :: Physics", ], extras_require={ 'db': ['pymongo>=3.0'], 'mpi': ['mpi4py'], 'conversion': ['networkx>=1.1.0'], 'gui': ['PySide'], }, entry_points={ 'console_scripts': [ 'signac = signac.__main__:main', 'signac-gui = signac.gui:main', ], }, )
import sys if sys.version_info < (2,7,0): print("Error: signac requires python version >= 2.7.x.") sys.exit(1) from setuptools import setup, find_packages setup( name='signac', version='0.2.8', packages=find_packages(), zip_safe=True, author='Carl Simon Adorf', author_email='csadorf@umich.edu', description="Computational Database.", keywords='simulation tools mc md monte-carlo mongodb ' 'jobmanagement materials database', classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering :: Physics", ], extras_require={ 'db': ['pymongo>=3.0'], 'mpi': ['mpi4py'], 'conversion': ['networkx>=1.1.0'], 'gui': ['PySide'], }, entry_points={ 'console_scripts': [ 'signac = signac.__main__:main', 'signac-gui = signac.gui:main', ], }, )
Fix spec for 0.10 compliance
var banner = require('./'); var chai = require('chai'); var expect = chai.expect; describe('banner', function() { var FILEPATH = 'test-target.js'; context('without options (using defaults)', function() { var expectation = '/*!\n * add-banner <https://github.com/jonschlinkert/add-banner>\n *\n * Copyright (c) 2018 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n */\n\n'; it('expected to populate banner', function() { expect(banner(FILEPATH)).to.eql(expectation); }); }); context('with specific options', function() { var options = { name: 'addbanner', author: 'J. Schlinkert (https://github.com/jonschlinkert)', homepage: 'https://github.com/jonschlinkert/addbanner', banner: 'banner.tmpl', year: '2017', license: 'GPL-3' }; var expectation = '/*!\n * addbanner <https://github.com/jonschlinkert/addbanner>\n *\n * Copyright (c) 2017 J. Schlinkert, contributors.\n * Licensed under the GPL-3 license.\n */\n\n'; it('expected to populate banner', function() { expect(banner(FILEPATH, options)).to.eql(expectation); }); }); });
var banner = require('./'); let chai = require('chai'); let expect = chai.expect; describe('banner', () => { let filepath = 'test-target.js'; context('without options (using defaults)', () => { let expectation = `/*! * add-banner <https://github.com/jonschlinkert/add-banner> * * Copyright (c) 2018 Jon Schlinkert, contributors. * Licensed under the MIT license. */ `; it('expected to populate banner', () => { expect(banner(filepath)).to.eql(expectation); }); }); context('with specific options', () => { let options = { name: 'addbanner', author: 'Jon Schlinkert (https://github.com/jonschlinkert)', homepage: 'https://github.com/jonschlinkert/add-banner', banner: 'banner.tmpl', year: '2017', license: 'GPL-3' }; let expectation = `/*! * addbanner <https://github.com/jonschlinkert/add-banner> * * Copyright (c) 2017 Jon Schlinkert, contributors. * Licensed under the GPL-3 license. */ `; it('expected to populate banner', () => { expect(banner(filepath, options)).to.eql(expectation); }); }); });
Remove forward slashes on path.join call for htpasswd file
'use strict'; const http = require('http'); const path = require('path'); const url = require('url'); const auth = require('http-auth'); const HttpStatusCodes = require('http-status-codes'); const stream_file_to_bd = require('./lib/stream_file_to_bd'); const basic_auth = auth.basic({ realm: 'Vidya', file: path.join(__dirname, 'test', 'test_files', 'htpasswd') }); const app = (request, response) => { const target_url = new url.URL(request.url, 'http://localhost'); if (target_url.pathname !== '/') { return reject_connection(response, HttpStatusCodes.NOT_FOUND); } if (request.method !== 'PUT') { return reject_connection(response, HttpStatusCodes.METHOD_NOT_ALLOWED); } stream_file_to_bd(request) .then(_ => { response.writeHead(HttpStatusCodes.OK, { 'Content-Type': 'text/plain' }); response.end(); }) .catch(_ => { reject_connection(response, HttpStatusCodes.INTERNAL_SERVER_ERROR); }); }; function reject_connection (response, status) { response.writeHead(status, { 'Content-Type': 'text/plain' }); return response.end(); } module.exports = http.createServer(basic_auth.check(app));
'use strict'; const http = require('http'); const path = require('path'); const url = require('url'); const auth = require('http-auth'); const HttpStatusCodes = require('http-status-codes'); const stream_file_to_bd = require('./lib/stream_file_to_bd'); const basic_auth = auth.basic({ realm: 'Vidya', file: path.join(__dirname, '/test/test_files/htpasswd') }); const app = (request, response) => { const target_url = new url.URL(request.url, 'http://localhost'); if (target_url.pathname !== '/') { return reject_connection(response, HttpStatusCodes.NOT_FOUND); } if (request.method !== 'PUT') { return reject_connection(response, HttpStatusCodes.METHOD_NOT_ALLOWED); } stream_file_to_bd(request) .then(_ => { response.writeHead(HttpStatusCodes.OK, { 'Content-Type': 'text/plain' }); response.end(); }) .catch(_ => { reject_connection(response, HttpStatusCodes.INTERNAL_SERVER_ERROR); }); }; function reject_connection (response, status) { response.writeHead(status, { 'Content-Type': 'text/plain' }); return response.end(); } module.exports = http.createServer(basic_auth.check(app));
Fix composer autoload for tests
<?php require_once(dirname(__FILE__) . '/../vendor/autoload.php'); abstract class DataDatabaseTestCase extends PHPUnit_Extensions_Database_TestCase { public function getConnection() { $db = Loader::db(); $pdo = new PDO('mysql:host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_USERNAME, DB_PASSWORD); return $this->createDefaultDBConnection($pdo); } public function getDataSet() { $dir = CONCRETE_5_DATA_TEST_DIR . '/fixtures/'; return new PHPUnit_Extensions_Database_DataSet_CompositeDataSet(array( $this->createMySQLXMLDataSet($dir . 'Config.xml'), $this->createMySQLXMLDataSet($dir . 'Datas.xml'), $this->createMySQLXMLDataSet($dir . 'DataTypes.xml'), $this->createMySQLXMLDataSet($dir . 'DataAttributeKeys.xml'), $this->createMySQLXMLDataSet($dir . 'AttributeKeys.xml') )); } }
<?php require_once "PHPUnit/Extensions/Database/Autoload.php"; abstract class DataDatabaseTestCase extends PHPUnit_Extensions_Database_TestCase { public function getConnection() { $db = Loader::db(); $pdo = new PDO('mysql:host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_USERNAME, DB_PASSWORD); return $this->createDefaultDBConnection($pdo); } public function getDataSet() { $dir = CONCRETE_5_DATA_TEST_DIR . '/fixtures/'; return new PHPUnit_Extensions_Database_DataSet_CompositeDataSet(array( $this->createMySQLXMLDataSet($dir . 'Config.xml'), $this->createMySQLXMLDataSet($dir . 'Datas.xml'), $this->createMySQLXMLDataSet($dir . 'DataTypes.xml'), $this->createMySQLXMLDataSet($dir . 'DataAttributeKeys.xml'), $this->createMySQLXMLDataSet($dir . 'AttributeKeys.xml') )); } }
PWX-5813: Remove whitespace from .stack & .heap filenames. Signed-off-by: Jose Rivera <4a3487e57d90e2084654b6d23937e75af5c8ee55@portworx.com>
package dbg import ( "fmt" "io/ioutil" "os" "runtime" "runtime/pprof" "time" "github.com/sirupsen/logrus" ) const ( path = "/var/cores/" ) // DumpGoMemoryTrace output memory profile to logs. func DumpGoMemoryTrace() { m := &runtime.MemStats{} runtime.ReadMemStats(m) res := fmt.Sprintf("%#v", m) logrus.Infof("==== Dumping Memory Profile ===") logrus.Infof(res) } // DumpGoProfile output goroutines to file. func DumpGoProfile() error { trace := make([]byte, 5120*1024) len := runtime.Stack(trace, true) return ioutil.WriteFile(path+time.Now().Format("2006-01-02T15:04:05.999999-0700MST")+".stack", trace[:len], 0644) } func DumpHeap() { f, err := os.Create(path + time.Now().Format("2006-01-02T15:04:05.999999-0700MST") + ".heap") if err != nil { logrus.Errorf("could not create memory profile: %v", err) return } defer f.Close() if err := pprof.WriteHeapProfile(f); err != nil { logrus.Errorf("could not write memory profile: %v", err) } }
package dbg import ( "fmt" "io/ioutil" "os" "runtime" "runtime/pprof" "time" "github.com/sirupsen/logrus" ) const ( path = "/var/cores/" ) // DumpGoMemoryTrace output memory profile to logs. func DumpGoMemoryTrace() { m := &runtime.MemStats{} runtime.ReadMemStats(m) res := fmt.Sprintf("%#v", m) logrus.Infof("==== Dumping Memory Profile ===") logrus.Infof(res) } // DumpGoProfile output goroutines to file. func DumpGoProfile() error { trace := make([]byte, 5120*1024) len := runtime.Stack(trace, true) return ioutil.WriteFile(path+time.Now().String()+".stack", trace[:len], 0644) } func DumpHeap() { f, err := os.Create(path + time.Now().String() + ".heap") if err != nil { logrus.Errorf("could not create memory profile: %v", err) return } defer f.Close() if err := pprof.WriteHeapProfile(f); err != nil { logrus.Errorf("could not write memory profile: %v", err) } }
Remove unused constant from sink Signed-off-by: Luan Santos <509a85c757dc22c0257f4655fb3fb682d42f965b@pivotal.io>
package lager import ( "io" "sync" ) // A Sink represents a write destination for a Logger. It provides // a thread-safe interface for writing logs type Sink interface { //Log to the sink. Best effort -- no need to worry about errors. Log(level LogLevel, payload []byte) } type writerSink struct { writer io.Writer minLogLevel LogLevel writeL *sync.Mutex } func NewWriterSink(writer io.Writer, minLogLevel LogLevel) Sink { return &writerSink{ writer: writer, minLogLevel: minLogLevel, writeL: new(sync.Mutex), } } func (sink *writerSink) Log(level LogLevel, log []byte) { if level < sink.minLogLevel { return } sink.writeL.Lock() sink.writer.Write(log) sink.writer.Write([]byte("\n")) sink.writeL.Unlock() }
package lager import ( "io" "sync" ) const logBufferSize = 1024 // A Sink represents a write destination for a Logger. It provides // a thread-safe interface for writing logs type Sink interface { //Log to the sink. Best effort -- no need to worry about errors. Log(level LogLevel, payload []byte) } type writerSink struct { writer io.Writer minLogLevel LogLevel writeL *sync.Mutex } func NewWriterSink(writer io.Writer, minLogLevel LogLevel) Sink { return &writerSink{ writer: writer, minLogLevel: minLogLevel, writeL: new(sync.Mutex), } } func (sink *writerSink) Log(level LogLevel, log []byte) { if level < sink.minLogLevel { return } sink.writeL.Lock() sink.writer.Write(log) sink.writer.Write([]byte("\n")) sink.writeL.Unlock() }
Allow upgrade of transaction from readonly to exclusive
/** * Copyright 2010 - 2017 JetBrains s.r.o. * * 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 jetbrains.exodus.entitystore; import org.jetbrains.annotations.NotNull; public class ReadonlyPersistentStoreTransaction extends PersistentStoreTransaction { ReadonlyPersistentStoreTransaction(@NotNull final PersistentEntityStoreImpl store) { super(store, TransactionType.Readonly); } @Override public boolean isIdempotent() { if (!super.isIdempotent()) { throw new IllegalStateException("ReadonlyPersistentStoreTransaction should be idempotent"); } return true; } public PersistentStoreTransaction getUpgradedTransaction(boolean exclusive) { return new PersistentStoreTransaction(this, exclusive ? TransactionType.Exclusive : TransactionType.Regular); } public PersistentStoreTransaction getUpgradedTransaction() { return getUpgradedTransaction(false); } }
/** * Copyright 2010 - 2017 JetBrains s.r.o. * * 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 jetbrains.exodus.entitystore; import org.jetbrains.annotations.NotNull; public class ReadonlyPersistentStoreTransaction extends PersistentStoreTransaction { ReadonlyPersistentStoreTransaction(@NotNull final PersistentEntityStoreImpl store) { super(store, TransactionType.Readonly); } @Override public boolean isIdempotent() { if (!super.isIdempotent()) { throw new IllegalStateException("ReadonlyPersistentStoreTransaction should be idempotent"); } return true; } public PersistentStoreTransaction getUpgradedTransaction() { return new PersistentStoreTransaction(this, TransactionType.Regular); } }
Test case for step function in time series Test a graph function that is linear in two time periods, jumping between linear values.
from wordgraph.points import Point import wordgraph EPOCH_START = 1407109280 def time_values(values, start=EPOCH_START, increment=1): datapoints = [] for index, value in enumerate(values): datapoints.append(Point(x=value, y=start + (increment * index))) return datapoints def test_monotonic_up_per_second(): datapoints = time_values(float(i) for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_monotonic_down_per_second(): datapoints = time_values(10.0 - i for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_tent_map(): values = [float(i) for i in range(10)] values.append(11.0) values += [10.0 - i for i in range(10)] datapoints = time_values(values) features = wordgraph.describe(datapoints) assert "" in features def test_step_function(): values = [1.0] * 10 values += [2.0] * 10 datapoints = time_values(values) features = wordgraph.describe(datapoints) assert "" in features
from wordgraph.points import Point import wordgraph EPOCH_START = 1407109280 def time_values(values, start=EPOCH_START, increment=1): datapoints = [] for index, value in enumerate(values): datapoints.append(Point(x=value, y=start + (increment * index))) return datapoints def test_monotonic_up_per_second(): datapoints = time_values(float(i) for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_monotonic_down_per_second(): datapoints = time_values(10.0 - i for i in range(10)) features = wordgraph.describe(datapoints) assert "" in features def test_tent_map(): values = list(float(i) for i in range(10)) values.append(11.0) values+= list(10.0 - i for i in range(10)) datapoints = time_values(values) features = wordgraph.describe(datapoints) assert "" in features
Refactor to make code more readable.
package gohandy import ( "archive/tar" "io" "os" "path/filepath" ) func Unpack(r *tar.Reader, toPath string) error { for { hdr, err := r.Next() switch { case err == io.EOF: break case err != nil: return err default: if err := doOnType(hdr.Typeflag, toPath, hdr.Name, r); err != nil { return err } } } return nil } func doOnType(typeFlag byte, toPath string, name string, r *tar.Reader) error { fullpath := filepath.Join(toPath, name) switch typeFlag { case tar.TypeReg, tar.TypeRegA: return writeFile(fullpath, r) case tar.TypeDir: return os.MkdirAll(fullpath, 0777) default: return nil } } func writeFile(path string, r *tar.Reader) error { out, err := os.Create(path) if err != nil { return err } defer out.Close() _, err = io.Copy(out, r) return err }
package gohandy import ( "archive/tar" "io" "os" "path/filepath" ) func Unpack(r *tar.Reader, toPath string) error { for { hdr, err := r.Next() if err == io.EOF { break } if err != nil { return err } err = nil if hdr.Typeflag == tar.TypeDir { dirpath := filepath.Join(toPath, hdr.Name) err = os.MkdirAll(dirpath, 0777) } else if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA { err = writeFile(toPath, hdr.Name, r) } if err != nil { return nil } } return nil } func writeFile(toPath, filename string, r *tar.Reader) error { path := filepath.Join(toPath, filename) out, err := os.Create(path) if err != nil { return err } defer out.Close() if _, err := io.Copy(out, r); err != nil { return err } return nil }
Add persist method to the Interface
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter; use Doctrine\Common\Collections\Collection; use CalendArt\AbstractEvent, CalendArt\AbstractCalendar; /** * Handle the dialog with the adapter's api for its events * * @author Baptiste Clavié <baptiste@wisembly.com> */ interface EventApiInterface { /** * Get all the events available on the selected calendar * * @return Collection<AbstractEvent> */ public function getList(AbstractCriterion $criterion = null); /** * Returns the specific information for a given event * * @param mixed $identifier Identifier of the event to fetch * * @return AbstractEvent */ public function get($identifier, AbstractCriterion $criterion = null); /** * Get the associated calendar for this api * * @return AbstractCalendar */ public function getCalendar(); /** * @param AbstractEvent $event * * @return AbstractEvent */ public function persist(AbstractEvent $event); }
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter; use Doctrine\Common\Collections\Collection; use CalendArt\AbstractEvent, CalendArt\AbstractCalendar; /** * Handle the dialog with the adapter's api for its events * * @author Baptiste Clavié <baptiste@wisembly.com> */ interface EventApiInterface { /** * Get all the events available on the selected calendar * * @return Collection<AbstractEvent> */ public function getList(AbstractCriterion $criterion = null); /** * Returns the specific information for a given event * * @param mixed $identifier Identifier of the event to fetch * * @return AbstractEvent */ public function get($identifier, AbstractCriterion $criterion = null); /** * Get the associated calendar for this api * * @return AbstractCalendar */ public function getCalendar(); }
Add tip about getProcessorArguments implementation
<?php namespace Swarrot\SwarrotBundle\Processor; use Symfony\Component\Console\Input\InputInterface; interface ProcessorConfiguratorInterface { /** * Define extra parameters to the configurator. * * @param array $extras */ public function setExtras(array $extras); /** * Retrieves the processor's class name and list of constructors arguments. * The class name should be first, and is mandatory. * * @param array $options * * @return array */ public function getProcessorArguments(array $options); /** * Retrieves the list of additional options to add to the CLI command. * * @return array */ public function getCommandOptions(); /** * Resolve user input parameters to returns an array of options. * * @param InputInterface $input * * @return array */ public function resolveOptions(InputInterface $input); /** * @return bool */ public function isEnabled(); }
<?php namespace Swarrot\SwarrotBundle\Processor; use Symfony\Component\Console\Input\InputInterface; interface ProcessorConfiguratorInterface { /** * Define extra parameters to the configurator. * * @param array $extras */ public function setExtras(array $extras); /** * Retrieves the processor's class name and list of constructors arguments. * * @param array $options * * @return array */ public function getProcessorArguments(array $options); /** * Retrieves the list of additional options to add to the CLI command. * * @return array */ public function getCommandOptions(); /** * Resolve user input parameters to returns an array of options. * * @param InputInterface $input * * @return array */ public function resolveOptions(InputInterface $input); /** * @return bool */ public function isEnabled(); }
Use iter's sentinel arg instead of infinite loop
from functools import partial from itertools import imap from itertools import islice from operator import itemgetter def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) for items_batch in iter(lambda: tuple(islice(iterable_items, max_size)), tuple()): yield items_batch
from functools import partial from itertools import imap from itertools import islice from operator import itemgetter def yield_getter_of(getter_maker, iterator): """ Iteratively map iterator over the result of getter_maker. :param getter_maker: function that returns a getter function. :param iterator: An iterator. """ return imap(getter_maker(), iterator) def yield_nth_of(nth, iterator): """ For an iterator that returns sequences, yield the nth value of each. :param nth: Index desired column of each sequence. :type nth: int :param iterator: iterator of sequences. """ return yield_getter_of(partial(itemgetter, nth), iterator) def i_batch(max_size, iterable): """ Generator that iteratively batches items to a max size and consumes the items iterable as each batch is yielded. :param max_size: Max size of each batch. :type max_size: int :param iterable: An iterable :type iterable: iter """ iterable_items = iter(iterable) while True: items_batch = tuple(islice(iterable_items, max_size)) if not items_batch: break yield items_batch
Fix naming in authentication filter.
/** * This source file is subject to the license that is bundled with this package in the file LICENSE. */ package com.codeup.auth.filters; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class AuthenticationFilter implements Filter { private String redirectTo; public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws ServletException, IOException { HttpSession session = ((HttpServletRequest) request).getSession(false); if (session == null || session.getAttribute("user") == null) { ((HttpServletResponse) response).sendRedirect(redirectTo); } else { chain.doFilter(request, response); } } public void destroy() { } public void init(FilterConfig config) throws ServletException { redirectTo = config.getInitParameter("redirectTo"); } }
/** * This source file is subject to the license that is bundled with this package in the file LICENSE. */ package com.codeup.auth.filters; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class AuthenticationFilter implements Filter { private String redirectTo; public void doFilter( ServletRequest req, ServletResponse resp, FilterChain chain ) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpSession session = request.getSession(false); if (session == null || session.getAttribute("user") == null) { ((HttpServletResponse) resp).sendRedirect(redirectTo); } else { chain.doFilter(req, resp); } } public void destroy() { } public void init(FilterConfig config) throws ServletException { redirectTo = config.getInitParameter("redirectTo"); } }
Set required in files related
<?php class RelatedFileForm extends BaseForm { public function configure() { $this->widgetSchema['filenames'] = new sfWidgetFormInputFile(); $this->widgetSchema['filenames']->setLabel("Add File") ; $this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file')); $this->validatorSchema['filenames'] = new sfValidatorFile( array( 'required' => true, //'mime_type_guessers' => array('guessFromFileinfo'), 'validated_file_class' => 'myValidatedFile' )); $this->validatorSchema['filenames']->setOption('mime_type_guessers', array( array($this->validatorSchema['filenames'], 'guessFromFileinfo'), array($this->validatorSchema['filenames'], 'guessFromFileBinary'), array($this->validatorSchema['filenames'], 'guessFromMimeContentType') )); } }
<?php class RelatedFileForm extends BaseForm { public function configure() { $this->widgetSchema['filenames'] = new sfWidgetFormInputFile(); $this->widgetSchema['filenames']->setLabel("Add File") ; $this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file')); $this->validatorSchema['filenames'] = new sfValidatorFile( array( 'required' => false, //'mime_type_guessers' => array('guessFromFileinfo'), 'validated_file_class' => 'myValidatedFile' )); $this->validatorSchema['filenames']->setOption('mime_type_guessers', array( array($this->validatorSchema['filenames'], 'guessFromFileinfo'), array($this->validatorSchema['filenames'], 'guessFromFileBinary'), array($this->validatorSchema['filenames'], 'guessFromMimeContentType') )); } }
INC-181: Format code via `./gradlew spotlessApply`
/* * Maintained by brightSPARK Labs. * www.brightsparklabs.com * * Refer to LICENSE at repository root for license details. */ package com.brightsparklabs.assam.validator; import com.brightsparklabs.assam.selector.Selector; /** * Combines a {@link Selector}, with the ability to provide a respective {@link Validator} if the * selection criteria is met. * * @author brightSPARK Labs */ public interface ValidatorSelector extends Selector { // ------------------------------------------------------------------------- // CONSTANTS // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // CLASS VARIABLES // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // PUBLIC METHODS // ------------------------------------------------------------------------- /** * Allows a ValidationRule to be associated with a Selector. * * @return the wrapped ValidationRule. */ ValidationRule getValidator(); }
/* * Maintained by brightSPARK Labs. * www.brightsparklabs.com * * Refer to LICENSE at repository root for license details. */ package com.brightsparklabs.assam.validator; import com.brightsparklabs.assam.selector.Selector; /** * Combines a {@link Selector}, with the ability to provide a respective {@link Validator} if the selection criteria is * met. * * @author brightSPARK Labs */ public interface ValidatorSelector extends Selector { // ------------------------------------------------------------------------- // CONSTANTS // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // CLASS VARIABLES // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // PUBLIC METHODS // ------------------------------------------------------------------------- /** * Allows a ValidationRule to be associated with a Selector. * * @return the wrapped ValidationRule. */ ValidationRule getValidator(); }
Make the version and timeout constants part of the prototype They don't need to be set in the constructor
var debug = require( 'debug' )( 'wpcom-vip' ); var request = require( './lib/util/request' ); // Modules function WPCOM_VIP( token ) { this.req = new Request( this ); } WPCOM_VIP.prototype.API_VERSION = '1'; WPCOM_VIP.prototype.API_TIMEOUT = 10000; WPCOM_VIP.prototype.req = new Request(); WPCOM_VIP.prototype.get = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.post = function() { return this.req.post.apply( arguments ); }; WPCOM_VIP.prototype.put = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.delete = function() { return this.req.delete.apply( arguments ); }; module.exports = WPCOM_VIP;
var debug = require( 'debug' )( 'wpcom-vip' ); var request = require( './lib/util/request' ); // Modules function WPCOM_VIP( token ) { this.API_VERSION = '1'; this.API_TIMEOUT = 10000; this.req = new Request( this ); } WPCOM_VIP.prototype.req = new Request(); WPCOM_VIP.prototype.get = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.post = function() { return this.req.post.apply( arguments ); }; WPCOM_VIP.prototype.put = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.delete = function() { return this.req.delete.apply( arguments ); }; module.exports = WPCOM_VIP;
Use typeof instead of isCallable
// Internal method, used by iteration functions. // Calls a function for each key-value pair found in object // Optionally takes compareFn to iterate object in specific order 'use strict'; var callable = require('./valid-callable') , value = require('./valid-value') , bind = Function.prototype.bind, call = Function.prototype.call, keys = Object.keys , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (method, defVal) { return function (obj, cb/*, thisArg, compareFn*/) { var list, thisArg = arguments[2], compareFn = arguments[3]; obj = Object(value(obj)); callable(cb); list = keys(obj); if (compareFn) { list.sort((typeof compareFn === 'function') ? bind.call(compareFn, obj) : undefined); } return list[method](function (key, index) { if (!propertyIsEnumerable.call(obj, key)) return defVal; return call.call(cb, thisArg, obj[key], key, obj, index); }); }; };
// Internal method, used by iteration functions. // Calls a function for each key-value pair found in object // Optionally takes compareFn to iterate object in specific order 'use strict'; var isCallable = require('./is-callable') , callable = require('./valid-callable') , value = require('./valid-value') , call = Function.prototype.call, keys = Object.keys , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (method, defVal) { return function (obj, cb/*, thisArg, compareFn*/) { var list, thisArg = arguments[2], compareFn = arguments[3]; obj = Object(value(obj)); callable(cb); list = keys(obj); if (compareFn) { list.sort(isCallable(compareFn) ? compareFn.bind(obj) : undefined); } return list[method](function (key, index) { if (!propertyIsEnumerable.call(obj, key)) return defVal; return call.call(cb, thisArg, obj[key], key, obj, index); }); }; };
Fix channel updating (Well, that was dumb)
'use strict' const TelegramBot = require('node-telegram-bot-api'); const config = require('../config'); const utils = require('./utils'); const Kinospartak = require('./Kinospartak/Kinospartak'); const bot = new TelegramBot(config.TOKEN); const kinospartak = new Kinospartak(); /** * updateSchedule - update schedule and push updates to Telegram channel * * @return {Promise} */ function updateSchedule() { return kinospartak.getChanges() .then(changes => changes.length ? utils.formatSchedule(changes) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.commitChanges()) }; /** * updateNews - update news and push updates to Telegram channel * * @return {Promise} */ function updateNews() { return kinospartak.getLatestNews() .then(news => news.length ? utils.formatNews(news) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.setNewsOffset(new Date().toString())) }; function update() { return Promise.all([ updateSchedule(), updateNews() ]).catch((err) => { setTimeout(() => { update(); }, 1000 * 60 * 5); }) } update();
'use strict' const TelegramBot = require('node-telegram-bot-api'); const config = require('../config'); const utils = require('./utils'); const Kinospartak = require('./Kinospartak/Kinospartak'); const bot = new TelegramBot(config.TOKEN); const kinospartak = new Kinospartak(); /** * updateSchedule - update schedule and push updates to Telegram channel * * @return {Promise} */ function updateSchedule() { return kinospartak.getChanges() .then(changes => changes.length ? utils.formatSchedule(changes) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.commitChanges()) }; /** * updateNews - update news and push updates to Telegram channel * * @return {Promise} */ function updateNews() { return kinospartak.getLatestNews() .then(news => news.length ? utils.formatNews(news) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.setNewsOffset(new Date().toString())) }; function update() { return Promise.all([ updateSchedule, updateNews ]).catch((err) => { setTimeout(() => { update(); }, 1000 * 60 * 5); }) } update();
Switch to packages instead of extensions and theme
import { combineReducers } from 'redux'; import * as types from '../types'; const packages = (state = {}, action) => { if (action.type === types.BUILD_UPDATED && action.packages) return action.packages; return state; } const siteId = (state = null, action) => { if (action.type === types.BUILD_UPDATED && action.siteId) return action.siteId; return state; }; const environment = (state = 'pre', action) => { if (action.type === types.BUILD_UPDATED && action.environment) return action.environment; return state; }; const amp = (state = false, action) => { if (action.type === types.BUILD_UPDATED && action.amp) return action.amp; return state; }; const ssr = (state = true, action) => { if (action.type === types.CLIENT_RENDERED) return false; return state; }; export default combineReducers({ ssr, siteId, environment, amp, packages, });
import { combineReducers } from 'redux'; import { omit, find } from 'lodash'; import * as types from '../types'; export const extensions = (state = [], action) => { if (action.type === types.BUILD_UPDATED && action.packages) return omit(action.packages, ['theme']); return state; }; export const theme = (state = '', action) => { if (action.type === types.BUILD_UPDATED && action.packages) return find(action.packages, (name, namespace) => namespace === 'theme'); return state; }; const siteId = (state = null, action) => { if (action.type === types.BUILD_UPDATED && action.siteId) return action.siteId; return state; }; const environment = (state = 'pre', action) => { if (action.type === types.BUILD_UPDATED && action.environment) return action.environment; return state; }; const amp = (state = false, action) => { if (action.type === types.BUILD_UPDATED && action.amp) return action.amp; return state; }; const ssr = (state = true, action) => { if (action.type === types.CLIENT_RENDERED) return false; return state; }; export default combineReducers({ extensions, theme, ssr, siteId, environment, amp, });
Move sound initialization up before showing the window.
package hypernova; import javax.swing.JFrame; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import hypernova.gui.Viewer; public class Hypernova { public static final String TITLE = "Hypernova"; public static Universe universe; private static Viewer viewer; public static boolean debug = false; private static Logger log = Logger.getRootLogger(); public static void main(String[] args) { /* Fix for poor OpenJDK performance. */ System.setProperty("sun.java2d.pmoffscreen", "false"); /* Prepare logging. */ BasicConfigurator.configure(); if (debug) log.setLevel(Level.TRACE); Sound.init(); universe = new Universe(); viewer = new Viewer(universe); JFrame frame = new JFrame(TITLE); frame.add(viewer); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); viewer.requestFocusInWindow(); universe.start(); } }
package hypernova; import javax.swing.JFrame; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import hypernova.gui.Viewer; public class Hypernova { public static final String TITLE = "Hypernova"; public static Universe universe; private static Viewer viewer; public static boolean debug = false; private static Logger log = Logger.getRootLogger(); public static void main(String[] args) { /* Fix for poor OpenJDK performance. */ System.setProperty("sun.java2d.pmoffscreen", "false"); /* Prepare logging. */ BasicConfigurator.configure(); if (debug) log.setLevel(Level.TRACE); universe = new Universe(); viewer = new Viewer(universe); JFrame frame = new JFrame(TITLE); frame.add(viewer); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); viewer.requestFocusInWindow(); Sound.init(); universe.start(); } }
Fix "undefined function" bug when iterating an object created with Object.create(null)
/* * Module requirements. */ var isArray = require('isarray'); /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Right now only Buffer and ArrayBuffer are supported.. * * @param {Object} anything * @api public */ function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { if (obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); }
/* * Module requirements. */ var isArray = require('isarray'); /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Right now only Buffer and ArrayBuffer are supported.. * * @param {Object} anything * @api public */ function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { if (obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); }
Remove unnecessary constructor 쓰이지 않는 생성자
package cloud.swiftnode.kspam.util; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; /** * Created by EntryPoint on 2017-01-05. */ public enum URLs { COMMUNITY_API("http://kspam.swiftnode.cloud/mcbanip/community.php?ip={0}"), SHROOMERY_API("http://www.shroomery.org/ythan/proxycheck.php?ip={0}"), STOPFORUM_API("http://www.stopforumspam.com/api?ip={0}"), BOTSCOUT_API("http://www.botscout.com/test/?ip={0}"), MCBLACKLIST_API("http://api.mc-blacklist.kr/API/check/{0}"), MOJANG_UUID_API("https://api.mojang.com/users/profiles/minecraft/{0}?at={1}"), CACHE("https://github.com/EntryPointKR/K-SPAM/blob/master/K-Spam.cache?raw=true"); private final String addr; URLs(String addr) { this.addr = addr; } @Override public String toString() { return addr; } public URL toUrl() throws MalformedURLException { return toUrl(""); } public URL toUrl(Object... value) throws MalformedURLException { String addr = MessageFormat.format(this.addr, value); return new URL(addr); } }
package cloud.swiftnode.kspam.util; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; /** * Created by EntryPoint on 2017-01-05. */ public enum URLs { COMMUNITY_API("http://kspam.swiftnode.cloud/mcbanip/community.php?ip={0}"), SHROOMERY_API("http://www.shroomery.org/ythan/proxycheck.php?ip={0}"), STOPFORUM_API("http://www.stopforumspam.com/api?ip={0}"), BOTSCOUT_API("http://www.botscout.com/test/?ip={0}"), MCBLACKLIST_API("http://api.mc-blacklist.kr/API/check/{0}"), MOJANG_UUID_API("https://api.mojang.com/users/profiles/minecraft/{0}?at={1}"), GRADLE("https://raw.githubusercontent.com/EntryPointKR/K-SPAM/master/build.gradle"), CACHE("https://github.com/EntryPointKR/K-SPAM/blob/master/K-Spam.cache?raw=true"); private final String addr; URLs(String addr) { this.addr = addr; } @Override public String toString() { return addr; } public URL toUrl() throws MalformedURLException { return toUrl(""); } public URL toUrl(Object... value) throws MalformedURLException { String addr = MessageFormat.format(this.addr, value); return new URL(addr); } }
EventPage.js: Fix storage call from local to sync
chrome.runtime.onMessage.addListener( function(echo, sender, sendResponse) { var promise = new Promise(function(resolve, reject) { chrome.identity.getProfileUserInfo(function(userInfo) { echo['google_credentials'] = userInfo.email; }); chrome.storage.sync.get('chrome_token', function(items) { echo['chrome_token'] = items.chrome_token }); echo['url'] = sender.url var timer = setInterval(function() { if (echo['google_credentials'] != null && echo['chrome_token'] != null && echo['url'] != null) { resolve(echo); clearInterval(timer); } }, 100) }).then(function(value) { var message = JSON.stringify(echo); var xml = new XMLHttpRequest(); xml.open("POST", "http://localhost:3000/api/echos", true); xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xml.send(message); sendResponse({ message: "Message: " + message }, function(reason) { }); }); });
chrome.runtime.onMessage.addListener( function(echo, sender, sendResponse) { var promise = new Promise(function(resolve, reject) { chrome.identity.getProfileUserInfo(function(userInfo) { echo['google_credentials'] = userInfo.email; }); chrome.storage.local.get('chrome_token', function(items) { echo['chrome_token'] = items.chrome_token }); echo['url'] = sender.url var timer = setInterval(function() { if (echo['google_credentials'] != null && echo['chrome_token'] != null && echo['url'] != null) { resolve(echo); clearInterval(timer); } }, 100) }).then(function(value) { var message = JSON.stringify(echo); var xml = new XMLHttpRequest(); xml.open("POST", "http://localhost:3000/api/echos", true); xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xml.send(message); sendResponse({ message: "Message: " + message }, function(reason) { }); }); });
Support multiple import methods and add Forth.pass.
var Forth = require("../forth"), forth = Forth.go ( function start (callforth) { var result = [1, 2, 3]; callforth.report(null, Date.now()); callforth.report(null, Date.now()); callforth.report(null, Date.now()); if (Date.now() % 3) { callforth ( null, result ); result.push(4); // NOTE: callforth is delayed } else { callforth ( new Error("bad"), null ); } } ); forth.good ( function success (callforth, data) { console.log(["success", data]); } ).bad( function die (err, callforth) { console.log(["die", err]); callforth(err, [5, 6, 7, 8]); }).last( function after (callforth, err, data) { console.log(["after", err, data]); }); forth.bad ( function fail (err, callforth) { console.log(["fail", err]); } ); forth.status( function progress (callforth, warn, info) { console.log(["progress", warn, info]); } ); forth = forth.pass (); forth.bad ( function either (err, callforth) { console.log(["either", err]); }); forth.good ( function or (callforth, data) { console.log(["or", data]); }).bad ( function not (err, callback) { console.log(["not", err]); });
var Forth = require("../forth"), forth = Forth.go ( function start (callforth) { setTimeout(function () { callforth.report(null, Date.now()); callforth.report(null, Date.now()); callforth.report(null, Date.now()); if (Date.now() % 3) { callforth ( null, [1, 2, 3] ); } else { callforth ( new Error("bad"), null ); } }, 0); } ); forth.good ( function success (callforth, data) { console.log(["success", data]); } ).bad( function die (err, callforth) { console.log(["die", err]); callforth.apply(null, arguments); }).last( function end (callforth, err, data) { console.log(["end", err, data]); }); forth.bad ( function fail (err, callforth) { console.log(["fail", err]); } ); forth.status( function progress (callforth, warn, info) { console.log(["progress", warn, info]); } );
Remove oauth_provider as that's the eggname for django-oauth-plus.
#!/usr/bin/env python from distutils.core import setup setup(name='SpaceScout-Server', version='1.0', description='REST Backend for SpaceScout', install_requires=[ 'Django>=1.7,<1.8', 'mock<=1.0.1', 'oauth2<=1.5.211', 'Pillow', 'pyproj', 'pytz', 'South', 'simplejson>=2.1', 'django-oauth-plus<=2.2.5', 'phonenumbers' ], )
#!/usr/bin/env python from distutils.core import setup setup(name='SpaceScout-Server', version='1.0', description='REST Backend for SpaceScout', install_requires=[ 'Django>=1.7,<1.8', 'mock<=1.0.1', 'oauth2<=1.5.211', 'oauth_provider', 'Pillow', 'pyproj', 'pytz', 'South', 'simplejson>=2.1', 'django-oauth-plus<=2.2.5', 'phonenumbers' ], )
Add TODO when PAX CDI will support global interceptors
/** * 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.camel.cdi.sample.metrics; import com.codahale.metrics.Meter; import org.apache.camel.Exchange; import org.apache.camel.RuntimeExchangeException; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class UnreliableService { @Inject private Meter attempt; //@Metered // TODO: to activate when global interceptors are supported in PAX CDI public void attempt(Exchange exchange) { attempt.mark(); if (Math.random() < 0.5) throw new RuntimeExchangeException("Random failure", exchange); } }
/** * 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.camel.cdi.sample.metrics; import com.codahale.metrics.Meter; import org.apache.camel.Exchange; import org.apache.camel.RuntimeExchangeException; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class UnreliableService { @Inject private Meter attempt; public void unreliable(Exchange exchange) { attempt.mark(); if (Math.random() < 0.5) throw new RuntimeExchangeException("Random failure", exchange); } }
Remove unused import in test
import urlparse from django.test import TestCase, override_settings from mock import patch, Mock from opendebates.context_processors import global_vars from opendebates.tests.factories import SubmissionFactory class NumberOfVotesTest(TestCase): def test_number_of_votes(self): mock_request = Mock() with patch('opendebates.utils.cache') as mock_cache: mock_cache.get.return_value = 2 context = global_vars(mock_request) self.assertEqual(2, int(context['NUMBER_OF_VOTES'])) class ThemeTests(TestCase): def setUp(self): self.idea = SubmissionFactory() @override_settings(SITE_THEME={'HASHTAG': 'TestHashtag'}) def test_email_url(self): email_url = self.idea.email_url() fields = urlparse.parse_qs(urlparse.urlparse(email_url).query) self.assertTrue('subject' in fields, fields) self.assertTrue('#TestHashtag' in fields['subject'][0], fields['subject'][0])
import urlparse from django.test import TestCase, override_settings from django.conf import settings from mock import patch, Mock from opendebates.context_processors import global_vars from opendebates.tests.factories import SubmissionFactory class NumberOfVotesTest(TestCase): def test_number_of_votes(self): mock_request = Mock() with patch('opendebates.utils.cache') as mock_cache: mock_cache.get.return_value = 2 context = global_vars(mock_request) self.assertEqual(2, int(context['NUMBER_OF_VOTES'])) class ThemeTests(TestCase): def setUp(self): self.idea = SubmissionFactory() @override_settings(SITE_THEME={'HASHTAG': 'TestHashtag'}) def test_email_url(self): email_url = self.idea.email_url() fields = urlparse.parse_qs(urlparse.urlparse(email_url).query) self.assertTrue('subject' in fields, fields) self.assertTrue('#TestHashtag' in fields['subject'][0], fields['subject'][0])
Revert "Revert "Revert "Changed back due to problems, will fix later""" This reverts commit 4b35247fe384d4b2b206fa7650398511a493253c.
from distutils.core import setup import sys import os import re PACKAGENAME = 'OpSimSummary' packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'opsimsummary') versionFile = os.path.join(packageDir, 'version.py') # Obtain the package version with open(versionFile, 'r') as f: s = f.read() # Look up the string value assigned to __version__ in version.py using regexp versionRegExp = re.compile("__VERSION__ = \"(.*?)\"") # Assign to __version__ __version__ = versionRegExp.findall(s)[0] print(__version__) setup(# package information name=PACKAGENAME, version=__version__, description='simple repo to study OpSim output summaries', long_description=''' ''', # What code to include as packages packages=[PACKAGENAME], packagedir={PACKAGENAME: 'opsimsummary'}, # What data to include as packages include_package_data=True, package_data={PACKAGENAME:['example_data/*.dat', 'example_data/*.simlib']} )
from distutils.core import setup import sys import os import re PACKAGENAME = 'OpSimSummary' packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), PACKAGENAME) versionFile = os.path.join(packageDir, 'version.py') # Obtain the package version with open(versionFile, 'r') as f: s = f.read() # Look up the string value assigned to __version__ in version.py using regexp versionRegExp = re.compile("__VERSION__ = \"(.*?)\"") # Assign to __version__ __version__ = versionRegExp.findall(s)[0] print(__version__) setup(# package information name=PACKAGENAME, version=__version__, description='simple repo to study OpSim output summaries', long_description=''' ''', # What code to include as packages packages=[PACKAGENAME], packagedir={PACKAGENAME: 'opsimsummary'}, # What data to include as packages include_package_data=True, package_data={PACKAGENAME:['example_data/*.dat', 'example_data/*.simlib']} )
Fix insecure youtube embed url
import React from 'react'; const caontinerStyle = { position: 'relative', paddingBottom: '56.25%', // 16:9 paddingTop: 25, height: 0 }; const videoStyle = { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }; const VideoInstruction = function(props) { const opts = { width: '100%' // This matches the width of the other responses }; // If multiple players get used on a page, this needs a unique id if (props.videoId) { console.log('rendering video'); return ( <div style={caontinerStyle}> <iframe style={videoStyle} id="youtube-player" type="text/html" width="640" height="390" src={'https://www.youtube.com/embed/' + props.videoId + '?autoplay=0'} frameborder="0"/> </div> ); } else { return ( <div style={caontinerStyle}> <iframe style={videoStyle} /> </div> ); } } export default VideoInstruction;
import React from 'react'; const caontinerStyle = { position: 'relative', paddingBottom: '56.25%', // 16:9 paddingTop: 25, height: 0 }; const videoStyle = { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }; const VideoInstruction = function(props) { const opts = { width: '100%' // This matches the width of the other responses }; // If multiple players get used on a page, this needs a unique id if (props.videoId) { console.log('rendering video'); return ( <div style={caontinerStyle}> <iframe style={videoStyle} id="youtube-player" type="text/html" width="640" height="390" src={'http://www.youtube.com/embed/' + props.videoId + '?autoplay=0'} frameborder="0"/> </div> ); } else { return ( <div style={caontinerStyle}> <iframe style={videoStyle} /> </div> ); } } export default VideoInstruction;
Clean up input and output.
#!/usr/bin/python import os import sys import json import getpass import tempfile import subprocess import aesjsonfile def editfile(fn, password): db = aesjsonfile.load(fn, password) f = tempfile.NamedTemporaryFile() json.dump(db, f, indent=2) f.flush() while True: subprocess.call([os.getenv("EDITOR") or "editor", f.name]) try: f.seek(0) db = json.load(f) aesjsonfile.dump(fn, db, password) break except Exception, e: print "Error in json" print e print "Try again (y/n)? ", input = raw_input() if not input.lower().startswith("y"): break f.seek(0,2) len = f.tell() f.seek(0) f.write(" " * len) f.flush() f.close() if __name__ == "__main__": if len(sys.argv) < 2: sys.exit(1) fn = sys.argv[1] password = getpass.getpass() editfile(fn, password)
#!/usr/bin/python import os import sys import json import getpass import tempfile import subprocess import aesjsonfile def editfile(fn, password): db = aesjsonfile.load(fn, password) f = tempfile.NamedTemporaryFile() json.dump(db, f, indent=2) f.flush() while True: subprocess.call([os.getenv("EDITOR") or "editor", f.name]) try: f.seek(0) db = json.load(f) aesjsonfile.dump(fn, db, password) break except Exception, e: print "Error in json" print e print "Try again (y/n)? ", input = sys.stdin.readline() if not input.lower().startswith("y"): break f.seek(0,2) len = f.tell() print len f.seek(0) f.write(" " * len) f.flush() f.close() if __name__ == "__main__": if len(sys.argv) < 2: sys.exit(1) fn = sys.argv[1] password = getpass.getpass() editfile(fn, password)
Fix exception when one error is thrown during startup
#!/usr/bin/env node var argv = require('minimist')(process.argv.slice(2)); var injection = require('./services/injection'); var _ = require('lodash'); var port = argv.port || process.env.PORT || 9080; var gitUrl = argv.git || process.env.GIT_URL; var dbUrl = argv.db || process.env.DB_URL; if (!gitUrl || !dbUrl) { console.log('Usage: allcountjs --git <Application Git URL> --db <Application MongoDB URL> -port [Application HTTP port]'); process.exit(0); } require('./allcount-server.js'); injection.bindFactory('port', port); injection.bindFactory('dbUrl', dbUrl); if (dbUrl.indexOf('postgres') !== -1) { injection.bindFactory('storageDriver', require('./services/sql-storage-driver')); injection.bindFactory('dbClient', 'pg'); } injection.bindFactory('gitRepoUrl', gitUrl); injection.installModulesFromPackageJson("package.json"); var server = injection.inject('allcountServerStartup'); server.startup(function (errors) { if (errors) { if (_.isArray(errors)) { throw new Error(errors.join('\n')); } else { throw errors; } } });
#!/usr/bin/env node var argv = require('minimist')(process.argv.slice(2)); var injection = require('./services/injection'); var _ = require('lodash'); var port = argv.port || process.env.PORT || 9080; var gitUrl = argv.git || process.env.GIT_URL; var dbUrl = argv.db || process.env.DB_URL; if (!gitUrl || !dbUrl) { console.log('Usage: allcountjs --git <Application Git URL> --db <Application MongoDB URL> -port [Application HTTP port]'); process.exit(0); } require('./allcount-server.js'); injection.bindFactory('port', port); injection.bindFactory('dbUrl', dbUrl); if (dbUrl.indexOf('postgres') !== -1) { injection.bindFactory('storageDriver', require('./services/sql-storage-driver')); injection.bindFactory('dbClient', 'pg'); } injection.bindFactory('gitRepoUrl', gitUrl); injection.installModulesFromPackageJson("package.json"); var server = injection.inject('allcountServerStartup'); server.startup(function (errors) { if (errors) { if (_.isObject(errors)) { throw new Error(errors); } else { throw new Error(errors.join('\n')); } } });
Fix call to stock instead of run
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # 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 argparse import socket from gearstore import stocker def main(): parser = argparse.ArgumentParser() parser.add_argument('servers', nargs='+', help='Servers to connect to, ' ' format of host/port') parser.add_argument('--sqlalchemy-dsn', help='SQLAlchemy DSN to store in') args = parser.parse_args() stkr = stocker.Stocker( client_id=socket.gethostname(), dsn=args.sqlalchemy_dsn) for s in args.servers: if '/' in s: (host, port) = s.split('/', 2) else: host = s port = None stkr.addServer(host, port) stkr.waitForServer() while True: stkr.stock() stkr.ship()
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # 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 argparse import socket from gearstore import stocker def main(): parser = argparse.ArgumentParser() parser.add_argument('servers', nargs='+', help='Servers to connect to, ' ' format of host/port') parser.add_argument('--sqlalchemy-dsn', help='SQLAlchemy DSN to store in') args = parser.parse_args() stkr = stocker.Stocker( client_id=socket.gethostname(), dsn=args.sqlalchemy_dsn) for s in args.servers: if '/' in s: (host, port) = s.split('/', 2) else: host = s port = None stkr.addServer(host, port) stkr.waitForServer() while True: stkr.run() stkr.ship()
Set default player simulator tickrate to 10 ticks
package org.cyclops.integratedtunnels.part; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.core.part.write.PartStateWriterBase; import org.cyclops.integratedtunnels.core.ExtendedFakePlayer; import org.cyclops.integratedtunnels.core.ItemHandlerPlayerWrapper; /** * A part state for holding a temporary player inventory. * @author rubensworks */ public class PartStatePlayerSimulator extends PartStateWriterBase<PartTypePlayerSimulator> { private ExtendedFakePlayer player = null; public PartStatePlayerSimulator(int inventorySize) { super(inventorySize); } public ExtendedFakePlayer getPlayer() { return player; } public void update(PartTarget target) { World world = target.getTarget().getPos().getWorld(); if (!world.isRemote) { if (player == null) { player = new ExtendedFakePlayer((WorldServer) world); } ItemHandlerPlayerWrapper.cancelDestroyingBlock(player); } } @Override protected int getDefaultUpdateInterval() { return 10; } }
package org.cyclops.integratedtunnels.part; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.core.part.write.PartStateWriterBase; import org.cyclops.integratedtunnels.core.ExtendedFakePlayer; import org.cyclops.integratedtunnels.core.ItemHandlerPlayerWrapper; /** * A part state for holding a temporary player inventory. * @author rubensworks */ public class PartStatePlayerSimulator extends PartStateWriterBase<PartTypePlayerSimulator> { private ExtendedFakePlayer player = null; public PartStatePlayerSimulator(int inventorySize) { super(inventorySize); } public ExtendedFakePlayer getPlayer() { return player; } public void update(PartTarget target) { World world = target.getTarget().getPos().getWorld(); if (!world.isRemote) { if (player == null) { player = new ExtendedFakePlayer((WorldServer) world); } ItemHandlerPlayerWrapper.cancelDestroyingBlock(player); } } }
Change input type to tel for mobile safari
import {Observable} from 'rx' import {div, input, label} from '@cycle/DOM' function renderInputField(value) { return input('.number-input .mdl-textfield__input', { type: 'tel', attributes: {inputmode: "numeric"}, value: value, pattern: "-?[0-9]*(\.[0-9]+)?" } ) } function renderLabel(labelText) { return label('.number-input-label .mdl-textfield__label', labelText) } function renderNumberInput(props, value) { return div('.number-input-container', [ div('.mdl-textfield .mdl-js-textfield .mdl-textfield--floating-label', [renderInputField(value), renderLabel(props.label)] )] ) } function view(props$, value$) { return Observable.combineLatest(props$, value$, renderNumberInput); } export default view;
import {Observable} from 'rx' import {div, input, label} from '@cycle/DOM' function renderInputField(value) { return input('.number-input .mdl-textfield__input', { type: 'number', attributes: {inputmode: "numeric"}, value: value, pattern: "-?[0-9]*(\.[0-9]+)?" } ) } function renderLabel(labelText) { return label('.number-input-label .mdl-textfield__label', labelText) } function renderNumberInput(props, value) { return div('.number-input-container', [ div('.mdl-textfield .mdl-js-textfield .mdl-textfield--floating-label', [renderInputField(value), renderLabel(props.label)] )] ) } function view(props$, value$) { return Observable.combineLatest(props$, value$, renderNumberInput); } export default view;
Make is_call handle multiple arguments. Can now be called with a sequence, as in is_call(ancestor::Function/@name) or just several literals, as in is_call('eval', 'feval'). In both cases, it does an or.
import sys import lxml.etree class XPathError(Exception): pass def parse_xml_filename(filename): return lxml.etree.parse(filename) def compile_xpath(query): try: return lxml.etree.XPath(query) except lxml.etree.XPathSyntaxError as e: raise XPathError(e.msg), None, sys.exc_info()[2] def register_extensions(): ns = lxml.etree.FunctionNamespace(None) ns['is_call'] = is_call def is_call(context, *names): node = context.context_node if node.tag != 'ParameterizedExpr': return False if node[0].tag != 'NameExpr' or node[0].get('kind') != 'FUN': return False called_name = node[0][0].get('nameId') # Could this function like # is_call('eval', 'feval') -> names is a tuple of strings # is_call(//some/sequence) -> names[0] is a list of strings for name in names: if isinstance(name, basestring) and called_name == name: return True elif any(called_name == n for n in name): return True return False
import sys import lxml.etree class XPathError(Exception): pass def parse_xml_filename(filename): return lxml.etree.parse(filename) def compile_xpath(query): try: return lxml.etree.XPath(query) except lxml.etree.XPathSyntaxError as e: raise XPathError(e.msg), None, sys.exc_info()[2] def register_extensions(): ns = lxml.etree.FunctionNamespace(None) ns['is_call'] = lambda c, n: is_call(c.context_node, n) def is_call(node, name): return (node.tag == 'ParameterizedExpr' and node[0].tag == 'NameExpr' and node[0].get('kind') == 'FUN' and node[0][0].get('nameId') == name)
Add a DEBUG environment option to Heroku settings.
import os import dj_database_url from .base import * # noqa: F401,F403 DEBUG = os.environ.get('DEBUG', False) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } # Email SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME', None) # noqa: F405 SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD', None) # noqa: F405 # Use SendGrid if we have the addon installed, else just print to console which # is accessible via Heroku logs if SENDGRID_USERNAME and SENDGRID_PASSWORD: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = SENDGRID_USERNAME EMAIL_HOST_PASSWORD = SENDGRID_PASSWORD EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_TIMEOUT = 60 else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
import os import dj_database_url from .base import * # noqa: F401,F403 DEBUG = False # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } # Email SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME', None) # noqa: F405 SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD', None) # noqa: F405 # Use SendGrid if we have the addon installed, else just print to console which # is accessible via Heroku logs if SENDGRID_USERNAME and SENDGRID_PASSWORD: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = SENDGRID_USERNAME EMAIL_HOST_PASSWORD = SENDGRID_PASSWORD EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_TIMEOUT = 60 else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Add support for multiple issue keywords in the same repo
String.prototype.replaceAll = function(search, replace) { //if replace is not sent, return original string otherwise it will //replace search string with 'undefined'. if (replace === undefined) { return this.toString(); } return this.replace(new RegExp('[' + search + ']', 'g'), replace); }; var repoFromLink = window.location.pathname.split("/")[2]; listRepositories(function(repos){ var repos = repos.filter(repo => repo.scm == repoFromLink); if(repos){ processRepo(repos); } }); function processRepo(repos){ var commentBody = $(".comment-body, .commit-title, .commit-desc"); var splittedBody = commentBody.text().split(" "); for( var i in splittedBody){ var text = splittedBody[i]; for(var j in repos){ var repo = repos[j]; if (splittedBody[i].indexOf(repo.keyword) > -1){ console.log("here"); //Clean the link from some symbols usually added to destinguish issue-id from commit message var cleanedText = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll("#", ""); commentBody.html(commentBody.html().replace(text, '<a href="' + repo.targetURL + cleanedText + '">' + text + '</a>')); } } } }
String.prototype.replaceAll = function(search, replace) { //if replace is not sent, return original string otherwise it will //replace search string with 'undefined'. if (replace === undefined) { return this.toString(); } return this.replace(new RegExp('[' + search + ']', 'g'), replace); }; var repoFromLink = window.location.pathname.split("/")[2]; listRepositories(function(repos){ var repo = repos.find(repo => repo.scm == repoFromLink); if(repo){ processRepo(repo); } }); function processRepo(repo){ var commentBody = $(".comment-body, .commit-title, .commit-desc"); var splittedBody = commentBody.text().split(" "); for( var i in splittedBody){ var text = splittedBody[i]; if (splittedBody[i].indexOf(repo.keyword) > -1){ //Clean the link from some symbols usually added to destinguish issue-id from commit message var cleanedText = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll("#", ""); commentBody.html(commentBody.html().replace(text, '<a href="' + repo.targetURL + cleanedText + '">' + text + '</a>')); } } }
Apply a trim to every value this removes non-unix-style-newlines, spaces at the end of the line. To remove spaces at the end of the line is especially important, when you rely on the hostname as an example.
<?php namespace NagParser\Definitions; abstract class Definition { private $type; private $config; public function __construct($type, $config) { $this->type = $type; $this->parseConfig($config); } private function parseConfig($config) { preg_match_all('/^\s*(.+?)\s+(.+)$/m', $config, $matches); $matches[2] = array_map('trim', $matches[2]); $this->config = array_combine($matches[1], $matches[2]); } public function getOption($option) { if (array_key_exists($option, $this->config)) { return $this->config[$option]; } } /** * @return mixed */ public function getConfig() { return $this->config; } /** * @return mixed */ public function getType() { return $this->type; } }
<?php namespace NagParser\Definitions; abstract class Definition { private $type; private $config; public function __construct($type, $config) { $this->type = $type; $this->parseConfig($config); } private function parseConfig($config) { preg_match_all('/^\s*(.+?)\s+(.+)$/m', $config, $matches); $this->config = array_combine($matches[1], $matches[2]); } public function getOption($option) { if (array_key_exists($option, $this->config)) { return $this->config[$option]; } } /** * @return mixed */ public function getConfig() { return $this->config; } /** * @return mixed */ public function getType() { return $this->type; } }
Make examples scripts executable only via CLI. This is meant as a basic layer of protection for those cases where the whole Predis repository is cloned into a path which is publicly exposed by the web server. Closes #408
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <suppakilla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (PHP_SAPI !== 'cli') { die("Example scripts are meant to be executed locally via CLI."); } require __DIR__.'/../autoload.php'; function redis_version($info) { if (isset($info['Server']['redis_version'])) { return $info['Server']['redis_version']; } elseif (isset($info['redis_version'])) { return $info['redis_version']; } else { return 'unknown version'; } } $single_server = array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 15, ); $multiple_servers = array( array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 15, 'alias' => 'first', ), array( 'host' => '127.0.0.1', 'port' => 6380, 'database' => 15, 'alias' => 'second', ), );
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <suppakilla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require __DIR__.'/../autoload.php'; function redis_version($info) { if (isset($info['Server']['redis_version'])) { return $info['Server']['redis_version']; } elseif (isset($info['redis_version'])) { return $info['redis_version']; } else { return 'unknown version'; } } $single_server = array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 15, ); $multiple_servers = array( array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 15, 'alias' => 'first', ), array( 'host' => '127.0.0.1', 'port' => 6380, 'database' => 15, 'alias' => 'second', ), );
Fix formatting and please IDE IntelliJ IDEA really likes `@Autowired` for XML configuration.
package ch.wisv.connect.overlay.services; import com.nimbusds.jwt.JWTClaimsSet; import org.mitre.oauth2.model.ClientDetailsEntity; import org.mitre.oauth2.model.OAuth2AccessTokenEntity; import org.mitre.openid.connect.service.impl.DefaultOIDCTokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.provider.OAuth2Request; import java.util.Set; public class CHOIDCTokenService extends DefaultOIDCTokenService { private final CHUserDetailsService chUserDetailsService; @Autowired public CHOIDCTokenService(CHUserDetailsService chUserDetailsService) { this.chUserDetailsService = chUserDetailsService; } @Override protected void addCustomIdTokenClaims(JWTClaimsSet.Builder idClaims, ClientDetailsEntity client, OAuth2Request request, String sub, OAuth2AccessTokenEntity accessToken) { Set<String> ldapGroups = chUserDetailsService.loadUserBySubject(sub).getLdapGroups(); idClaims.claim("ldap_groups", ldapGroups); } }
package ch.wisv.connect.overlay.services; import com.nimbusds.jwt.JWTClaimsSet; import org.mitre.oauth2.model.ClientDetailsEntity; import org.mitre.oauth2.model.OAuth2AccessTokenEntity; import org.mitre.openid.connect.service.impl.DefaultOIDCTokenService; import org.springframework.security.oauth2.provider.OAuth2Request; import java.util.Set; public class CHOIDCTokenService extends DefaultOIDCTokenService { private final CHUserDetailsService chUserDetailsService; public CHOIDCTokenService(CHUserDetailsService chUserDetailsService) { this.chUserDetailsService = chUserDetailsService; } @Override protected void addCustomIdTokenClaims(JWTClaimsSet.Builder idClaims, ClientDetailsEntity client, OAuth2Request request, String sub, OAuth2AccessTokenEntity accessToken) { Set<String> ldapGroups = chUserDetailsService.loadUserBySubject(sub).getLdapGroups(); idClaims.claim("ldap_groups", ldapGroups); } }
Revert "Increased wait time to 5sec" This reverts commit fef7dee
package urchin.selenium.view; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import urchin.selenium.testutil.SeleniumDriver; import urchin.selenium.testutil.SeleniumUrl; public abstract class PageView<T> { private static final int TIME_OUT_IN_SECONDS = 3; protected final WebDriver driver = SeleniumDriver.getDriver(); private final String url = SeleniumUrl.getUrl(); private final WebDriverWait wait = new WebDriverWait(driver, TIME_OUT_IN_SECONDS); protected abstract String viewUrl(); public abstract T verifyAtView(); public T goTo() { driver.get(url + viewUrl()); return verifyAtView(); } protected void waitUntil(ExpectedCondition webElementExpectedCondition) { wait.until(webElementExpectedCondition); } protected By byDataView(String name) { return By.cssSelector("[data-view=" + name + "]"); } }
package urchin.selenium.view; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import urchin.selenium.testutil.SeleniumDriver; import urchin.selenium.testutil.SeleniumUrl; public abstract class PageView<T> { private static final int TIME_OUT_IN_SECONDS = 5; protected final WebDriver driver = SeleniumDriver.getDriver(); private final String url = SeleniumUrl.getUrl(); private final WebDriverWait wait = new WebDriverWait(driver, TIME_OUT_IN_SECONDS); protected abstract String viewUrl(); public abstract T verifyAtView(); public T goTo() { driver.get(url + viewUrl()); return verifyAtView(); } protected void waitUntil(ExpectedCondition webElementExpectedCondition) { wait.until(webElementExpectedCondition); } protected By byDataView(String name) { return By.cssSelector("[data-view=" + name + "]"); } }
Fix use of style in tri.Draw
// Copyright 2016 The Gosl 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 tri import "github.com/cpmech/gosl/plt" func Draw(V [][]float64, C [][]int, style *plt.A) { if style == nil { style = &plt.A{C: "b", M: "o", Ms: 2} } type edgeType struct{ A, B int } drawnEdges := make(map[edgeType]bool) for _, cell := range C { for i := 0; i < 3; i++ { a, b := cell[i], cell[(i+1)%3] edge := edgeType{a, b} if b < a { edge.A, edge.B = edge.B, edge.A } if _, found := drawnEdges[edge]; !found { x := []float64{V[a][0], V[b][0]} y := []float64{V[a][1], V[b][1]} plt.Plot(x, y, style) drawnEdges[edge] = true } } } }
// Copyright 2016 The Gosl 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 tri import "github.com/cpmech/gosl/plt" func Draw(V [][]float64, C [][]int, style *plt.A) { if style == nil { style = &plt.A{C: "b", M: "o", Ms: 2} } type edgeType struct{ A, B int } drawnEdges := make(map[edgeType]bool) for _, cell := range C { for i := 0; i < 3; i++ { a, b := cell[i], cell[(i+1)%3] edge := edgeType{a, b} if b < a { edge.A, edge.B = edge.B, edge.A } if _, found := drawnEdges[edge]; !found { x := []float64{V[a][0], V[b][0]} y := []float64{V[a][1], V[b][1]} plt.Plot(x, y, nil) drawnEdges[edge] = true } } } }
:bug: Fix handling of null in extend config
'use babel' import isGlob from 'is-glob' import {isMatch} from 'micromatch' export function getRules(relativePath, config) { const localConfig = {} for (const key in config) { const value = config[key] if (value && value instanceof Array) { localConfig[key] = value.slice() } else if (value && typeof value === 'object') { localConfig[key] = Object.assign({}, value) } else { localConfig[key] = value } } config.rules.forEach(function(rule) { const matches = isGlob(rule.path) ? isMatch(relativePath, rule.path) : relativePath === rule.path if (matches) { for (const key in rule) { if (typeof localConfig[key] !== 'undefined' && localConfig[key] instanceof Array) { localConfig[key] = localConfig[key].concat(rule[key]) } else { localConfig[key] = rule[key] } } } }) delete localConfig.rules delete localConfig.path return localConfig }
'use babel' import isGlob from 'is-glob' import {isMatch} from 'micromatch' export function getRules(relativePath, config) { const localConfig = {} for (const key in config) { const value = config[key] if (value && value instanceof Array) { localConfig[key] = value.slice() } else if (typeof value === 'object') { localConfig[key] = Object.assign({}, value) } else { localConfig[key] = value } } config.rules.forEach(function(rule) { const matches = isGlob(rule.path) ? isMatch(relativePath, rule.path) : relativePath === rule.path if (matches) { for (const key in rule) { if (typeof localConfig[key] !== 'undefined' && localConfig[key] instanceof Array) { localConfig[key] = localConfig[key].concat(rule[key]) } else { localConfig[key] = rule[key] } } } }) delete localConfig.rules delete localConfig.path return localConfig }
Remove loose mode from babel
const createConfig = (api) => { api.cache.never(); return { presets: [ '@babel/preset-react', [ '@babel/env', { modules: false, useBuiltIns: false, targets: { browsers: [ 'last 2 Chrome versions', 'last 2 Firefox versions', 'last 1 Safari versions', 'last 1 ChromeAndroid versions', 'last 1 Edge versions', ], }, }, ], ], plugins: ['@babel/syntax-dynamic-import'], }; }; module.exports = createConfig;
const createConfig = (api) => { api.cache.never(); return { presets: [ '@babel/preset-react', [ '@babel/env', { modules: false, loose: true, useBuiltIns: false, targets: { browsers: [ 'last 2 Chrome versions', 'last 2 Firefox versions', 'last 1 Safari versions', 'last 1 ChromeAndroid versions', 'last 1 Edge versions', ], }, }, ], ], plugins: ['@babel/syntax-dynamic-import'], }; }; module.exports = createConfig;
Remove createJSModules for RN 0.47.
package com.artirigo.kontaktio; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Range and Monitor Kontakt.io beacons */ public class KontaktPackage implements ReactPackage { @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<NativeModule> createNativeModules( ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new KontaktModule(reactContext)); return modules; } }
package com.artirigo.kontaktio; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Range and Monitor Kontakt.io beacons */ public class KontaktPackage implements ReactPackage { @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<NativeModule> createNativeModules( ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new KontaktModule(reactContext)); return modules; } }
Fix REPL script require path
#!/usr/bin/env node var repl = require('repl'); var program = require('commander'); var defaults = require('../lib/defaults.js'); var protocol = require('../lib/protocol.json'); var Chrome = require('../'); program .option('-h, --host <host>', 'Remote Debugging Protocol host', defaults.HOST) .option('-p, --port <port>', 'Remote Debugging Protocol port', defaults.PORT) .parse(process.argv); var options = { 'host': program.host, 'port': program.port }; Chrome(options, function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ', 'ignoreUndefined': true }); // disconnect on exit chromeRepl.on('exit', function () { chrome.close(); }); // add protocol API for (var domainIdx in protocol.domains) { var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } }).on('error', function () { console.error('Cannot connect to Chrome'); });
#!/usr/bin/env node var repl = require('repl'); var program = require('commander'); var defaults = require('./defaults.js'); var protocol = require('../lib/protocol.json'); var Chrome = require('../'); program .option('-h, --host <host>', 'Remote Debugging Protocol host', defaults.HOST) .option('-p, --port <port>', 'Remote Debugging Protocol port', defaults.PORT) .parse(process.argv); var options = { 'host': program.host, 'port': program.port }; Chrome(options, function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ', 'ignoreUndefined': true }); // disconnect on exit chromeRepl.on('exit', function () { chrome.close(); }); // add protocol API for (var domainIdx in protocol.domains) { var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } }).on('error', function () { console.error('Cannot connect to Chrome'); });
Update site variables for v1.0.0
// The buildInfo constant is generated by sbt. Do not edit directly. const buildInfo = { organization: 'is.cir', coreModuleName: 'ciris', latestVersion: '1.0.0', scalaPublishVersions: '2.12 and 2.13' }; const repoUrl = "https://github.com/vlovgr/ciris"; const apiUrl = "/api/ciris/index.html"; // See https://docusaurus.io/docs/site-config for available options. const siteConfig = { title: "Ciris", tagline: "Functional Configurations for Scala", url: "https://cir.is", baseUrl: "/", customDocsPath: "docs/target/mdoc", projectName: "ciris", organizationName: "vlovgr", headerLinks: [ { href: apiUrl, label: "API Docs" }, { doc: "overview", label: "Documentation" }, { href: repoUrl, label: "GitHub" } ], headerIcon: "img/ciris.white.svg", titleIcon: "img/ciris.svg", favicon: "img/favicon.png", colors: { primaryColor: "#122932", secondaryColor: "#153243" }, copyright: `Copyright © 2017-${new Date().getFullYear()} Viktor Lövgren.`, highlight: { theme: "github" }, onPageNav: "separate", separateCss: ["api"], cleanUrl: true, repoUrl, buildInfo, apiUrl }; module.exports = siteConfig;
// The buildInfo constant is generated by sbt. Do not edit directly. const buildInfo = { organization: "is.cir", coreModuleName: "ciris", latestVersion: "1.0.0-SNAPSHOT", scalaPublishVersions: "2.12 and 2.13" }; const repoUrl = "https://github.com/vlovgr/ciris"; const apiUrl = "/api/ciris/index.html"; // See https://docusaurus.io/docs/site-config for available options. const siteConfig = { title: "Ciris", tagline: "Functional Configurations for Scala", url: "https://cir.is", baseUrl: "/", customDocsPath: "docs/target/mdoc", projectName: "ciris", organizationName: "vlovgr", headerLinks: [ { href: apiUrl, label: "API Docs" }, { doc: "overview", label: "Documentation" }, { href: repoUrl, label: "GitHub" } ], headerIcon: "img/ciris.white.svg", titleIcon: "img/ciris.svg", favicon: "img/favicon.png", colors: { primaryColor: "#122932", secondaryColor: "#153243" }, copyright: `Copyright © 2017-${new Date().getFullYear()} Viktor Lövgren.`, highlight: { theme: "github" }, onPageNav: "separate", separateCss: ["api"], cleanUrl: true, repoUrl, buildInfo, apiUrl }; module.exports = siteConfig;
Change the field type of amount and balance to DecimalField
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.DecimalField(decimal_places=10, max_digits=19) balance = models.DecimalField(decimal_places=10, max_digits=19) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.CharField(max_length=50) balance = models.CharField(max_length=50) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
Update password functions for Django 1.8
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^macnamer/', include('macnamer.foo.urls')), url(r'^login/$', 'django.contrib.auth.views.login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'), url(r'^changepassword/$', 'django.contrib.auth.views.password_change', name='password_change'), url(r'^changepassword/done/$', 'django.contrib.auth.views.password_change_done', name='password_change_done'), url(r'^', include('server.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), #url(r'^$', 'namer.views.index', name='home'), )
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^macnamer/', include('macnamer.foo.urls')), url(r'^login/$', 'django.contrib.auth.views.login'), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'), url(r'^changepassword/$', 'django.contrib.auth.views.password_change'), url(r'^changepassword/done/$', 'django.contrib.auth.views.password_change_done'), url(r'^', include('server.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), #url(r'^$', 'namer.views.index', name='home'), )
Add an exception to tell a controller does not implement something.
import unittest import operator import itertools class NotImplementedByController(unittest.SkipTest): def __str__(self): return 'Not implemented by controller: {}'.format(self.args[0]) class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) for (msg, tests) in sorted(msg_to_tests): print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result
import unittest import operator import itertools class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) for (msg, tests) in msg_to_tests: print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result
Remove UNICORE_DISTRIBUTE_API from test settings This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109c
from testapp.settings.base import * ENABLE_SSO = True MIDDLEWARE_CLASSES += ( 'molo.core.middleware.MoloCASMiddleware', 'molo.core.middleware.Custom403Middleware', ) AUTHENTICATION_BACKENDS = ( 'molo.profiles.backends.MoloProfilesModelBackend', 'molo.core.backends.MoloModelBackend', 'django.contrib.auth.backends.ModelBackend', 'molo.core.backends.MoloCASBackend', ) CAS_SERVER_URL = 'http://testcasserver' CAS_ADMIN_PREFIX = '/admin/' LOGIN_URL = '/accounts/login/' CAS_VERSION = '3' CELERY_ALWAYS_EAGER = True DEAFULT_SITE_PORT = 8000 INSTALLED_APPS = INSTALLED_APPS + [ 'import_export', ]
from testapp.settings.base import * ENABLE_SSO = True MIDDLEWARE_CLASSES += ( 'molo.core.middleware.MoloCASMiddleware', 'molo.core.middleware.Custom403Middleware', ) AUTHENTICATION_BACKENDS = ( 'molo.profiles.backends.MoloProfilesModelBackend', 'molo.core.backends.MoloModelBackend', 'django.contrib.auth.backends.ModelBackend', 'molo.core.backends.MoloCASBackend', ) CAS_SERVER_URL = 'http://testcasserver' CAS_ADMIN_PREFIX = '/admin/' LOGIN_URL = '/accounts/login/' CAS_VERSION = '3' UNICORE_DISTRIBUTE_API = 'http://testserver:6543' CELERY_ALWAYS_EAGER = True DEAFULT_SITE_PORT = 8000 INSTALLED_APPS = INSTALLED_APPS + [ 'import_export', ]
Improve code comments for undocumented API
'use strict' module.exports = new AsyncState() function AsyncState () { var tracing var state = this try { tracing = require('tracing') } catch (e) { tracing = require('./lib/tracing_polyfill.js') } tracing.addAsyncListener({ 'create': asyncFunctionInitialized, 'before': asyncCallbackBefore, 'error': function () {}, 'after': asyncCallbackAfter }) function asyncFunctionInitialized () { // Record the state currently set on on the async-state object and return a // snapshot of it. The returned object will later be passed as the `data` // arg in the functions below. var data = {} for (var key in state) { data[key] = state[key] } return data } function asyncCallbackBefore (context, data) { // We just returned from the event-loop: We'll now restore the state // previously saved by `asyncFunctionInitialized`. for (var key in data) { state[key] = data[key] } } function asyncCallbackAfter (context, data) { // Clear the state so that it doesn't leak between isolated async stacks. for (var key in state) { delete state[key] } } }
'use strict' module.exports = new AsyncState() function AsyncState () { var tracing var state = this try { tracing = require('tracing') } catch (e) { tracing = require('./lib/tracing_polyfill.js') } tracing.addAsyncListener({ 'create': asyncFunctionInitialized, 'before': asyncCallbackBefore, 'error': function () {}, 'after': asyncCallbackAfter }) function asyncFunctionInitialized () { var data = {} for (var key in state) { data[key] = state[key] } return data } function asyncCallbackBefore (context, data) { for (var key in data) { state[key] = data[key] } } function asyncCallbackAfter (context, data) { for (var key in state) { delete state[key] } } }
[TASK] Fix regex for images with hypen
<?php /* * This file is part of the Slim Image Resize middleware * * Copyright (c) 2014 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * https://github.com/tuupola/slim-image-resize * */ namespace Slim\Middleware\ImageResize; class DefaultMutator extends MutatorAbstract { protected static $regexp = "/(?<original>.+)-(?<size>(?<width>\d*)x(?<height>\d*))-?(?<signature>[0-9a-z]*)/"; public function execute() { /* Fit or resize. */ extract($this->options); if (null !== $width && null !== $height) { $this->image->fit($width, $height); } else { $this->image->resize($width, $height, function ($constraint) { $constraint->aspectRatio(); }); } return $this; } }
<?php /* * This file is part of the Slim Image Resize middleware * * Copyright (c) 2014 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * https://github.com/tuupola/slim-image-resize * */ namespace Slim\Middleware\ImageResize; class DefaultMutator extends MutatorAbstract { protected static $regexp = "/(?<original>[^-]+)-(?<size>(?<width>\d*)x(?<height>\d*))-?(?<signature>[0-9a-z]*)/"; public function execute() { /* Fit or resize. */ extract($this->options); if (null !== $width && null !== $height) { $this->image->fit($width, $height); } else { $this->image->resize($width, $height, function ($constraint) { $constraint->aspectRatio(); }); } return $this; } }
Use WFS feature name in UI if the title is empty.
/* * DownloadClient Geodateninfrastruktur Bayern * * (c) 2016 GSt. GDI-BY (gdi.bayern.de) * * 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 de.bayern.gdi.gui; import de.bayern.gdi.services.WFSMeta; /** * Model class to display WFS features. */ public class FeatureModel implements ItemModel { private WFSMeta.Feature feature; /** * Contructor to wrap. */ public FeatureModel(WFSMeta.Feature f) { this.feature = f; } public Object getItem() { return this.feature; } public String getDataset() { return feature.name; } @Override public String toString() { return this.feature.title != null && !this.feature.title.isEmpty() ? this.feature.title : this.feature.name; } }
/* * DownloadClient Geodateninfrastruktur Bayern * * (c) 2016 GSt. GDI-BY (gdi.bayern.de) * * 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 de.bayern.gdi.gui; import de.bayern.gdi.services.WFSMeta; /** * Model class to display WFS features. */ public class FeatureModel implements ItemModel { private WFSMeta.Feature feature; /** * Contructor to wrap. */ public FeatureModel(WFSMeta.Feature f) { this.feature = f; } public Object getItem() { return this.feature; } public String getDataset() { return feature.name; } @Override public String toString() { return this.feature.title; } }
Undo member changes in test
from django.test import TestCase from django.contrib.auth.models import User from mks.models import Member from .models import Suggestion class SuggestionsTests(TestCase): def setUp(self): self.member = Member.objects.create(name='mk_1') self.regular_user = User.objects.create_user('reg_user') def test_simple_text_suggestion(self): MK_SITE = 'http://mk1.example.com' suggestion = Suggestion.objects.create_suggestion( suggested_by=self.regular_user, content_object=self.member, suggestion_action=Suggestion.UPDATE, suggested_field='website', suggested_text=MK_SITE ) self.assertIsNone(self.member.website) suggestion.auto_apply() mk = Member.objects.get(pk=self.member.pk) self.assertEqual(mk.website, MK_SITE) # cleanup mk.website = None mk.save() self.member = mk
from django.test import TestCase from django.contrib.auth.models import User from mks.models import Member from .models import Suggestion class SuggestionsTests(TestCase): def setUp(self): self.member = Member.objects.create(name='mk_1') self.regular_user = User.objects.create_user('reg_user') def test_simple_text_suggestion(self): MK_SITE = 'http://mk1.example.com' suggestion = Suggestion.objects.create_suggestion( suggested_by=self.regular_user, content_object=self.member, suggestion_action=Suggestion.UPDATE, suggested_field='website', suggested_text=MK_SITE ) self.assertIsNone(self.member.website) suggestion.auto_apply() mk = Member.objects.get(pk=self.member.pk) self.assertEqual(mk.website, MK_SITE)
Add chord to the url
define(['jquery', 'underscore', 'backbone', 'noteConverter', ], function ($, _, Backbone, NoteConverter) { var Router = Backbone.Router.extend({ routes: { 'chord/*notes': 'setNotes' }, initialize: function (options) { this.model = options.model; this.listenTo(this.model, 'change', this.updateUrl); }, updateUrl: function () { this.navigate('chord/' + this.model.url()); }, setNotes: function (notes) { if (notes) { var parsedNotes = NoteConverter.parseNotes(notes); this.model.set('notes', parsedNotes); } } }); return Router; });
define(['jquery', 'underscore', 'backbone', 'noteConverter', ], function ($, _, Backbone, NoteConverter) { var Router = Backbone.Router.extend({ routes: { 'chord/*notes': 'setNotes' }, initialize: function (options) { this.model = options.model; this.listenTo(this.model, 'change', this.updateUrl); }, updateUrl: function () { this.navigate(this.model.url()); }, setNotes: function (notes) { if (notes) { var parsedNotes = NoteConverter.parseNotes(notes); this.model.set('notes', parsedNotes); } } }); return Router; });
Add tests for arrays of Comparable objects.
package com.stephenramthun.algorithms.sorting; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; class BubbleSortTest { @Test void testSorting() { int n = 1000; int r = 10; for (int i = 0; i < r; i++) { int[] array = Utility.randomArray(n); BubbleSort.sort(array); assertTrue(Utility.isSorted(array)); } String[] strings = {"cbc", "abc", "bbc", "ccd", "ccb", "bbc", "aab"}; assertFalse(Utility.isSorted(strings)); BubbleSort.sort(strings); assertTrue(Utility.isSorted(strings)); } @Test void testPermutation() { int n = 1000; int r = 10; for (int i = 0; i < r; i++) { int[] a = Utility.randomArray(n); int[] b = Utility.copy(a); BubbleSort.sort(a); assertTrue(Utility.arePermutations(a, b)); } } }
package com.stephenramthun.algorithms.sorting; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class BubbleSortTest { @Test void testSorting() { int n = 1000; int r = 10; for (int i = 0; i < r; i++) { int[] array = Utility.randomArray(n); BubbleSort.sort(array); assertTrue(Utility.isSorted(array)); } } @Test void testPermutation() { int n = 1000; int r = 10; for (int i = 0; i < r; i++) { int[] a = Utility.randomArray(n); int[] b = Utility.copy(a); BubbleSort.sort(a); assertTrue(Utility.arePermutations(a, b)); } } }
Replace dir separator for windows
<?php /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright 2010-2017 Mike van Riel<mike@phpdoc.org> * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ namespace phpDocumentor\Application\Stage; use phpDocumentor\Application\Configuration\ConfigurationFactory; use phpDocumentor\Application\Configuration\Factory\Version3; use phpDocumentor\DomainModel\Uri; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \phpDocumentor\Application\Stage\Configure */ class ConfigureTest extends TestCase { /** * @use \phpDocumentor\Application\Configuration\ConfigurationFactory; * @use \phpDocumentor\Application\Configuration\Factory\Version3; * @use \phpDocumentor\DomainModel\Uri; */ public function testInvokeOverridesConfig() { $configFactory = new ConfigurationFactory( [new Version3(__DIR__ . '/../../../../../data/xsd/phpdoc.xsd')], new Uri(__DIR__ . str_replace('/', DIRECTORY_SEPARATOR, '/../../../data/phpDocumentor3XML.xml')) ); $fixture = new Configure($configFactory); $result = $fixture(['force' => true]); $this->assertFalse($result['phpdocumentor']['use-cache']); } }
<?php /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright 2010-2017 Mike van Riel<mike@phpdoc.org> * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ namespace phpDocumentor\Application\Stage; use phpDocumentor\Application\Configuration\ConfigurationFactory; use phpDocumentor\Application\Configuration\Factory\Version3; use phpDocumentor\DomainModel\Uri; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \phpDocumentor\Application\Stage\Configure */ class ConfigureTest extends TestCase { /** * @use \phpDocumentor\Application\Configuration\ConfigurationFactory; * @use \phpDocumentor\Application\Configuration\Factory\Version3; * @use \phpDocumentor\DomainModel\Uri; */ public function testInvokeOverridesConfig() { $configFactory = new ConfigurationFactory( [new Version3(__DIR__ . '/../../../../../data/xsd/phpdoc.xsd')], new Uri(__DIR__ . '/../../../data/phpDocumentor3XML.xml') ); $fixture = new Configure($configFactory); $result = $fixture(['force' => true]); $this->assertFalse($result['phpdocumentor']['use-cache']); } }
Put both jsx and js varaibles on same line in config file.
/* * @Author: KevinMidboe * @Date: 2017-06-01 19:09:16 * @Last Modified by: KevinMidboe * @Last Modified time: 2017-10-24 21:55:41 */ const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './app/index.js', }, plugins: [ new CleanWebpackPlugin(['dist']), new HtmlWebpackPlugin({ template: './app/index.html', }) ], module: { loaders: [ { test: /\.(js|jsx)$/, loader: 'babel-loader', exclude: /node_modules/ }, ] }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };
/* * @Author: KevinMidboe * @Date: 2017-06-01 19:09:16 * @Last Modified by: KevinMidboe * @Last Modified time: 2017-10-24 21:55:41 */ const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './app/index.js', }, plugins: [ new CleanWebpackPlugin(['dist']), new HtmlWebpackPlugin({ template: './app/index.html', }) ], module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }, ] }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };
Update IN_DB validation rule to support specifying column different from model property.
<?php class InDbValidator { private $model; public function __construct ($model) { $this->model = $model; } public function validate ($property, $rules) { if ($this->model->$property !== null && $this->model->$property != '') { $dbRelation = (isset($rules['relation']) ? $rules['relation'] : false); $dbColumn = (isset($rules['column']) ? $rules['column'] : $property); if ($dbRelation) { $db = DatabaseFactory::getConnection(); $dbCast = (isset($rules['type']) ? '::' . $rules['type'] : ''); $query = "SELECT 1 FROM $dbRelation WHERE $dbColumn = ?{$dbCast}"; if (!$db->getColumn($query, $this->model->$property)) { return array('in_db' => array($rules['name'], $this->model->$property)); } } } return true; } } ?>
<?php class InDbValidator { private $model; public function __construct ($model) { $this->model = $model; } public function validate ($property, $rules) { if ($this->model->$property !== null && $this->model->$property != '') { $dbRelation = (isset($rules['relation']) ? $rules['relation'] : false); if ($dbRelation) { $db = DatabaseFactory::getConnection(); $dbCast = (isset($rules['type']) ? '::' . $rules['type'] : ''); $query = "SELECT 1 FROM $dbRelation WHERE $property = ?{$dbCast}"; if (!$db->getColumn($query, $this->model->$property)) { return array('in_db' => array($rules['name'], $this->model->$property)); } } } return true; } } ?>
Raise the sleep hack in this test to make it less flaky. This sucks, must repair!
// Copyright 2020 Google Inc. All Rights Reserved. // This file is available under the Apache license. package mtail_test import ( "os" "path" "testing" "time" "github.com/golang/glog" "github.com/google/mtail/internal/mtail" "github.com/google/mtail/internal/testutil" ) func TestLogDeletion(t *testing.T) { testutil.SkipIfShort(t) workdir, rmWorkdir := testutil.TestTempDir(t) defer rmWorkdir() // touch log file logFilepath := path.Join(workdir, "log") logFile := testutil.TestOpenFile(t, logFilepath) defer logFile.Close() m, stopM := mtail.TestStartServer(t, 0, 1, mtail.LogPathPatterns(logFilepath)) defer stopM() logCountCheck := m.ExpectExpvarDeltaWithDeadline("log_count", -1) glog.Info("remove") testutil.FatalIfErr(t, os.Remove(logFilepath)) m.PollWatched(1) // one pass to stop // TODO(jaq): this sleep hides a race between filestream completing and // PollLogStreams noticing. time.Sleep(1 * time.Second) m.PollWatched(0) // one pass to remove completed stream logCountCheck() }
// Copyright 2020 Google Inc. All Rights Reserved. // This file is available under the Apache license. package mtail_test import ( "os" "path" "testing" "time" "github.com/golang/glog" "github.com/google/mtail/internal/mtail" "github.com/google/mtail/internal/testutil" ) func TestLogDeletion(t *testing.T) { testutil.SkipIfShort(t) workdir, rmWorkdir := testutil.TestTempDir(t) defer rmWorkdir() // touch log file logFilepath := path.Join(workdir, "log") logFile := testutil.TestOpenFile(t, logFilepath) defer logFile.Close() m, stopM := mtail.TestStartServer(t, 0, 1, mtail.LogPathPatterns(logFilepath)) defer stopM() logCountCheck := m.ExpectExpvarDeltaWithDeadline("log_count", -1) glog.Info("remove") testutil.FatalIfErr(t, os.Remove(logFilepath)) m.PollWatched(1) // one pass to stop // TODO(jaq): this sleep hides a race between filestream completing and // PollLogStreams noticing. time.Sleep(10 * time.Millisecond) m.PollWatched(0) // one pass to remove completed stream logCountCheck() }
Use PSR-7 way of accessing uri
<?php /* * This file is part of Slim JSON Web Token Authentication middleware * * Copyright (c) 2015 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * https://github.com/tuupola/slim-jwt-auth * */ namespace Slim\Middleware\JwtAuthentication; use \Psr\Http\Message\RequestInterface; class RequestPathRule implements RuleInterface { protected $options = array( "path" => "/", "passthrough" => array() ); public function __construct($options = array()) { $this->options = array_merge($this->options, $options); } public function __invoke(RequestInterface $request) { /* If request path is matches passthrough should not authenticate. */ foreach ($this->options["passthrough"] as $passthrough) { $passthrough = rtrim($passthrough, "/"); if (!!preg_match("@^{$passthrough}(/.*)?$@", $request->getUri()->getPath())) { return false; } } /* Otherwise check if path matches and we should authenticate. */ $path = rtrim($this->options["path"], "/"); return !!preg_match("@^{$path}(/.*)?$@", $request->getUri()->getPath()); } }
<?php /* * This file is part of Slim JSON Web Token Authentication middleware * * Copyright (c) 2015 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * https://github.com/tuupola/slim-jwt-auth * */ namespace Slim\Middleware\JwtAuthentication; use \Psr\Http\Message\RequestInterface; class RequestPathRule implements RuleInterface { protected $options = array( "path" => "/", "passthrough" => array() ); public function __construct($options = array()) { $this->options = array_merge($this->options, $options); } public function __invoke(RequestInterface $request) { /* If request path is matches passthrough should not authenticate. */ foreach ($this->options["passthrough"] as $passthrough) { $passthrough = rtrim($passthrough, "/"); if (!!preg_match("@^{$passthrough}(/.*)?$@", $app->request->getResourceUri())) { return false; } } /* Otherwise check if path matches and we should authenticate. */ $path = rtrim($this->options["path"], "/"); return !!preg_match("@^{$path}(/.*)?$@", $app->request->getResourceUri()); } }
Remove params from login route.
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var webServiceInit = new WebService(new CurrentUser()); var runService = webServiceInit.runWrapper(); // Database adapters. var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { // Add things to dependencies in everything service. webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); next(); }); app.use(function (req, res, next) { webServiceInit.runRef = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3])); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(process.argv[2]); console.log('Server listening on port ' + process.argv[2] + '.');
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var webServiceInit = new WebService(new CurrentUser()); var runService = webServiceInit.runWrapper(); // Database adapters. var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { // Add things to dependencies in everything service. webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); next(); }); app.use(function (req, res, next) { webServiceInit.runRef = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3], { param1: 'value1', param2: 'value2' })); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(process.argv[2]); console.log('Server listening on port ' + process.argv[2] + '.');
Add lodash dependency. Still needed for _.without
import Observable from '../util/Observable'; import * as _ from 'lodash'; export default class MetaControl extends Observable { constructor() { super(); this._registry = []; this._controlEvents = ['engage', 'disengage']; } _createEventProxy(event) { return (...args) => this.fireEvent.call(this, event, ...args); } addControl(control) { this._registry.push(control); const listeners = {}; this._controlEvents.forEach( event => listeners[event] = this._createEventProxy(event) ); control.attachListeners(listeners, this); } removeControl(control) { this._registry = _.without(this._registry, control); control.detachAllListeners(this); } destroy() { this._registry.forEach( control => control.detachAllListeners(this) ); this._registry = []; } }
import Observable from '../util/Observable'; export default class MetaControl extends Observable { constructor() { super(); this._registry = []; this._controlEvents = ['engage', 'disengage']; } _createEventProxy(event) { return (...args) => this.fireEvent.call(this, event, ...args); } addControl(control) { this._registry.push(control); const listeners = {}; this._controlEvents.forEach( event => listeners[event] = this._createEventProxy(event) ); control.attachListeners(listeners, this); } removeControl(control) { this._registry = _.without(this._registry, control); control.detachAllListeners(this); } destroy() { this._registry.forEach( control => control.detachAllListeners(this) ); this._registry = []; } }
Add Python 3.x versions to classifiers Things seem to be working with 3.x too.
#!/usr/bin/env python """ Erply-API --------- Python wrapper for Erply API """ from distutils.core import setup setup( name='ErplyAPI', version='0.2015.01.16-dev', description='Python wrapper for Erply API', license='BSD', author='Priit Laes', author_email='plaes@plaes.org', long_description=__doc__, install_requires=['requests'], py_modules=['erply_api'], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: Site Management', 'Topic :: Office/Business :: Financial :: Point-Of-Sale', 'Topic :: Software Development :: Libraries', ] )
#!/usr/bin/env python """ Erply-API --------- Python wrapper for Erply API """ from distutils.core import setup setup( name='ErplyAPI', version='0.2015.01.16-dev', description='Python wrapper for Erply API', license='BSD', author='Priit Laes', author_email='plaes@plaes.org', long_description=__doc__, install_requires=['requests'], py_modules=['erply_api'], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: Site Management', 'Topic :: Office/Business :: Financial :: Point-Of-Sale', 'Topic :: Software Development :: Libraries', ] )