Sunday, September 3, 2017

PSR-1 and PSR-2 coding standards for PHP

Visual aspects of code play a significant role in raising or drowning developer's productivity. In case that there's too much clutter, no clear patterns and no lots of randomness in style, code reading can be difficult, and even stressful. This is why developers are constructing ways of dealing with the code complexity. They hope it can make everyday programming life easier. And I'd say they have the point. It really is important to have a clean, flowing, easy to read code.

One good example of such a coding standard is PSR-1, and it's extension PSR-2. Some of the rules of these standards are:


  • Files MUST use only <?php and <?= tags.
  • Files MUST use only UTF-8 without BOM for PHP code.
  • Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.
  • Namespaces and classes MUST follow an "autoloading" PSR: [PSR-0, PSR-4].
  • Class names MUST be declared in StudlyCaps.
  • Class constants MUST be declared in all upper case with underscore separators.
  • Method names MUST be declared in camelCase.



More details on these coding standards can be found here and here.

Thursday, August 17, 2017

WordPress - init hook seems to be fired more than once

init hook should be fired only once in WP

If it appears as being fired more than once, it's probably because there was a redirect and/or 404 error (even for a PNG, it's going to trigger the full WP Load).



Also, there might be multiprocess/multithread execution. Every page load can run multiple wp processes in case of 404 errors or redirects! And they can enter a race condition!

Saturday, August 12, 2017

mysql 5.7 - disabling STRICT mode

If your app was written for older versions of MySQL and is not compatible with strict SQL mode in MySQL 5.7, you can disable strict SQL mode. For example, apps such as WHMCS 6 and Craft 2 do not support strict SQL mode.

If you're using WHMCS 7, see our article on customizing MySQL for WHMCS 7.
To disable strict SQL mode, SSH in to your server as root and create this file:

/etc/mysql/conf.d/disable_strict_mode.cnf
Open the file and enter these two lines:

[mysqld]
sql_mode=IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Restart MySQL with this command:

sudo service mysql restart
This change disables two SQL mode settings, STRICT_TRANS_TABLES and ONLY_FULL_GROUP_BY, that were added in MySQL 5.7 and cause problems for some older applications.

Full details here

Friday, August 4, 2017

npm, Homestead, and Windows - EIO npm error - solved

If you are using npm inside of a Homestead box which is being hosted in Windows, and you see a "Exit status 1" error , or EIO error thrown by npm scripts, make sure that you have downloaded the npm packages inside of Homestead box, and not in Windows.

Apparently, there could be some differences in encoding / character set which can result in npm errors inside of Homestead box.

So, inside your Homestead box, remove the node_modules file and re-run npm install. Now you should be able to run npm scripts normally.

Tuesday, August 1, 2017

Laravel Cashier - There are no commands defined in the "cashier" namespace. [Solved]

In Laravel 5.4, when trying to use Laravel\Cashier, the following error can sometimes occur:
There are no commands defined in the "cashier" namespace.

The solution is to manually create the migration file and execute it:

Run this:
php artisan make:migration add_cashier_table_fields
And then, in the created empty file, add this:

[code]

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddCashierTableFields extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //

         Schema::table('users', function ($table) {
            $table->string('stripe_id')->nullable();
            $table->string('card_brand')->nullable();
            $table->string('card_last_four')->nullable();
            $table->timestamp('trial_ends_at')->nullable();
        });
        Schema::create('subscriptions', function ($table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('name');
            $table->string('stripe_id');
            $table->string('stripe_plan');
            $table->integer('quantity');
            $table->timestamp('trial_ends_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->timestamps();
        });
     
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}


[/code]

Now, you can execute the command:
php artisan migrate


Original solution is here:
http://itsolutionstuff.com/post/how-to-solve-there-are-no-commands-defined-in-the-cashier-namespace-in-laravel-5example.html

Friday, July 28, 2017

Homestead - recreate database after it's name being changed in Homestead.yaml

When a database name is changed in Homestead.yaml, this database is not cretead until you run this command:

homestead reload --provision

Sunday, July 23, 2017

MySQL crash recovery - ibdata1 file

It proved to me working in my case:

If you don't have backup.
I think the recommended way to recover that databases is start MySQL with innodb_force_recovery = 4 (or higher values) and dump the databases to a SQL.Then drop it and recover from backup. Instead of dropping the original database I prefer to create the new databases with another name or in another server and check the content first.
STEPS TO BE FOLLOWED
  1. In mysqld section of my.cnf add a line innodb_force_recovery = 4 and then restart MySQL server using /etc/init.d/mysql restart.
  2. Take backup.
  3. Restore it on other server and verify the contents.
Please also have a look at Forcing InnoDB Recovery.
UPDATE : For your comment how to progress on that so that it would not happen again
You should not kill MySQL it is not a good practice that may cause MySQL server to crash,whenever you make any configuration changes you should proceed as follows.
  1. Safely stop MySQL Server using /etc/init.d/mysql stop
  2. Make changes
  3. Restart MySQL Server

Saturday, July 15, 2017

MSSQL - list all foreign tables for a table

Useful command which returns a list of all referenced (foreign) tables for a MSSQL table:

EXEC sp_fkeys 'TableName'

Sunday, July 9, 2017

ReactJS - If componentWillReceiveProps is not firing, double check the syntax of mapStateToProps

In ReactJS, the first obvious reason for componentWillReceiveProps() not firing is the use of mutable data. However, if that's not the case, you should always double check the form of your mapStateToProps() function.

Here, the first example works as expected, but the second one contains a logical, but not syntax error which can be a problem to find sometimes.

EXAMPLE:

CORRECT:

var mapStateToProps=(state)=>({

    curOrder:state.orderEditorReducer.curOrder,


});



INCORRECT (not returning anything, just a function declaration):


var mapStateToProps=(state)=>function(){

  return {

    curOrder:state.orderEditorReducer.curOrder,


  }

};

Friday, July 7, 2017

[solved] - PermError SPF Permanent Error: Unknown mechanism found: -all

Super useful article about SPF records which got rejected by mail servers, although they look valid in validators ( it's all about hyphen sign, which looks similar , but it's not the same in validator and at the actual SPF record registry):

https://www.stephendonaghy.com/?p=29

Friday, June 30, 2017

[SOLVED] - npm install crashes with error code 128

Error scenario:

You are trying to run npm install on an existing git repository, but your npm install stops somewhere at fetchMetadata and throws an error code 128, which doesn't tell you much.

First of all, there are multiple possible causes for error code 128, most of them have something to do with permissions, so make sure you have access permissions and you're using proper ssh key(if any).

However, if that doesn't solve the problem, you might try this:
Try to split the package.json file's dependency list into N subgroups and run npm install on those chunks.

This way, it will download some packages every time, and it won't download them anymore when you run npm install for the next chunk.

I'm not sure what's root cause of this bug, but it seems to be a potential bug in npm v.5.0.0+. This needs some more research, but for the moment, I hope that the trick of splitting the npm install load will do the trick for you!


This was tested with node v8.0.0.0 and v8.1.3  with npm v5.0.0 and v5.1.3.
OS: Ubuntu 16.04
(nvm was used as the node manager, and the package.json contained both free and private git repos hosted at bitbucket and github).

UPDATE:
Possible reason for this error is the too high number of connections npm is trying to open. For some internet routers / connections, it might simply be too much. Currently, there's no official ability to limit max connections from npm, even there were some discussions on this in past. Lets hope this will be added into the newer versions.

Also, npm's error log is very bad at reporting the root cause of this error. In most cases, it simply says error code 128. However, every once in a while, it will print out something like Connection refused, or cannot connect to remote repository - host unknown, or something.

This error has a tendency to show up at large repos , filled with lots of git+ssh entries.

This issue might be somewhat related to this problem too:
https://github.com/npm/npm/issues/7862

sudo npm - command not found


Here is the solution if sudo npm is not working, while npm alone is:


up vote274down voteaccepted
Yes, it is a bit annoying but you can fix it with some links:
sudo ln -s /usr/local/bin/node /usr/bin/node
sudo ln -s /usr/local/lib/node /usr/lib/node
sudo ln -s /usr/local/bin/npm /usr/bin/npm
sudo ln -s /usr/local/bin/node-waf /usr/bin/node-waf
There might be more but that is all I have run across so far. Lack of node-waf will cause some npminstalls to fail with a rather cryptic error message.

