Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Miscellaneou$

100th post

Nothing, just saying 🙂

Ok, jokes aside, this has been a nice journey for me. It all started with the post Carcassonne scoring board application which I decided to post after reading James Clear’s post on why we should make things.

Top 10  popular posts until now:

  • How to get started on the MEAN stack (written for HackHands.com and featured in NodeWeekly)
  • Delving into Node.js and Express web framework (written for HackHands.com)
  • MEAN.io VS MEAN.js and deploying the latter on DigitalOcean (written for HackHands.com)
  • Deploying MongoDB and Node.js application on OpenShift (written for CodeProject.com)
  • How I built my own testable The Answer To Life The Universe And Everything npm module (written for CodeProject.com)
  • Build a font viewer application in WPF without writing any C# code (written for CodeProject.com)
  • Using CasperJS on Webfaction to automatically send emails with attached images via Gmail (written for CodeProject.com)
  • How to delete node_modules folder on Windows machine
  • Enable continuous scrolling by default in Adobe Reader
  • Git push origin master could not read username for http://github.com

 

Programming

Notes from the book Game development with Three.js by Isaac Sukin

My notes from the book Game development with Three.js by Isaac Sukin:

Three.js is usually used with a new technology called WebGL, a JavaScript API for rendering graphics without plugins. The API is based on OpenGL, a desktop graphics API (GL stands for graphics library).

Because it uses the client’s graphics processing unit to accelerate rendering, WebGL is fast! However, many mobile browsers as well as Internet Explorer 10 and below do not support WebGL. Luckily, Three.js supports rendering with the HTML5 Canvas API as well as other technologies such as Scalable Vector Graphics instead.

<!DOCTYPE html>
<html>
	<head>
		<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r57/three.min.js"></script>
	</head>
	<body>
		
		<script>
			var camera, scene, renderer;
			var geometry, material, mesh;

			var init = function () {

				renderer = new THREE.CanvasRenderer();
				renderer.setSize( window.innerWidth, window.innerHeight );
				document.body.appendChild( renderer.domElement );

				camera = new THREE.PerspectiveCamera( 95, window.innerWidth / window.innerHeight, 1, 5000 );
				camera.position.z = 900;

				scene = new THREE.Scene();

				geometry = new THREE.CubeGeometry( 100, 100, 100 );
				material = new THREE.MeshNormalMaterial( { color: 0x000000, wireframe: true, wireframeLinewidth: 2 } );

				mesh = new THREE.Mesh( geometry, material );
				scene.add( mesh );
			}

			var animate = function () {

				requestAnimationFrame( animate );

				mesh.rotation.x = Date.now() * 0.001;
				mesh.rotation.y = Date.now() * 0.001;

				renderer.render( scene, camera );

			}

			init();
			animate();
		</script>
	</body>
</html>

The renderer creates a new <canvas> element by default that should be added to the DOM. Avoid changing the canvas’ size with CSS; use the renderer’s setSize method instead, which sets the width and height HTML attributes on the canvas element.

This is because CSS describes the display size but not the render size. That is, if the canvas is rendered at 800 x 600, but the CSS shows it at 1024 x 768, the rendering will be stretched to fill the space just like if you specified the CSS size of an image to be larger than its true size. This can result in distortion and difficulty converting between “screen space” and “canvas space.”

The one last thing we need is a camera object as shown in the following code snippet, which is something Three.js uses to tell the renderer from what perspective the scene should be displayed. If the player was standing in your virtual world and their screen represented what they could see, camera would be their eyes, renderer would be their brain, and scene would be their universe.

All objects are initialized at the position (0, 0, 0), also called the origin. The key here is requestAnimationFrame(), which executes the function passed to it when the browser is ready to paint a new frame. Geometries are instances of THREE.Geometry that define the shape of an object in a scene. They are made up of vertices and faces (which are themselves objects and are accessible through the vertices and faces array properties). Vertices are the THREE.Vector3 objects representing points in three-dimensional space, while faces are the THREE.Face3 objects representing triangular surfaces.

Triangle:

var geo = new THREE.Geometry();
geo.vertices = [
    new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(0, 100, 0),
    new THREE.Vector3(0, 0, 100)
];

geo.faces.push(new THREE.Face3(0, 1, 2));
geo.computeBoundingSphere();

