Zeeshan Ahmad

PHP, LARAVEL, YII, HTML, CSS. TECH BLOG !

5 JavaScript Loops that you want to know about

1. For
2. While
3. Do While
4. For Of
5. For In
BONUS:
1. ForEach
2. For as a While

1. For Loop
This is the most well known Loop and I don’t recall any programming language without it. It has :
1. Counter Initialization
2. Stop condition
3. Step on every iteration


2. While Loop
This loop only focuses on the stopping condition. As long as you pass the condition the execution will still iterate the loop code
Note: When the total score crosses 100 it stopped going further.

3. Do While Loop
This is similar to the While loop except it guarantees that the code will execute once even if the condition is not met initially.
Note: The check is done at the end of execution. I am executing the do loop again after we crossed 100 and still it executed once

4. For Of
For of loop is a for loop with a simpler structure that guarantees to run for all array elements. It doesn’t care about indexes and similar to for each in someway

5. For In
This is a special kind of loop that iterates object keys In case you’re interested in Object properties this can be very helpful to use. You can still use it with Arrays, but ATTENTION that it may not follow the order

Courtesy: https://twitter.com/tobealy

5 platforms to boost your coding skills with online tests and challenges

1. HackerRank
HackerRank is a place where programmers from all over the world come together to solve programming problems. It provides verified solutions you can check at any time and a wide array of programming/coding questions for you to solve.
https://www.hackerrank.com

2. Exercism IO
Exercism is a free platform which aims to provide opportunity for people of all backgrounds to develop their programming skills through practice and mentorship. They cover over 50 languages including JavaScript.
https://exercism.io

3. Codewars
Codewars provides you with ‘kata’ challenges focused on improving skill and technique. Some train programming basics, while others focus on complex problem-solving. They also provide puzzles meant to test your creative problem-solving.
https://www.codewars.com

4. TopCoder
This platform provides a list of algorithmic challenges from the past that you can complete on your own directly online. At TopCoder, you can compete with other programmers as well.
https://www.topcoder.com

5. LeetCode
Leetcode is an interview-based Platform where programming questions are asked directly, to help you prepare for your job interview. Their questions are based on 9 programming languages.
https://leetcode.com

7 online [GUI] tools that will make your CSS coding easier

I bring to you 7 online tools with which you can automate CSS and save yourself some time and hassles. Make sure you read till the end cuz number 6 and 7 are the most powerful.

1. SmolCSS A collection of readymade CSS grid samples you can grab from codepen. Link: http://SmolCSS.dev

2. PxtoEm Convert CSS units easily without having to do guesses.
Link: http://pxtoem.com

3. Getwaves You don’t have to make wavy backgrounds all from scratch. Do it with Getwaves and download it as svg.
Link: http://getwaves.io

4. Animista Play with a collection of readymade CSS animations and copy the codes
Link: https://animista.net/

5. Getcssscan Get readymade beautiful box shadows.
Link: https://getcssscan.com/css-box-shadow-examples…

6. CSS Generator A very powerful GUI tool for generating any CSS you want
Link: https://webcode.tools/generators

Yii2 . FORM How to make dependant drop down. Where second drop downs values are dependant on first drop down selection

In form file :

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?= $form->field($model, 'country_id')->dropDownList(["5"=>'USA', "6"=>"Pakistan"],
['prompt'=>'Select Country',
'onchange'=>'
$.get( "'.yiihelpersUrl::toRoute('/site/getstates').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'state_id').'" ).html( data );
}
);
','class' => 'form-control'
]
); ?>
<?= $form->field($model, 'state_id')
->dropDownList(
[
'prompt'=>'Select State',
]
);
?>

In siteController.php file add a function like below:

public function actionGetstates($id){
$states = StateProvince::find()->where(
[
'country_id'=>$id
]
)->all();

$returnStr = "";
foreach ($states as $state){
$returnStr.="<option value='{$state->state_id}'>{$state->name}</option>";
}

return $returnStr;
}

Java , convert a String to an int

  To convert a string to an in int in java we use Integer.parseInt() function.

Example:

String anyNumber = "15";
int result = Integer.parseInt(anyNumber); 

System.out.println(result); 

int aaa = Integer.parseInt("123456");
See the Java Documentation for more information.
(If you have it in a StringBuilder (or the ancient StringBuffer), you’ll need to do Integer.parseInt(myBuilderOrBuffer.toString()); instead).

 very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.
int aaa;
String StringThatCouldBeANumberOrNot = "2623263hiworld"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "2336263"; //will not throw exception
try {
aaa
= Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
}

try {
aaa
= Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
//No problem this time, but still it is good practice to care about exceptions.
//Never trust user input :)
//Do something! Anything to handle the exception.
}
So, It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

How to undo last commtis on GIT

If you have comitted wrong files to git and you want to undo it, here is what you can do :


$ git commit -m "Some comment here"                         (1)
$ git reset HEAD
~ (2)
<< edit files as necessary >> (3)
$ git add
... (4)
$ git commit
-c ORIG_HEAD (5)

  1. This is what you are looking to undo
  2. This leaves your working tree (the state of your files on disk) unchanged but undoes the commit and leaves the changes you committed unstaged (so they’ll appear as “Changes not staged for commit” in git status and you’ll need to add them again before committing). If you only want to add more changes to the previous commit, or change the commit message1, you could use git reset --soft HEAD~ instead, which is like git reset HEAD~ but leaves your existing changes staged.
  3. Make corrections to working tree files.
  4. git add anything that you want to include in your new commit.
  5. Commit the changes, reusing the old commit message. reset copied the old head to .git/ORIG_HEADcommit with -c ORIG_HEAD will open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the -C option