Original post here:
ln (link creation function) is documented here:
https://www.computerhope.com/unix/uln.htm

Sunday, June 25, 2017

Session cookie not getting send or saved

If you are experiencing missing Session Cookie while using NodeJS (and probably any other server side framework), remember that:

Your client and your server should be on exactly the same domain. For example, if client is set to  http://127.0.0.1 and connecting to server at http://localhost, cookie won't be saved - Web Browser is going to reject it (rejects Set-Cookie command to protect your safety)


Monday, June 19, 2017

Linux command to copy folder with hidden files

If cp command doesn't seem to work for you, and you see that hidden files are not getting copied to the destination directory, it's probably time to try rsync command!

Instead of:

cp src_dir target_dir -r

You can use:

rsync -av src_dir target_dir

Please note: Trailing slash is super important in rsync sytax. If you omit slash at the end of source directory, a new subdirectory will be created inside of target directory.

Sunday, June 18, 2017

David Allen, natural thinking process is: Why -> Vision -> Brainstorming -> Organization -> Next actions

In his superb book "Getting Things Done", David Allen introduced a phenomenal approach to creative project management. In one important section, he talks about natural order of thinking when looking to complete a non-trivial project. It is a powerful 5-step process:


1. Why

You MUST have a super strong WHY, if you hope to ever complete a complex project. Nothing below makes sense without a very powerful WHY.
If there are problems on lower levels of this hierarchy , always go back and redefine your WHY.


2- Vision of successful outcome

See yourself after the success. Vividly. It opens up your subconscious eyes to see things you've ignored all the time.


3. Brainstorming

This is beginning of How part. Write down, draw down all things that come to your mind for which you believe that could potentially help you realize the successful outcome you envisioned in step #2.

Mind mapping by Tony Buzan can help here.
Make no judgement and no analysis at this step. Every idea is a good idea.


4.Organization

Connect the dots, isolate the processes, streamline actions. Make some Gantt charts if needed.

5. Next actions

Make concrete action plan and execute them. After execution, move to Next action and redo.
Reward yourself for every action completed - it's one step forward to your successful outcome, it's a big thing!



Also, written plan of next actions help us focus and maintain it for a longer period. Most of us cannot focus more than a couple of minutes to the task at hand, without a significant external motivation. This is why written plan of next actions, and the vision of whole project is really helpful - it makes us feel more control over the project and increases our confidence in the whole project.

More tips - Vagrant on windows

These tips are about Vagrant on Windows, coupled with NFS using VirtualBox NFS plugin.

#1 If Vagrant ssh terminal is getting stuck
If your Vagrant ssh terminal is getting stuck all the time, check if you have multiple running vagrants: vagrant global-status and then halt / destroy them by id.

If NFS Enabled and plugin updated , but Vagrant still running slow:
Stop  it(vagrant halt)
Remove winnfsd.exe from memory (using Task manager)
Reload Vagrant machine (vagrant reload)
Try to access VM via IP


#2 If Vagrant VM is slow
Any wrong flag or option in Vagrantfile shared folder settings can degrade your VM's performance by 10x! For example, this is a valid synced folder entry for windows host using NFS:

config.vm.synced_folder ".", "/vagrant", type: "nfs"

Be careful when modifying this basic line, as any extra option can be the cause of slowliness of your VM.

Friday, June 16, 2017

Time saver - Quick fix for non working round() function in PHP

If there are some problems with rounding floats with round() function in PHP, such as too long decimal string, we can safely replace it with function number_format().

For example:

$rounded=round($x, 2);

can be replaced with:

$rounded=number_format($x,2);

Wednesday, June 14, 2017

1 week challenge - Let's not use ALT-TAB shortcut for one week

We all run  dozens of programs running simultaneously. We all use ALT-TAB to  quickly jump between those programs. ALT-TAB looks like a time saver. And it probably is. On the other side, we never consider a potential downside of using this, and other similar, keyboard  shortcuts:

ALT-TAB can severely reduce our concentration and therefore our productivity.

Pressing ALT-TAB will bring a new program to our screen instantly. Computer has no problems with fast context switching. But what about us - human beings? I'm not entirely convinced that we can do a quick context switch, without sacrificing our current thoughts.

Here is my challenge for you:

Can you try to avoid using ALT + TAB for 1 whole week. If you succeed at it, let us know how it felt? Has your productivity soared, jumped a little bit, or degraded?

I'm sure that there are some productivity awards for those who can endure this challenge. :)

Thursday, June 8, 2017

Webpack 2 - You may need an appropriate loader to handle this file type , error

When using webpack 2 with React, if you get a compile time error stating "You may need an appropriate loader to handle this file type.", and pointing to a JSX code block:

Make sure your babel-loader has appropriate include setting value.

An example:

rules:{

    {
         test:/\.jsx?$/,
         use:
         [
           {
                 loader:'babel-loader',
                 options:{presets:['es2015', 'react']},
                 include:__dirname

          ]

   }
}

If include is set to a wrong path (not pointing to your source files), you're likely to see the error above. Tested with weback 2.6.

Tuesday, May 30, 2017

TextView.setText() - be careful with overloaded variations of this method

In Android native development, when using TextView's setText() function, one needs to be careful to use a proper overloaded version.

For example, if you provide a string as the first and only parameter of this function, it will set the label of the component to that string. This is usually what developer wants.

However, if you provde an integer as parameter, then setText() will search for a resource with corresponding Resource ID. It won't simply convert to string and display that value. If the resource is not found, it will throw the following error:

Android Resources$NotFoundException: Resource ID .... not found


Therefore, double check this function:)

ADT - unable to deploy to a Genymotion virtual device

Scenario:

You try to deploy your Android for debugging to a Genymotion virtual phone. Eclipse ADT doesn't react to that action. In the bottom right corner you can see "Android SDK Loader" and nothing like "Launching YOUR APP NAME".

What can be wrong?

Check this:

Make sure your adb is connected to the phone.

If it is, then go to Genymotion window, click inside of it, and press ESC on keyboard, to awake it from sleep. That usually helps. Try to re-run (re-deploy) your app from Eclipse ADT again.

Monday, May 29, 2017

ReactJS - Animating with ReactCSSTransitionGroup

Here are a few very important reminders for ReactJS CSS3 animations using ReactCSSTransitionGroup:

1. Your ReactCSSTransitionGroup should be mounted (rendered) before the content that should be dynamically changed.
This means that ReactCSSTransitionGroup and it's child element(s) must not appear at the same action. For example, if both ReactCSSTransitionGroup and it's child element get mounted at the time when property prop1 gets changed, your animation won't work.

So, child elements need to be mounted later then their parent ReactCSSTransitionGroup.


2. Any change of the child elements visibility must come with it's own unique key. If the child elements have no unique keys, the animations won't appear at all!



Here is a working example:

START OF RENDER FUNCTION


....
....


  var curScreen= this.props.curScreen;

    let outerContainer=null;

    if(curScreen!=null){
       // alert("It is not null. I'm mounting it...");


        outerContainer=(
            <div className={'rc-container-outer ' + curScreen}  key={curScreen+"-screen-step"}>


                <div className='panel panel-default'>
                    <div className='panel-body'>

                        <ProgressBar />




                        <StepContainer curScreen={this.props.curScreen} />







                    </div>
                </div>

            </div>

        );



    }
    else{

        outerContainer=<p  key="22aaaa1">Loading..</p>;
       // alert("It is null....");
    }



....
....
....


                        <ReactCSSTransitionGroup
                            transitionName="rct"



                        >

                                {outerContainer}




                        </ReactCSSTransitionGroup>



....
....

END OF RENDER FUNCTION

Monday, May 22, 2017

WP HTTP Error 403 can be raised by Invalid URL

If your WP Admin replies with http error code 403, and an error message like this:
"Sorry, you are not allowed to access this page"
,
and if you cannot find out the cause for this, check the url you are trying to access. Maybe it is not valid.

In example, this url will generate HTTP status 403:
http://localhost/wptest1/wp-admin/admin.php?page=run-connector?a=3

This will be ok:
http://localhost/wptest1/wp-admin/admin.php?page=run-connector&a=3

Saturday, April 29, 2017

Gradient Descent's role in Linear Regression

