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
Angular

Speeding up Angular development with Yeoman

Yeoman helps you to kickstart new projects, prescribing best practices and tools to help you stay productive.

To do so, we provide a generator ecosystem. A generator is basically a plugin that can be run with the `yo` command to scaffold complete projects or useful parts…

First, install Yeoman with npm:

npm install yo -g

Now you need a “generator”, and most likely you’ll need grunt:

npm install -g generator-angular grunt

If you get the error like The package generator-karma does not satisfy its siblings’ peerDependencies requirements then try uninstalling generator-karma:

npm uninstall -g generator-karma

and running the previous npm install command again.

Btw,  you can use Yeoman’s CLI (by first executing yo) to search and install any of the existing generators.

To scaffold a new app, create some folder and execute the following command:

yo angular myApp

Yeoman will ask you few questions to which you can all give a default answer and it will start the installation process. After the installation is done you can do:

grunt serve

to actually see a live preview of your scaffolded app.

If you get an error like Warning: Couldn’t find the `compass` binary. Make sure it’s installed and in your $PATH Use –force to continue install it with (if you’re on Mac):

sudo gem install compass

Additional cool thing is that this generator comes with extra tools for quick scaffolding of routes, controllers, views, directives, services, filters… Be sure to check the project on GitHub for more info.

For example, the following command generates a controller and a view, and configures a route in app/scripts/app.js connecting them.

yo angular:route myroute

 

Stack Overflow

How can I make sure that DELETE SQL statement in Postgres using PHP was successfull?

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 question was:

Is there a function which would return true of false based on if the DELETE SQL statement succeded or not? For example something like this:

<?php
    $sql = "DELETE FROM table WHERE id=123";
    $result = pg_query($sql);

    if **function**($result)
        return true;
    else
        return false;
?>

The answer, by LolCoder, was:

Use mysql_affected_rows() to get number of affected rows in mysql.

Similary for postgres, it will be pg_affected_rows.

NodeJS, Quick tips

Keep your Node.js scripts running with Forever and Nodemon

edit (18.06.2015): Nowdays I’m using PM2, and here’s my post that explains how to use PM2.


Nodemon is a utility that will monitor for any changes in your source and automatically restart your server.  Install with npm:

npm install -g nodemon

Forever is a simple CLI tool for ensuring that a given script runs continuously (i.e. forever). Install with npm:

npm install -g forever

Forever & Nodemon running together:

forever start nodemon --exitcrash app.js

edit (24.02.2015):

If you get an error like this:

error:   Cannot start forever
error:   script /home/nikola/nodemon does not exist.

Try to run nodemon with the full path:

forever start /usr/bin/nodemon --exitcrash app.js

You can find out the path to nodemon by executing:

which nodemon
Stack Overflow

Writing small data to file and reading from it or query the database

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 question was:

I have a situation where I would have to query the database for some data which is the same for all users and changes daily, so I figured I could make a file in which I would save this data (once per day) and then load it from that file each time a user visits my site.

Now, I know that this is a common practice (caching) when the requests from database are big but the data I’m about to write to the file is a simple 3 digit number, so my question is should this still be faster or is it just an overkill and I should stick with the database query?

 The answer, by Dukeling, was:

Caching, when done right, is always faster.

It depends how long storing and retrieving data from the file takes and how long requests to the database takes.

If the database query to get the number takes long, then caching may be a good idea, since the data is small.

If you were to do a search (e.g. sequential) in a file with lots of cached data (which doesn’t seem to be the case), it would take long.

Disk I/O could be slower than database I/O (which is unlikely, unless it’s a local DB).

Bottom line – benchmark.

For your scenario, caching is probably a good idea, but if it’s only a single 3-digit number for all users then I’d just try to stick it in RAM rather than in a file.

NodeJS

How to use Redis with Node.js

Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

Comparison with Memcache and Memcached can be found here, and the naming distinction can be found here.

You can download the installation zip file here (I used the Windows version), and extract it to C:\redis. To run the Redis server (in order to be able to save to it and query it) you have to execute the redis-server.exe from this directory.

To use Redis with Node.js you have install the redis module:

npm install redis

A simple usage example:

var redis = require("redis"),
    client = redis.createClient();

// if you'd like to select database 3, instead of 0 (default), call
// client.select(3, function() { /* ... */ });

client.on("error", function (err) {
    console.log("Error " + err);
});

client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
    console.log(replies.length + " replies:");
    replies.forEach(function (reply, i) {
        console.log("    " + i + ": " + reply);
    });
    client.quit();
});

A lot more examples here.

Unity3D

Sharing data between scenes in Unity3D

Here’s I’m going to show you steps on how to share your data between scenes in Unity3D

  1. In the starting scene make a new empty object and name it GameData.
  2. Add a script named GameController with the following content:
    #pragma strict
    
    private var data : Array;
    
    function Awake () {
    	DontDestroyOnLoad (this);
    }
    
    function Start () {
    	data = new Array();
    	
    	GetNewResults();
    }
    
    function GetNewResults(){
    	var www : WWW = new WWW ("http://localhost/check");
    	
    	yield www;// Wait for download to complete
    	
    	var dataJson = JSON.Parse(www.data);
    	var novi = dataJson["data"].Value;
    	data = dataJson["someMoreData"];
    	
    	if (novi == "true"){	
    		Application.LoadLevel(Application.loadedLevel + 1);
    	}
    	else{
    		Debug.Log("false");
    	}
    }
    
    public function getData(){
    	return data;
    }

    The most important part is DontDestroyOnLoad(this) which does not destroy this object once a new scene is loaded.

  3. Then, in another scene, in some script do the following to fetch the data:
    var data = GameObject.Find("GameData").GetComponent(GameController).getData();

     

 

Ionic

Create icons and splash screen automatically with ionic resources

In Ionic framework you can use the

ionic resources

command to automatically generate icons and splash screen of different sizes and for optionally different platforms (iOS, Android).

All you have to do is place the icon.png and splash.png in the resources folder in the root of the application and execute the aforementioned command. Ionic will generate the needed configuration in the config.xml file. More about it on the official blog post.

CodeProject, Unity3D

Quick tip on how to use custom fonts in Unity3D

In this post I’m going to show you how to use custom fonts in Unity3D.

TimerTime

demo  forkMe

  1. Create a new project
  2. Save scene (CTRL + s) and name it whatever you wish
  3. Download some free font from the web (I used Texas Grunge from dafont.com):
    FontImportUnity
  4. Create a new folder called Fonts in the Assets folder and drag the .ttf  file inside
    FontImportUnity_2
  5. Adjust the size of the Camera to 8:
    CameraSize
  6. Hierarchy->Create->UI->TextAddingText
  7. Click on Canvas in Hierarchy and set the Render Mode and select your Render Camera:CanvasRenderMode
  8. Click on Text and change the settings (Rect Transform – resize the text to match the canvas size and drag the anchors in all 4 corners, Text, Font, Best Fit, Max Size):
    FontImportUnity_4
Stack Overflow

When I click the next page in datatables my jquery selectors aren’t working anymore

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 question was:

I’m using datatables plugin for jquery to show my data on the page. I have this selector when someone clicks on a row:

$('#myTable tr[class !="tableHeader"]').click(function(){
    alert("clicked!");
}

and everything is OK until I click on the “Next page” which shows me next 10 results – then this click function doesn’t show “clicked” message box anymore no matter which row I click.

I’m guessing that the problem is in a way how these new results (rows in the table) are shown, so please give me some ideas on how to solve this.

 The answer, by ghayes, was:

Use jQuery’s Live function. Live will apply to all elements on the page, even ones that don’t exist yet (I assume this is your issue). Thus, your new rows will be clickable when they are created and added to the DOM.

$('#myTable tr[class !="tableHeader"]').live('click',function(){
  alert("clicked!");
});
CodeProject, Unity3D

How to create a countdown timer and show current time in Unity3D

In this post I’m going to show you how to create a countdown timer and show current time in Unity3D.

TimerTime

demo  forkMe

  1. Create a new 2D project:
    unityCreateNewProject
  2. Optionally download some background image (I used this one) and drag it to the Assets folder:
    assetsFolder
  3. Drag the background image to the Hierarchy:
    Hierarchy
  4. Adjust the size of the Camera to 8:
    CameraSize
  5. Hierarchy->Create->UI->Text:
    AddingText
  6. Click on Canvas in Hierarchy and set the Render mode:
    CanvasRenderMode
  7. Click on Text and change the settings (Positions, Width, Height, Text, Font Site):
    textSettings
  8. Rename the Text to TimerText
  9. Duplicate the TimerText and rename to TimeText:
    duplicate
  10. Change y position of TimeText to -200:positionChange
  11. Hierarchy -> Create -> Create Empty:
    CreateEmpty
  12. Rename it to GameController
  13. Inspector -> Add Component -> New Script (name it Timer and select JavaScript):
    AddScript
  14. Paste the following code:
    #pragma strict
     
     var timer: float = 70;
     var isFinishedLevel : boolean = false;
     public var displayText : UnityEngine.UI.Text;
     public var timeText : UnityEngine.UI.Text;
     
     var minsDisplay : String;
     var secsDisplay : String;
     
     var mySeconds : int = 0;
     
     private var oldTimer : float;
     
     function Start(){
         oldTimer = timer;
     }
     
     function Update()
     {
         if (!isFinishedLevel) {
             timer -= Time.deltaTime;
         } 
         
         CurrentTime();
     }
     
     function CurrentTime() { 
         var dt : System.DateTime = System.DateTime.Now;
         var h : int = dt.Hour; 
         var m : int = dt.Minute; 
         var s : int = dt.Second;
     
         timeText.text = h + ":" + m + ":" + s;
         
         if(mySeconds != s)
         {
             mySeconds = s;
             Timing();
         }
         
     }
     
     function Timing()
     {
         if (timer > 0) {
             //var minsDisplay : String = parseInt( timer / 60 ).ToString();
             minsDisplay = parseInt( timer / 60 ).ToString();
             
             //var secsDisplay : String = parseInt( timer ).ToString();
             secsDisplay = parseInt( timer ).ToString();
              
             if ( (timer - ( parseInt(minsDisplay) * 60)) > 10 ) {
                  secsDisplay = parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString();
             } 
             else {
                 secsDisplay = "0" + parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString();
             }
             
             //displayText.text = minsDisplay + " : " + secsDisplay;
         } 
         else {
              timer += oldTimer;
         }
         displayText.text = minsDisplay + " : " + secsDisplay;
     }
  15. Drag TimerText and TimeText to the script from Hierarchy:
    dragging
  16. [le problems] – Run the program, and you’ll run into few issues:
    1. If you open up any other window you will notice that the timer will stop, and continue counting once you return to the Unity window [edit: this seems to be expected behavior and in order to “fix” this, you have to set the “Edit -> Project Settings -> Player -> Run In Background” option (from here)]
    2. TimerText and TimeText are not “ticking off” at the same time [edit: this is now also fixed and the code is updated with the fix]
  17. If someone has info on how to solve this, please comment and I’ll update the post once the solution is found [edit: both issues have been resolved thanks to Unity Answers, I’m just leaving them here for some future reference].
Page 40 of 51« First...102030«39404142»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