However, If you don’t need to reset to an earlier commit if you just made a mistake in your commit message. The easier option is to git reset (to unstage any changes you’ve made since) and then git commit --amend, which will open your default commit message editor pre-populated with the last commit message.
Beware however that if you have added any new changes to the index, using commit --amend will add them to your previous commit.

Some Explaination:

Undoing a commit is a little scary if you don’t know how it works. But it’s actually amazingly easy if you do understand.
Say you have this, where C is your HEAD and (F) is the state of your files.
   (F)
A-B-C

master
You want to nuke commit C and never see it again. You do this:
git reset --hard HEAD~1
The result is:
 (F)
A-B

master
Now B is the HEAD. Because you used --hard, your files are reset to their state at commit B.
Ah, but suppose commit C wasn’t a disaster, but just a bit off. You want to undo the commit but keep your changes for a bit of editing before you do a better commit. Starting again from here, with C as your HEAD:
   (F)
A-B-C

master
You can do this, leaving off the --hard:
git reset HEAD~1
In this case the result is:
   (F)
A-B-C

master
In both cases, HEAD is just a pointer to the latest commit. When you do a git reset HEAD~1, you tell Git to move the HEAD pointer back one commit. But (unless you use --hard) you leave your files as they were. So now git status shows the changes you had checked into C. You haven’t lost a thing!
For the lightest touch, you can even undo your commit but leave your files and your index:
git reset --soft HEAD~1
This not only leaves your files alone, it even leaves your index alone. When you do git status, you’ll see that the same files are in the index as before. In fact, right after this command, you could do git commit and you’d be redoing the same commit you just had.
One more thing: Suppose you destroy a commit as in the first example, but then discover you needed it after all? Tough luck, right?
Nope, there’s still a way to get it back. Type git reflog and you’ll see a list of (partial) commit shas that you’ve moved around in. Find the commit you destroyed, and do this:
git checkout -b someNewBranchName shaYouDestroyed
You’ve now resurrected that commit. Commits don’t actually get destroyed in Git for some 90 days, so you can usually go back and rescue one you didn’t mean to get rid of.

Another way of doing it can be following :

Add/remove files to get things the way you want:
git rm classdir
git add sourcedir
Then amend the commit:
git commit --amend
The previous, erroneous commit will be edited to reflect the new index state – in other words, it’ll be like you never made the mistake in the first place.
Note that you should only do this if you haven’t pushed yet. If you have pushed, then you’ll just have to commit a fix normally.

Yet Another approach can be :

This took me a while to figure out, so maybe this will help someone…
There are two ways to “undo” your last commit, depending on whether or not you have already made your commit public (pushed to your remote repository):

How to undo a local commit

Lets say I committed locally, but now want to remove that commit.
git log
commit 101: bad commit # latest commit, this would be called 'HEAD'
commit 100: good commit # second to last commit, this is the one we want
To restore everything back to the way it was prior to the last commit, we need to reset to the commit before HEAD:
git reset --soft HEAD^     # use --soft if you want to keep your changes
git reset --hard HEAD^ # use --hard if you don't care about keeping the changes you made
Now git log will show that our last commit has been removed.

How to undo a public commit

If you have already made your commits public, you will want to create a new commit which will “revert” the changes you made in your previous commit (current HEAD).
git revert HEAD
Your changes will now be reverted and ready for you to commit:
git commit -m 'restoring the file I removed by accident'
git log
commit 102: restoring the file I removed by accident
commit 101: removing a file we dont need
commit 100: adding a file that we need
For more info, check out Git Basics – Undoing Things

Yii2: Using csrf token

Yii2: Using csrf token

First, if you do not understand what is the CSRF token? and why should we use it, please refer to the following link :
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)

One of the new features of Yii2 is CSRF validation enabled by default.
If you use ajax or basic form as follows :

<form action='#' method='POST'>
...........
</form>

You will get an error exception :

Bad Request (#400): Unable to verify your data submission

That is because you do not submit csrf token. The easiest way if you dont care about csrf just disable it in main config :

'components' => [
'request' => [
....
'enableCsrfValidation'=>false,
],
.....
],

Or in Controller :

public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}

So how to use Csrf Validation for your strong security website:

* With basic form:
– Create form with yiiwidgetsActiveForm or yiibootstrapActiveForm
ActiveForm will automatically add a token in the form

Can use like this

<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
....
<?php ActiveForm::end(); ?>

Or

<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<input type='text' name='name'/>
.........
<?php ActiveForm::end(); ?>

* With manual form:
you must manually add CSRF token in the form

<form action='#' method='POST'>
<input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
....
</form>

* With Ajax
– In main layout add csrfMetaTags :

<head>
.......
<?= Html::csrfMetaTags() ?>
</head>

– And in javascript ajax code add csrf param like this:

var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
url: 'request',
type: 'post',
dataType: 'json',
data: {param1: param1, _csrf : csrfToken},
});

source : http://zero-exception.blogspot.com/2015/01/yii2-using-csrf-token.html

Yii2 REST API remove tag

$xml = new yiiwebXmlResponseFormatter;
$xml
->rootTag = 'Response';
       
Yii::$app->response->format = 'custom_xml';
Yii::$app->response->formatters['custom_xml'] = $xml;
       
return ['customer' => ['name' => 'John Smith']];
« Older posts

© 2021 Zeeshan Ahmad

Theme by Anders NorenUp ↑