Over the past few weeks we opened our discussion of machine learning and neural networks with an introduction to linear classification that discussed the concept of parameterized learning, and how this type of learning enables us to define a scoring function that maps our input data to output class labels.
This scoring function is defined in terms of parameters; specifically, our weight matrix W and our bias vector b. Our scoring function accepts these parameters as inputs and returns a predicted class label for each input data point x_{i}.
From there, we discussed two common loss functions: Multi-class SVM loss and cross-entropy loss (commonly referred to in the same breath as “Softmax classifiers”). Loss functions, at the most basic level, are used to quantify how “good” or “bad” a given predictor (i.e., a set of parameters) are at classifying the input data points in our dataset.
Given these building blocks, we can now move on to arguably the most important aspect of machine learning, neural networks, and deep learning — optimization.
Throughout this discussion we’ve learned that high classification accuracy is dependent on finding a set of weights W such that our data points are correctly classified. Given W, can compute our output class labels via our scoring function. And finally, we can determine how good/poor our classifications are given some W via our loss function.
But how do we go about finding and obtaining a weight matrix W that obtains high classification accuracy?
Do we randomly initialize W, evaluate, and repeat over and over again, hoping that at some point we land on a W that obtains reasonable classification accuracy?
Well we could — and it some cases that might work just fine.
But in most situations, we instead need to define an optimization algorithm that allows us to iteratively improve our weight matrix W.
In today’s blog post, we’ll be looking at arguably the most common algorithm used to find optimal values of W — gradient descent.

http://www.pyimagesearch.com/2016/10/10/gradient-descent-with-python/

Monday, April 24, 2017

Google Drive API Error: The user has not granted the app XXXXX read access to the file YYYYYY

If you get an error like this one:


"error": {
"errors": [
{
"domain": "global",
"reason": "appNotAuthorizedToFile",
"message": "The user has not granted the app 183181265754 read access to the file 0B7unS-zlQOGYcjhnOUJkNDY5Z0E.",
"locationType": "header",
"location": "Authorization"
}
],
"code": 403,
"message": "The user has not granted the app 183181265754 read access to the file 0B7unS-zlQOGYcjhnOUJkNDY5Z0E."
}
}

Make sure you have DRIVE , METADATA and DRIVE_FILE scope permissions set in your client code. Like this (PHP):


define('SCOPES', implode(' ', array(
  \Google_Service_Drive::DRIVE_METADATA,
  \Google_Service_Drive::DRIVE_FILE,
  \Google_Service_Drive::DRIVE
 
 )

For example, if DRIVE is missing, it's going to return that error. Also, make sure that your service account's email is added to share list of the file/folder you're trying to access.

Sunday, April 23, 2017

WPEngine - sessions disabled for non-logged in users


At WPEngine, their caching disables sessions by default. Session ID is being changed all the time by default, for non-logged  in users.

They need to be contacted to enable normal session usage:

https://wpengine.com/support/cookies-and-php-sessions/

They can enable sessions on some pages, and disable them on the rest, which is kinda cool.

Tuesday, April 18, 2017

How to fix external USB HDD for which Windows report: "You need to format the disk in drive X"

If Windows report "You need to format the disk in drive ..." for your NTFS external HDD, then you can try this.

Use Ubuntu or any other Linux, and try to open your disk with it. If Ubuntu gives you an error stating something like partition is smaller than NTFS, you can try to run this tool:

sudo ntfsfix /dev/yourdevice

For example:

sudo ntfsfix /dev/sdb1

If it fails, it should at least  give you some more details on what's wrong with the HDD.

It saved my disk ! :)

Monday, April 17, 2017

For non-SPA pages, make page browsing work without screen flicker

If you would like to avoid screen flicker while the user surfs the site, here are a few ideas:

http://stackoverflow.com/questions/13122769/how-to-browse-between-pages-without-screen-flickering

The main idea to try is this css:

body {
  background: url("Images/sky01.jpg") repeat scroll 0 0 #121210;
  font-family: Verdana,Geneva,sans-serif;
  font-size: 12px;
  margin: 0;
  padding: 0;
}


Tuesday, April 11, 2017

Some tips for Laravel installation on Windows

1.PHP interpreter path and version


If you need to update your php version , just dowload PHP executable and save it to a folder. Add that folder to PATH and make sure it's the first php.exe in the PATH's folder list.
Rename php.ini.development to php.ini and uncomment the extension you need. You will need mbstring and openssl for sure (otherwise composer update will fail).


More tips will be added soon:)