3D:

THREE.Sphere(radius, horizontalSegments = 8, verticalSegments = 6)

THREE.Icosahedron(radius, detail = 0);
THREE.Octahedron(radius, detail = 0);
THREE.Tetrahedron(radius, detail = 0);

THREE.CylinderGeometry(radiusTop, radiusBottom, height, radiusSegments = 8, heightSegments = 1, openEnded= false)

THREE.TorusGeometry(radius, tubeWidth = 40, radialSegments = 8, tubularSegments = 6)

THREE.TorusKnotGeometry(radius, tubeWidth = 40, radialSegments, tubularSegments, p = 2, q = 3, heightScale = 1)

2D:

Plane THREE.PlaneGeometry(width, height, widthSegments = 1, heightSegments = 1)

Circle THREE.CircleGeometry(radius, numberOfSides = 8)

Ring THREE.RingGeometry(innerRadius, outerRadius, radialSegments = 8, ringSegments = 8)

Extruding:

var triangle = new THREE.Shape([
new THREE.Vector2 (0, 50),
new THREE.Vector2 (50, 50),
new THREE.Vector2 (50, 0)
]);
var geometry = new THREE.ExtrudeGeometry(triangle, {
bevelEnabled: false,
amount: 30
});

Custom fonts must be in the typeface.js format (you can convert OpenType and TrueType fonts to Typeface format at http://typeface.neocracy.org/fonts.html). Use the following code to create text geometry:

new THREE.TextGeometry("Text message goes here", {
    size: 30,
    height: 20, // extrude thickness
    font: "helvetiker", // font family in lower case
    weight: "normal", // or e.g. bold
    style: "normal", // or e.g. italics
    bevelEnabled: false
});

Procedural city:

var camera, scene, renderer;

function setup() {
    document.body.style.backgroundColor = '#d7f0f7';
    setupThreeJS();
    setupWorld();
    requestAnimationFrame(function animate() {
        renderer.render(scene, camera);
        requestAnimationFrame(animate);
    });
}

function setupThreeJS() {
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.y = 400;
    camera.position.z = 400;
    camera.rotation.x = -45 * Math.PI / 180;
    renderer = new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
}

function setupWorld() {
    // Floor
    var geo = new THREE.PlaneGeometry(2000, 2000, 20, 20);
    var mat = new THREE.MeshBasicMaterial({color: 0x9db3b5, overdraw:true});
    var floor = new THREE.Mesh(geo, mat);
    floor.rotation.x = -90 * Math.PI / 180;
    scene.add(floor);
    // Original building
    var geometry = new THREE.CubeGeometry(1, 1, 1);
    geometry.applyMatrix(new THREE.Matrix4().makeTranslation(0, 0.5,0));

    var material = new THREE.MeshDepthMaterial({overdraw: true});
    // Cloned buildings
    for (var i = 0; i < 300; i++) {
        var building = new THREE.Mesh(geometry.clone(), material.clone());
        building.position.x = Math.floor(Math.random() * 200 - 100) * 4;
        building.position.z = Math.floor(Math.random() * 200 - 100) * 4;
        building.scale.x = Math.random() * 50 + 10;
        building.scale.y = Math.random() * building.scale.x * 8 + 8;
        building.scale.z = building.scale.x;
        scene.add(building);
    }
}

// Run it!
setup();

Fog:

scene.fog = new THREE.FogExp2(0x9db3b5, 0.002);

Only the DirectionalLight and PointLight objects can cast shadows. Casting shadows first requires that we enable shadows on the renderer:

renderer.shadowMapEnabled = true;

For our city scene, we’ll enable shadow receiving for our floor and both casting and receiving for our buildings:

floor.receiveShadow = true;
city.castShadow = true;
city.receiveShadow = true;

Finally, we configure our DirectionalLight object to use shadows:

light.castShadow = true;
light.shadowDarkness = 0.5;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
light.position.set(500, 1500, 1000);
light.shadowCameraFar = 2500;

// DirectionalLight only; not necessary for PointLight
light.shadowCameraLeft = -1000;
light.shadowCameraRight = 1000;
light.shadowCameraTop = 1000;
light.shadowCameraBottom = -1000;

Earlier, we switched from CanvasRenderer to WebGLRenderer in order to support shadows and fog. As a rule of thumb, WebGLRenderer is faster and has the most features, while CanvasRenderer has fewer features but broader browser support. One particularly nice feature of WebGLRenderer is that it supports antialiasing to smooth out jagged edges. We can enable this for our cityscape by passing the option in to the renderer constructor:

renderer = new THREE.WebGLRenderer({antialias: true});

Already written navigation from examples:

<script src="FirstPersonControls.js"></script>

Add timer:

clock = new THREE.Clock();
controls = new THREE.FirstPersonControls(camera);
controls.movementSpeed = 100;
controls.lookSpeed = 0.1;

Add this to requestAnimationFrame:

controls.update(clock.getDelta());

Clicking on the screen in order to select or interact with something is a common requirement, but it’s somewhat harder than it sounds because of the need to project the location of the click in the 2D plane of your screen into the 3D world of Three.js. To do this, we draw an imaginary line, called a ray, from the camera toward the position where the mouse might be in 3D space and see if it intersects with anything. In order to project, we first need a projector:

projector = new THREE.Projector();

Then we need to register a listener on the click event for the canvas:

renderer.domElement.addEventListener('mousedown', function(event) {
var vector = new THREE.Vector3(
renderer.devicePixelRatio * (event.pageX - this.offsetLeft) /
this.width * 2 - 1,
-renderer.devicePixelRatio * (event.pageY - this.offsetTop) /
this.height * 2 + 1,
0
);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(
camera.position,
vector.sub(camera.position).normalize()
);
var intersects = raycaster.intersectObjects(OBJECTS);
if (intersects.length) {
// intersects[0] describes the clicked object
}
}, false);

The last thing you want when your player is clicking madly to shoot at enemies is for the whole screen to suddenly turn blue because the browser thinks the user is trying to select something. To avoid this, you can either cancel the select event in JavaScript with document.

onselectstart = function() { return false; }

or disable it in CSS:

* {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

Colission libraries:

  • Ammo.js is a large but complete library compiled to JavaScript from C++. It is available at https://github.com/kripken/ammo.js/
  • Cannon.js is a smaller library written from scratch in JavaScript and inspired in part by concepts from Three.js. It is available at https://github.com/schteppe/cannon.js
  • Physi.js is a bridge between Ammo or Cannon and Three.js that also runs the physics simulation in a separate thread to avoid blocking the rendering. It is available at https://github.com/chandlerprall/Physijs

Well, tbh, stopped at page 61/100 as the examples from the book didn’t quite work for me so all in all very disappointed with the book in that department. But, as far as the writing and explanations up till this point go I think it was good. Grade: 2.7/5  

Books

Legion: Skin deep – Brandon Sanderson

My favourite quotes from the book Legion: Skin deep by Brandon Sanderson:

Always tell your captives they have more time than they do. It makes them relaxed. Sets them to planning instead of trying to break out immediately. The last thing you want to do is to make them desperate, since desperate people are unpredictable.

Anything that is possible is actually a reality given infinity.

Miscellaneou$

Sleep you must, yoda so says

Post from James Clear here: http://jamesclear.com/better-sleep

In the words of the researchers, sleep debt “has a neurobiological cost which accumulates over time.” After one week, 25 percent of the six-hour group was falling asleep at random times throughout the day. After two weeks, the six-hour group had performance deficits that were the same as if they had stayed up for two days straight. Let me repeat that: if you get 6 hours of sleep per night for two weeks straight, your mental and physical performance declines to the same level as if you had stayed awake for 48 hours straight.

The irony of it all is that many of us are suffering from sleep deprivation so that we can work more, but the drop in performance ruins any potential benefits of working additional hours.

Stack Overflow

Should I use Node.js only or behind Apache or Nginx

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

I wondered about basically the same quesiton as user 7cows had: In what cases should one prefer to use Node.js only as a server in real deployment? When one does not want to use Node.js only, what plays better with Node.js, Apache or Nginx?

The answer, by pauljz, was:

There are several good reasons to stick another webserver in front of Node.js:

  • Not having to worry about privileges/setuid for the Node.js process. Only root can bind to port 80 typically. If you let nginx/Apache worry about starting as root, binding to port 80, and then relinquishing its root privileges, it means your Node app doesn’t have to worry about it.
  • Serving static files like images, css, js, and html. Node may be less efficient compared to using a proper static file web server (Node may also be faster in select scenarios, but this is unlikely to be the norm). On top of files serving more efficiently, you won’t have to worry about handling eTags or cache control headers the way you would if you were servings things out of Node. Some frameworks may handle this for you, but you would want to be sure. Regardless, still probably slower.
  • As Matt Sergeant mentioned in his answer, you can more easily display meaningful error pages or fall back onto a static site if your node service crashes. Otherwise users may just get a timed out connection.
  • Running another web server in front of Node may help to mitigate security flaws and DoS attacks against Node. For a real-world example, CVE-2013-4450 is prevented by running something like Nginx in front of Node.

I’ll caveat the second bullet point by saying you should probably be serving your static files via a CDN, or from behind a caching server like Varnish. If you’re doing this it doesn’t really matter if the origin is Node or Nginx or Apache.

Caveat with nginx specifically: if you’re using websockets, make sure to use a recent version of nginx (>= 1.3.13), since it only just added support for upgrading a connection to use websockets.

Also, user Matt Sergeant added:

Just to add one more reason to pauljz’s answer, I use a front end server so that it can serve up 502 error pages when I’m restarting the backend server or it crashes for some reason. This allows your users to never get an error about unable to establish a connection.

Stack Overflow

Get/Set values of dynamical generated input fields using ng-repeat in Angular

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I have an input field which once filled with a number populates that count of additional input fields. I can’t figure out how to get the values inserted in those generated input fields. Any help is appreciated, and oh, I did try various things and even with angular.element, or solely with jquery, but failed, so any explanation on how to do this is welcome.

Here is my jsfiddle, and the code c/p-ed here:

<div ng-controller="MyCtrl">
    <input type="text" ng-model="cntInputs" placeholder="#Inputs"><br/>

    <input ng-repeat="i in getTimes()" type="text" placeholder="{{i}}" id="input_{{i}}">

    <ul>
        <li ng-repeat="j in getTimes()">
            Inputed value is: {{getValue(j)}}
        </li>
    </ul>
</div>

js:

var myApp = angular.module('myApp', []);


function MyCtrl($scope) {
    $scope.cntInputs = 0;

    $scope.getTimes=function(){
        var a = new Array();

        for(var i=1; i <= $scope.cntInputs; i++)
            a.push(i);

        return a;       
    };

    $scope.getValue = function(id){
        //here get the value of that inserted in the element with the id of "input_" + id
        return angular.element("input_" + id);
    }
}

The answer, by James Kleeh, was:

So add ng-model="inputs[i-1]" to your text field

Then in your controller add $scope.inputs= [];

Then in your getValue function: return $scope.inputs[id-1];

If you make your getTimes function 0 based you wouldn’t need the -1s

Updated your fiddle: http://jsfiddle.net/7MhLd/60/

Books

Storm Front – Jim Butcher

The only quote I liked from the book Storm Front by Jim Butcher:

I made a vampire cry. I felt like a real super hero now. Harry Blackstone Copperfield Dresden, breaker of monster’s hearts.

Stack Overflow

Webkitdotnet unable to load https site

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I am using this webkitdotnet in my C# project. It all went well until I had to use access site with https.

I’ve searched their forum and found few posts about this but none of it solves my problem, so please shed some light on this one. Thx!

edit: Also as mentioned in their threads (also without an answer) I get a “Peer certificate cannot be authenticated with known CA certificates” error when trying to access my server, buthttps://www.google.com works fine.

They also mention the “apple” build which worked fine with ssl (at least so they say), but I can’t find it anywhere…

The answer, by therealmitchconnors, was:

This is a bit of a hack, but you can make webkitdotnet ingore peer ssl errors. WebKitDotNet uses WebKit, which, in turn uses curl, which is responsible for your wonderful ssl error there. curl exposes an option to ignore ssl errors, but neither webkit nor webkitdotnet seem to expose this functionality in their api. However, if you checkout the webkit source code, webkit sets the curl option (CURLOPT_SSL_VERIFYPEER) to false if the value of the environment variable WEBKIT_IGNORE_SSL_ERRORS is set to true.

What this all boils down to is that if you set the environment variable in code before initializing either webkit or webkitdotnet components, webkit will ignore the bad certificate and allow you to navigate to the site (sort of like clicking Proceed Anyway on IE9’s Bad Certificate Warning page).

C++:

setvar("WEBKIT_IGNORE_SSL_ERRORS", "1");

C#:

Environment.SetEnvironmentVariable("WEBKIT_IGNORE_SSL_ERRORS", "1");

If anyone is interested, the webkit source code referenced is in file webkit\Source\WebCore\platform\network\curl\ResourceHandleManager.cpp at lines 65 and 681, currently.

CodeProject, NodeJS

How I built my own testable The Answer To Life The Universe And Everything npm module

TL;DR: In this short tutorial I’ll show you how I built my own testable (Jasmine) npm module which I then published to npm repository. The npm module is here, and the GitHub repository is here.

First, if you haven’t already, set some author info in your terminal:

npm set init.author.name "Nikola Brežnjak"
npm set init.author.email "[email protected]"
npm set init.author.url “http://www.nikola-breznjak.com"

Then, create a new GitHub repository, clone it to your disk and then run npm init. Create a index.js file and copy/paste the following code:

module.exports = function(){
    return 42;
}

Next, install Jasmine by doing:

npm install jasmine-node -g

To test your module, create a folder spec, and a file TheAnswerToLifeTheUniverseAndEverything.spec.js inside it with the following content:

var TheAnswerToLifeTheUniverseAndEverything = require('../index.js');

describe("TheAnswerToLifeTheUniverseAndEverything Suite", function() {
 it("should return a value of 42", function(done) {
 var value = TheAnswerToLifeTheUniverseAndEverything();
 expect(value).toEqual(42);
 done();
 });
});

In order to test your module, run jasmine-node spec/ as shown on the image below:

jasmineTest

In order to publish your npm module you first have to execute the npm adduser command and answer few of the questions, and after that you just have to execute npm publish and you’ll have your npm module listed on npmjs.com:

theAnswerToLifeNPMmodule

Now you can use npm install theanswertolifetheuniverseandeverything to install the module.

If you’re testing this your self and you get an error like “Error: forbidden New packages must have all-lowercase names: TheAnswerToLifeTheUniverseAndEverything” then that means what it says – you must use only lowercase letters when naming your modules.

Books

Scream free parenting – Hal Edward Runkel

My favourite quotes from the book Scream free parenting by Hal Edward Runkel:

Parenting is not about kids, it’s about parents. The greatest thing you can do for your kids is learn to focus on yourself.

We are responsible for our children – this is the biggest lie. We have responsibility to our children.

To be in charge as a parent means inspiring children to motivate them selves.

The definition of insanity is doing the same thing over and over again expecting a different result.

Then importance of giving your children increasing space as they age is far greater than the fear of what they will do with that space.

It is your room, clean it if you will.

Let them close the door. Knock before you come in, and await their answer and if it’s NO, come back later.

Give them money, but then teach them about it.

Let them struggle.

You can’t? Man, that sucks, what have you tried so far? After the response ask: so what are you going to do about it?

This is what I think, what do you think?

Wow, you’re bored. That stinks. I hate it when I’m bored too. What are you going to do about it?

After 10 minutes in the car – are we there yet? Wow it looks like you really don’t want to be in the car right now. You know what, me neither – and for whole next two hours! What are we going to do about it?

The very act of homework hovering makes a problem even worse.

Learning from our mistakes is the highest form of education possible.

I told you so – don’t use this.

Integrity. It’s very important for your children to believe that what you say is what you honestly believe and what you will actually do.

Broken body makes it extremely difficult to provide for and protect your children. Your health is your first responsibility. Your self-respect is important, as well as your marriage – your marriage is more important than your kids. Take care of yourself in order to benefit others.

The only way to change the pattern is focusing on your part in it, and then do something different. Don’t wait for others to change – you change and the rest will follow.

Page 42 of 51« First...102030«41424344»50...Last »

Recent posts

  • When espanso Breaks on Long Replacement Strings (and How to Fix It)
  • 2024 Top Author on dev.to
  • Hara hachi bun me
  • Discipline is also a talent
  • Play for the fun of it

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (78)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (41)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak