What they never tell you about GitHub

GitHub is brilliant…. There are loads of tutorials, video and articles out there, recently I’ve spent time filling gaps in my Git version control knowledge and something struck me as odd. Every tutorial should make it clear right from the start and reminders throughout their presentations that you

DO NOT STORE PASSWORDS, KEYS, USERNAMES, CREDENTIALS, ETC. ON GIT HUB

Why?

Because there are bastards out there who are scanning git repositories for anything that could help access secured areas or consume resources they should not.

Git does scan your repo’s and will warn you but its not in real time so be warned. Still not convinced? The image is of a free Amazon Web Service account that was set up as a learning exercise the keys where saved in a Git Repo and over the course of 3 days a free account had racked up nearly $10,000US .

What can you do, if you accidentally commit a password, key, etc? Delete the branch? Roll back?

No!

The best advice and this is also given by Git themselves is to consider your data compromised and your accounts that use the data hacked. Once again, rolling back and deleting does not work.

So reset your passwords/key etc and don’t just add a 1 at the end or swap out vowels for 12345.

How do you manage password and environment values?

Have a Google for git .gitignore or visit dotIgnore on GitHub

Javascript quick filter, map and reduce

Again part of my breaking out of jQuery and back into vanilla JavaScript

Filter, Map and Reduce examples

const dragonEvents = [
 {type: 'attack', value: 12, target: 'dorkman'},
 {type: 'yawn', value: 40},
 {type: 'eat', target: 'horse'},
 {type: 'attack', value: 23, target: 'fluffy'},
 {type: 'attack', value: 12, target: 'dorkman'},
 {type: 'attack', value: 3, target: 'dorkman'},
 {type: 'attack', value: 10, target: 'dorkman'}
]

const totalDamageToDorkman = dragonEvents
 .filter(event => event.type === 'attack')
 .filter(event => event.target === 'dorkman')
 .map(event => event.value)
 .reduce((prev, value) => (prev || 0) + value)

const targets = dragonEvents
 .filter(event => event.target)
 .map(event => event.target)

const findFluffy = dragonEvents
 .filter(event => event.target === 'fluffy')

const totalAttackPoints = dragonEvents
 .filter(event => event.value) // Filter out null or undefined event.value
 .map(event => event.value) // Push to the new array only event.value
 .reduce((total, event) => (total | 0) + event) // Sum the array
 // .reduce((total, event) => { return total + event}, 0) //Does the dame thing but specifies starting value
 
 console.log('Total:\n' + totalDamageToDorkman);
 console.log(JSON.stringify(targets, null, 2));
 console.log(findFluffy);
 console.log(totalAttackPoints);

Tanks to Fun Fun Functions and Mattias Petter Johansson

JavaScript fetch()

In a previous post I was refreshing my memory with vanilla JavaScript  after years of jQuery-ing, especially AJAX request and the

XMLHttpRequest()

My eyes rolled when I was reading more about it then  I found fetch()  ( I know its been about since 2015 and now almost universally adopted).

Fetch does what XMLHttpRequest does but in a more elegant way and DOES NOT need additional libraries as it is bundled with JavaScript. It also makes use of “promises” .

const url = "https://randomuser.me/api/?results=10";

fetch(url)
.then(function(response) {
 return response.json();
})
.then(function(data) {
 console.log(data.results);
})
.catch(function() {
 console.log("Booo");
});

The above code queries the URL, then parses the string as JSON, then does something with the data.

It also catches errors.

Good eh?

Its looks to be easy to expand and do all manner of fetching. For example submitting a form

var form = new FormData(commentForm);
fetch( url, { method: "POST", body: form })

You can then chain .then() promises to get the desired outcomes.

For more information

A quick introduction video from Google

From Google Working with the Fetch API

Jake Archibald’s post Thats so Fetch

Scotch post The Fetch API

 

 

 

 

 

strpos() not working?