2. Non-Windows related: Accessing external classes added via composer (in Laravel controllers):

Example:

$objReader = \PHPExcel_IOFactory::createReader($type);

Where PHPExcel represents PHPExcel library.

Monday, April 3, 2017

How to make HTML body tag take 100% of height

It's always good to remember how to make body tag to occupy 100% of document height.

Here's a little reminder from Stack Overflow:


up vote202down voteaccepted
In order for a percentage value to work for height, the parent's height must be determined. The only exception is the root element <html>, which can be a percentage height. .
So, you've given all of your elements height, except for the <html>, so what you should do is add this:
html {
    height: 100%;
}
And your code should work fine.
* { padding: 0; margin: 0; }
html, body, #fullheight {
    min-height: 100% !important;
    height: 100%;
}
#fullheight {
    width: 250px;
    background: blue;
}
<div id=fullheight>
  Lorem Ipsum        
</div>

Sunday, March 26, 2017

Updating Redux state doesn't trigger componentWillReceiveProps - solution

Scenario:

React Redux state is changed. However, the component which listens for state changes does not receive a call to componentWillReceiveProps().

Possible cause:

State should be an immutable object. Updates to it should be made by assigning new objects to its properties, not by modifying current properties like mutable objects. You might be passing the same object ( just modified) as the new updated state.

Solution:
Make sure your state is updated by adding a new object, not just by a modification of an existing state object. If you pass the same old object ( by reference), redux won't detect it as a change. This was done to ensure that we use immutable objects for state.


More details here.

Thursday, March 16, 2017

Simultaneous AJAX calls appear to be executed serially - here's a possible explanation

Scenario:

You issue multiple AJAX requests to your ASP.NET (or any other similar Web Server). In Inspector Console, your requests are fired at the same time. However, it appears that one is starting to execute only after one request is finished.

Probable explanation:

Locking at the server side is the probable reason for this behavior. For example, if all your server side scripts access Session object, they need to wait in a queue for Session to become available. Session becomes available only when one of the simultaneous requests is finished. This is why it appears as a serial execution.


One easy workaround:
If you can , declare your ASP.NET MVC controller / page as readonly when it comes to accessing the Session object.


From the Stack Overflow thread:

Session is blocking access to other ones.

This is because session is single threaded per session. Requests to ASP scripts for the same session can only be processed sequentially so only one request will be handled at a time. To stop this you will need to stop using session on the page and turn it off: http://support.microsoft.com/kb/244465/en-us. If you need session you may need to instead use a database.


Details here in this useful forum thread

This same story applies to all shared resources on the server side. One great way to minimize these events, is to  replace Session object with Database.

Tuesday, March 14, 2017

Solution for node error:Cannot find module 'internal/fs' ( for gulp )

Error scenario:

-You run gulp 
-gulp fails with exception "Cannot find module 'internal/fs'"


Probable cause:
-Your node version has been changed recently
It's likely that the gulp script would work with an older version of node. New version you installed won't work with it. There are two options here:
1. To revert to old node version
2. To reinstall node_modules

In this article, we will use option #2.

Fix:
Try to delete all node modules and reinstall them. A command sequence like this would do:

npm cache clean
rm -Rf node_modules/
npm install

More information on this fix can be found here.

Sunday, March 12, 2017

JavaScript fundamentals - pass by value / pass by reference

In this post, I would like to make a few simple examples showing the way JavaScript handles the standard programming language features -  pass by reference and pass by value.

A very good summation of JS behavior in this area is given here at StackOverflow post:

  • Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • However, changing a property of an object referenced by a variable does change the underlying object.
Based on these facts, we can easily resolve the following simple operation:

var a=12;
a=13;

b=a;
b=14;

document.write("A="+a+"<br/>");

document.write("B="+b);
/*
since a and b are primitive types:
a is now 13
b is now 14
*/
Here is a Fiddle of a more complex scenario. This scenario shows an example of dealing with objects and arrays. It's clear that that in case of assignment operation with objects, the JS will behave as any other language which uses "pass by reference":





Wednesday, March 8, 2017

Some notes on redux/ES6/react

