Category Archives: Programming

Redux’s Connect Method Explained.

Sorry but all the explanations this far have been bad so I thought I’d simplify it.

In plain Redux without connect you need to manually bind up your store.dispatch to your components as well as subscribe to updates so you can call store.getState(). But your components are suppose to be dumb.

const store = createStore(reducer);

const render = () => ReactDOM.render( // turns ReactDOM.render into executable function
  <Counter
    value={store.getState()}
    onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
    onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
  />,
  document.getElementById('root')
);

render();
store.subscribe(render);

So rather than manually linking dispatch and subscribing to updates we create two mapping functions, both of which bind the dispatch and the state to props of the ‘connected component’. So in this case all updates to this.store.getState().value are mapped to this.props.value and rather than mapping dispatch directly, we just wrap it and pass it in as a prop.

// create component
class ContainerComponent extends React.Component {
  render() {
    <PresentationComponent 
      value={this.props.value}
      onIncrement={this.props.onIncrement} 
      onDecrement={this.props.onDecrement} />
  }
}
// create state mapping
function mapStateToProps(state) {
  return { 
    value: state.value
  };
}
// add dispatch mapper 
function mapDispatchToProps(dispatch) { 
  return { 
    onIncrement: function() { 
      dispatch({type:'INCREMENT'}); 
    }, 
    onDecrement : function() { 
      dispatch({type:'DECREMENT'}); 
    } 
  }; 
} 
export default connect(mapStateToProps,mapDispatchToProps)(ContainerComponent);

Now when you call your components you can simply call the value passed in like so.

export default class PresentationComponent extends React.Component {
render() {
    return (      
        <div>
<span>{this.props.value}</span>
<button onClick={this.props.onIncrement}>Increment</button>
<button onClick={this.props.onDecrement}>Decrement</button>
        </div>
    );
  }
}

For more information you can checkout both of these github projects for reference.

JavaScript has become Java, sigh…

  • If I wanted to work with compiled languages, I would have stuck with Java.
  • If I wanted complicated build systems, I would have stuck with Java.
  • If I wanted complicated all encompassing frameworks, I would have stuck with Java.
  • If I wanted complicated unreadable error messages, I would have stuck with Java.
  • If I wanted to run server side code (Node) in my browser, I would have stuck with Java.

Something needs to happen to fix JavaScript making it more and more like Java is not the answer. Or is it time to move to another language with less ceremony???

libopenzwave.so error

If you’ve ever seen this error:

MinOZW: error while loading shared libraries: libopenzwave.so.1.3: cannot open shared object file: No such file or directory

or 

Error: libopenzwave.so.1.3: cannot open shared object file: No such file or directory

Just type this and it did the trick for me (Ubuntu 14.04).

sudo ldconfig /usr/local/lib64

 

Openzwave Binary Sensors

I’ve been struggling a bit with openzwave items because its so poorly documented. I’ve finally figured out how to get results from a door sensors with the node package node-openzwave-shared.

If you follow the install script, then just add this event handler below, you can receive updates.

zwave.on('node event', function(nodeid, nodeEvt) {
 console.log(new Date(), 'node event', nodeid, nodeEvt);
});

More live examples coming soon here: https://github.com/scottpreston/node-openzwave-examples

And via npm via npm-install node-openzwave-examples

Simple WebSocket & NodeJS Server Example

I’ve been searching for a NodeJS server for web sockets, but socket.io, required both the client and server to be run from within node. I wanted to connect to this server via a normal web page using WebSockets from HTML5. Here’s some code, hope you find it useful:

https://github.com/scottpreston/examples

Server Code

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 3000});

wss.on('connection', function (ws) {
    ws.on('message', function (message) {
        console.log('received: %s', message);
        ws.send(message + "!!!!");
    });
});

Client Code

    var websocket = new WebSocket('ws://localhost:3000');
    websocket.onopen = function (evt) {
        websocket.send("This Rocks!");
        websocket.close();
     }
    websocket.onmessage = function (evt) {
        console.log('RESPONSE: ' + evt.data);
    };

 

Home Grown Script Loader

I was wondering how RequireJS and AMD worked. So I created this snip. It might not be correct but it worked for me.

load('foo', function (foo){
        var f = new foo();
        f.a = 100;
        f.b = 200;
        alert(f.add());
    });

    function define(name, callback) {
        modules[name] = callback;
    }

    function load(file, callback) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.src = file + ".js";
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
        script.onload = function() {
            callback(modules[file]);
        };
    }

    var modules = [];

// foo.js
define("foo", function() {
    var foo = {
        a: 1,
        b: 2,
        add: function () {
            return this.a + this.b;
        }
    };
    return foo;
});

Google Maps, Not Showing, Grey Box?

I was working today on a bug with google maps not showing. It turns out it was because I had a css with overflow:hidden.

In order to fix this you’ll need to set the overflow:visible on any css elements for your #{MAP_ID} and subsequent <div> tags.

div#map,div#map div{ overflow:visible;}

A Simple MySQL Trigger Example

I was searching for this a few days back and I was struck at how Google had all these terrible explanations at the top of the results. Here’s a simple way to create and understand triggers in mysql.

CREATE TABLE IF NOT EXISTS `emails` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `emails` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `emails_triggers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `emails` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

DELIMITER $$
CREATE TRIGGER trigger_test AFTER
INSERT ON emails
FOR EACH ROW
BEGIN
 INSERT INTO `emails_triggers` (email) values (NEW.email);
END$$
DELIMITER ;

insert into emails values('test@test.com');
select * from emails_trigger;

Just a note: the DELIMITER keyword is used via a tool like PhpMyAdmin or the MySQL Client. I could not get this keyword to be recognized by my SQL editor and had problems until I just pasted it via PhpMyAdmin.

The JavaScript Module Pattern

One thing that really bothers me is often how obtuse programmers explain relatively simple things. Take for example the JavaScript Module Pattern.

<script type="text/javascript">
    var module = (function () {
        var foo = 0;
        return {
            bar:function () {
                foo = foo + 1;
                alert(foo);
            }
        };
    }());

    module.bar();
    module.bar();
</script>

This is really just two things:

  1. An anonymous function which allows for immediate execution.
  2. Returning a function, which behave like “public variables/methods”, keeping the other functions/properties inside the module which behave like “private variables/methods”

That’s it, no need to explain this with 5 pages of explanation about encapsulation, etc.

Simple HTML5 Webcam Example

Here’s a quick example that shows you how to access your web camera with HTML5 and JavaScript. (Works in Chrome 21).

<video autoplay id="vid" style="display:none;"></video>
<canvas id="canvas" width="640" height="480" style="border:1px solid #d3d3d3;"></canvas><br>
<button onclick="snapshot()">Take Picture</button>

<script type="text/javascript">

    var video = document.querySelector("#vid");
    var canvas = document.querySelector('#canvas');
    var ctx = canvas.getContext('2d');
    var localMediaStream = null;

    var onCameraFail = function (e) {
        console.log('Camera did not work.', e);
    };

    function snapshot() {
        if (localMediaStream) {
            ctx.drawImage(video, 0, 0);
        }
    }

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    window.URL = window.URL || window.webkitURL;
    navigator.getUserMedia({video:true}, function (stream) {
        video.src = window.URL.createObjectURL(stream);
        localMediaStream = stream;
    }, onCameraFail);

</script>

Just cut and paste the code above into your browser and you should be good to go. Also to view the video just set style of the video tag to inline or block.