PHP strpos() not working as expected? It could be a  “non-strict” comparison problem.

When using strpos() to determine whether a substring exists within a string the  results can be misleading: Remember FALSE == 0?

Consider the following:

$quote = 'Dave rocks';
 
if (strpos($quote, 'Dave')) {
    echo 'Dave is awesome.';
} else {
    echo 'Dave is not awesome.';
}

strpos() Returns position is 0 ( zero ) that is evaluated as FALSE so, “Dave is not awesome”.

Much better. In this case adding the strict comparison === ( 3 equals ) to the “if” statement asks if strpos() returns a number and  is not strictly FALSE. So, “Dave is awesome”

$quote = 'Dave rocks';
 
if (strpos($quote, 'Dave') !== FALSE) {
    echo 'Dave is awesome.';
} else {
    echo 'Dave is not awesome.';
}

For more see PHP.net

 

 

 

Laravel Pagination

Pagination with Laravel (5.4 at the time of writing) is very easy.

Say you want a table of users

In your controller:

$user = User::all()->paginate(10);

In the view loop through your users as normal and then add

$user->links() where ever you feel like it and more than one place if you are feeling dandy.

There is more..

But say you want more than one paginate-able list/table on the same page? This is the paginators signature

paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)

Easy, extending the original query lets get all the threads/comments for a user. Assuming your User model can dish out Threads and Comments

$user = User::find(1);
$threads = $user->threads()->paginate(4, ['*'], 'threads');
$comments = $user->comments()->paginate(4, ['*'], 'comments');

Then in your view loop through your comments and add

$comments->links();

Loop through your threads and add

$threads->links();

 

 

 

New querySelector() and querySelectorAll()

Catching up with JavaScript after years of using jQuery I found these two shortcuts for replacing longer getElementById() methods. NOTE: the querySelector is passed an ID in the CSS format

<button id="our-button">Add New Item</button>

<script>
    // These are both the same
    var ourButton = document.getElementById("our-button");
    var ourButton = document.querySelector("#our-button");
</script>
<ul id="our-list>
    <li>A thing</li>
    <li>Another thing</li>
    <li>A new thing</li>
</ul>


<script>
// These are both the same
   var listItems = document.getElementById('#our-list').getElementsByTagName("li");
   var listItems = document.querySelectorAll("#our-list li");
</script>

 

 

Javascript AJAX without jQuery

I learnt this stuff years ago but with the rise of jQuery I like many others had become lazy. Add the fact that so many browsers handled things slightly different going down the library route had its benefits.

It is 2017 and things have improved many jQuery(ish) approaches have been adopted by Javascript and browsers have become more similar.

So here goes. First off a GET request to retrieve a Chuck Norris joke

<script>
var url = "http://api.icndb.com/jokes/random";
var request = new XMLHttpRequest();

request.open('GET', url, true);

request.onload = function() {
 if (request.status >= 200 && request.status < 400) {
 // Success!

printJokes(request.responseText);

} else {
 // We reached our target server, but it returned an error
 console.log('There was a problem. Status:' + request.status);

}
};

request.onerror = function() {
 console.log('There was a problem!');
};

request.send();


var printJokes = function(jokes){

JSON.parse(jokes, (key, value) => {
 key == 'joke' ?
 console.log(value) : ''
 });

}
</script>

 

 

 

Toggling in Javascript, PHP and possibly other environments

For a long time if I wanted to change the state of a variable between true and false (toggling). In PHP I would do something like…

$switch = true;
if($switch == true){
    $switch = false;
}else{
    $switch = true
}

That worked fine, then there came Ternary shorthand

$switch = true;
$switch = ($switch == true ? false : true);

Not bad eh? Much easier to read. Then came this

$switch = true;
$switch = !$switch;

If you read it out loud it sounds like, ‘Switch is not true?’ So the answer would be either

True = $switch is false

Or

False = $switch is true