-Actions must have type property.The rest of object's properties are arbitrary

-Be careful with exporting classes. They need to be instanced after import.

-Make sure your next state resets the props on which components depend, as componentWillReceivedProps() won't be called unless the prop it's bound to hadn't  been actually changed!

combineStores changes the structure of state object.
Each reducer inside of the combined reducer object gets a property.

For example:

combineReducers{

    appReducer,
    selectActivityReducer
}

will result in a state object like this:

{
    appReducer:{
      //state variables set in appReducer
   }
   ,

   selectActivityReducer:{
      ///state variables set in selectActivityReducer
   }

}




For redux, and react-redux, documentation is incomplete. It's a good idea to look at blogs of some of the key code contributors, or git repos directly.


UI state should be separated from data state, if possible.

UI componentns should be stateless, functional and separated in a special folder.

Container components should be connected to redux store and should receive updates using props. They should call UI components, and set props for them.

Another good idea is to look for blog posts of people who already had problems with Redux/React and who can share some useful concepts and tips. For example, here:
https://medium.com/@docodemore/why-you-don-t-need-react-redux-31b5aebb38a9#.g6b0xmvqt




-Reducers should be pure

Actions are triggered from container components.


If using webpack 2, every loader needs to have suffix -loader when used. For example:

{
  test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
  loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
}

instead of

{
  test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
  loader: 'url?limit=10000&mimetype=image/svg+xml'
}


Import destructuring... ES6

In ES6 import, we need to be careful about a feature called destructuring.

Example:

import MyComp from './MyComp'

import {MyComp} from 'MyComp'

The results of these two statements are not the same.

The second example uses destructuring to extract MyComp from export.default object in MyComp.js.

The first example pulls the whole export.default object.

Details:

http://stackoverflow.com/questions/33524696/es6-destructuring-and-module-imports

mapDispatchToProps - explanation


48down voteaccepted
I feel like none of the answers have crystallized why mapDispatchToProps is useful.
This can really only be answered in the context of the container-component pattern, which I found best understood by first reading:
then
In a nutshell, your components are supposed to be concerned only with displaying stuff. The only place they are supposed to get information from is their props.
Separated out from this is the concern about:
  • how you get the stuff to display,
  • and how you handle events.
That is what containers are for.
Therefore, a "well designed" component in the pattern look like this:
class FancyAlerter extends Component {
    sendAlert = () => {
        this.props.sendTheAlert()
    }

    render() {
        <div>
          <h1>Today's Fancy Alert is {this.props.fancyInfo}</h1>
          <Button onClick={sendAlert}/>
        </div>
     }}
See how this component gets the info it displays from props (which came from the redux store via mapStateToProps) and it also gets its action function from its props: sendTheAlert().
That's where mapDispatchToProps comes in: in the corresponding container
FancyButtonContainer.js
function mapDispatchToProps(dispatch) {
    return({
        sendTheAlert: () => {dispatch(ALERT_ACTION)}
    })
}

function mapStateToProps(state} {
    return({fancyInfo: "Fancy this:" + state.currentFunnyString})
}

export const FancyButtonContainer = connect(
    mapStateToProps, mapDispatchToProps)(
    FancyAlerter
)
I wonder if you can see, now that it's the container [1] that knows about redux and dispatch and store and state and ... stuff.
The component in the pattern, FancyAlerter, which does the rendering doesn't need to know about any of that stuff: it gets its method to call at onClick of the button, via its props.
And ... mapDispatchToProps was the useful means that redux provides to let the container easily pass that function into the wrapped component on its props.
All this looks very like the todo example in docs, and another answer here, but I have tried to cast it in the light of the pattern to emphasize why.
(Note: you can't use mapStateToProps for the same purpose as mapDispatchToProps for the basic reason that you don't have access to dispatch inside mapStateToProp. So you couldn't use mapStateToProps to give the wrapped component a method that uses dispatch.
I don't know why they chose to break it into two mapping functions - it might have been tidier to have mapToProps(state, dispatch, props) IE one function to do both!)




http://stackoverflow.com/questions/39419237/what-is-mapdispatchtoprops

PSR-1 and PSR-2 coding standards for PHP

Visual aspects of code play a significant role in raising or drowning developer's productivity. In case that there's too much clutte...