Skip to content

Instantly share code, notes, and snippets.

@AGiallelis
Last active August 27, 2020 21:15
Show Gist options
  • Save AGiallelis/d701f46d7431c9ac5cded4edd64313f7 to your computer and use it in GitHub Desktop.
Save AGiallelis/d701f46d7431c9ac5cded4edd64313f7 to your computer and use it in GitHub Desktop.

PHP top

Tool Notes

  • Composer autoload.php MUST be required in the init file
  • Important: If we do not have classes that follow the PSR-4 then we need to run composer dump-autoload when we add a new class in order to be found
  • If we place the /dev/tools folder in PATH variable then we can call all the executables there straight from everywhere.
  • If we rename phpunit.phar -> phpunit and place the file in tools folder then we can run it explicitly
  • We can use composer locally and just upload the files live without using composer on the server. This way we don't need to care about custom Autoloading classes
  • In order to generate documentation with phpDocumentor we run: php ../../../tools/phpDocumentor.phar -d src -t docs
  • In order to run Unit Tests we run: phpunit tests --bootstrap vendor/autoload.php

Namespace Tips

  • The following functions have better performance when the root namespace is specified like \stlen :
    "array_slice"
    "assert"
    "boolval"
    "call_user_func"
    "call_user_func_array"
    "chr"
    "count"
    "defined"
    "doubleval"
    "floatval"
    "func_get_args"
    "func_num_args"
    "get_called_class"
    "get_class"
    "gettype"
    "in_array"
    "intval"
    "is_array"
    "is_bool"
    "is_double"
    "is_float"
    "is_int"
    "is_integer"
    "is_long"
    "is_null"
    "is_object"
    "is_real"
    "is_resource"
    "is_string"
    "ord"
    "strlen"
    "strval"
    

Datetime Tips

  • Automatic DateTime Timezone is set to Asia/Baghdad. So if we do new Datetime("now") we get the current time in Baghdad
  • DateTime objects can be compared with normal operators even if they have different timezones. PHP takes into account the timezone differences.

So when we have 2016-11-15 10:43:40 Europe/Athens, PHP will see it as bigger than 2016-11-15 11:30:00 Asia/Baghdad, as Baghdad is GMT+3 while Athens GMT+2

  • The only places where we need to be careful is the insertion of dates to be in Iraq time

error reporting

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

However, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line:

display_errors = on

For printing the values of an array

print "<pre>";
print_r($check);
print "</pre>";	

<pre means preformated text and will keep a pretty display of the contents of the array

For printing stuff in the console

echo '<script>
	console.log(" ZahlungsartID: '. $zahlungen[$j]->data['ZahlungsartID'] .'");
	console.log(" ZahlungsbeschreibungID: '. $zahlungen[$j]->data['ZahlungsbeschreibungID'] .'");
	console.log(" KostengruppeID: '. $costs[$k]->data['KostengruppeID'] .'");
	console.log(" Amount: ' . $zahlungen[$j]->data['Betrag'] .'");
	console.log(" Booking ID: '. $record->BuchungID .'");
	console.log("---");
</script>';

For checking if include will work

$testingString = "" . getcwd() . " : ";
if(file_exists("../saferpay/saferpay_cpt_authorization.php")){
	$testingString = $testingString . "Exists - ";
}
if(is_readable("../saferpay/saferpay_cpt_authorization.php")){
	$testingString = $testingString . "Readable - ";
}
if(include("../saferpay/saferpay_cpt_authorization.php")){
	$testingString = $testingString . "Included";
	mail( 'tooth@blumenriviera.de', 'Neue Saferpay-Zahlung', $testingString , 'From: saferpay@blumenriviera.de' );
}else{
	mail( 'tooth@blumenriviera.de', 'Neue Saferpay-Zahlung', $testingString , 'From: saferpay@blumenriviera.de' );
}

Display in terminal a php array

$jsonInfo = json_encode($vr );
echo '<script>
	console.log("STR: " + JSON.stringify(' . $jsonInfo . '));
</script>';

Command for printing logs

error_log("Log: \n", 3, $_SERVER["DOCUMENT_ROOT"]."/../logs/test.iraqlotto.com/custom.log");

recursively encode in UTF-8 an array

array_walk_recursive($rowBuchung, function(&$item, $key){
	if(!mb_detect_encoding($item, 'utf-8', true)){
			$item = utf8_encode($item);
	}
});

MySQL top

MySQL Foreign Key(FK) possible errors

* The columns that are going to have a relation must be of exactly the same type (Attributes included)
* The referenced column must be primary key but not coupled with another column

To see the last FK error execute:

SHOW ENGINE INNODB STATUS;

SQL for getting actual database size (We can run it through phpmyadmin)

SELECT table_schema "Data Base Name",
	sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB",
	sum( data_free )/ 1024 / 1024 "Free Space in MB"
FROM information_schema.TABLES
GROUP BY table_schema ; 
Tip: The data_free ("Free space in MB") mean the space that the tables have occupied and can use it if needed.

Check if tables are locked

SHOW OPEN TABLE;

Show the processes that are running

SHOW FULL PROCESSLIST;				//Less info
select * from INFORMATION_SCHEMA.PROCESSLIST;	//Analytical info

And if we want to kill a query we do:

KILL <Query ID>;

If we want to kill all processes:

select concat('KILL ',id,';') from information_schema.processlist;

Execute MySQL commans via linux Bash

mysql -u [user] -p[pass] -e "[mysql commands]"

command for bringing the entries which have date less than one year ago

select * from your_table
where registration_date > curdate() - interval 1 year

MySQL where mupltiple values

SELECT * FROM table WHERE interests REGEXP 'sports|pub'

MySQL group by one column where there is duplicate on another column

SELECT d.deltia_id,b.play_time,b.b_code,g.gamers_id, g.f_name,g.l_name,d.praktores_id,d.barcode_id
FROM deltia d
INNER JOIN barcode b on b.barcode_id = d.barcode_id
INNER JOIN gamers g on g.gamers_id = d.gamers_id
WHERE d.barcode_id IN (
	SELECT barcode_id 
	FROM deltia de
	GROUP BY de.barcode_id having Count(de.barcode_id) > 7
)
GROUP BY d.gamers_id
ORDER BY d.barcode_id;

Winners of round and the agent data

SELECT p.f_name, p.l_name,g.f_name,g.l_name, b.b_code,b.play_time, count(*) as cnt FROM deltia d,round r,barcode b 
INNER JOIN praktores p ON p.praktores_id = b.praktores_id 
INNER JOIN gamers g ON g.gamers_id = b.gamers_id 
WHERE r.round_id=d.round_id and r.round=5 and d.tip=r.final and d.barcode_id=b.barcode_id 
GROUP BY b.barcode_id having cnt=6 or cnt=7 ORDER BY `play_time` DESC

MySQL Version display

SHOW VARIABLES LIKE "%version%";

Show Tickets for the agents between two rounds

SELECT x.f_name, x.l_name, x.Tickets AS Coupons_6, y.Tickets AS Coupons_7
FROM (
	SELECT p.f_name, p.l_name, b.play_time, COUNT(b.praktores_id) AS Tickets FROM barcode b
	INNER JOIN praktores p ON b.praktores_id = p.praktores_id
	WHERE b.round = 6
	GROUP BY b.praktores_id
	) AS x
JOIN
	(
	SELECT p.f_name, p.l_name, b.play_time, COUNT(b.praktores_id) AS Tickets FROM barcode b
	INNER JOIN praktores p ON b.praktores_id = p.praktores_id
	WHERE b.round = 7
	GROUP BY b.praktores_id
	) AS y
ON x.f_name = y.f_name AND x.l_name = y.l_name;

Counting Distinct Values on Multiple Columns

SELECT computer, user, count(*) AS count
FROM login
GROUP BY computer, user

Count( * ) will count the duplicate appearances of both computer,user on the same row and return that for every line that the GROUP BY outputs

Find records with no data on the other table

SELECT * FROM barcode
WHERE NOT EXISTS (
	SELECT * FROM deltia WHERE barcode.barcode_id = deltia.barcode_id
)

Multiple summing/grouping using JOIN

SELECT a.round_id, SUM(a.total_played) as total_played, SUM(w.win_sum) as won FROM win w 
RIGHT JOIN (
    SELECT r.round_id, b.barcode_id, SUM(bd.money) as total_played FROM round r 
	INNER JOIN barcode b ON b.round_id = r.round_id
	INNER JOIN bet_data bd ON bd.barcode_id = b.barcode_id
	GROUP BY b.barcode_id
) as a ON a.barcode_id = w.barcode_id
GROUP BY a.round_id

Get 20 latest results and sort them from newest to oldest

SELECT result FROM (SELECT round_id, result FROM round WHERE agent_id = $agentId AND status = 0 ORDER BY round_id DESC LIMIT 20) temp ORDER BY round_id ASC

Prepared Statements in PHP

  • bind_param() needs to be provided with all the columns selected.
  • If we need to fetch the result set with fetch_all() then we use get_result() (works only with mysqlnd)
  • When using bind_param() we better use store_result() before the binding so that we have no sync errors
  • We do not use store_result() if we are using get_result() because the later will not work

CSS top

Align css items in center

.first-row > div:first-child{  
	display: flex;
	align-items:center;
}

Responsive images with custom code (not using bootstrap class)

Bootstrap's img-responsive:

img{
	max-width: 100%; 
	display:block; 
	height: auto;
}

Check also: http://stackoverflow.com/questions/3029422/image-auto-resize-to-fit-div-container

Css code for centering absolute elements

#element{
	position: absolute;
	margin-left: auto;
	margin-right: auto;
	left: 0;
	right: 0;
}

Javascript top

Filter ES6 array/object

let newArray = oldArray.filter((element) => (a !== b));

JS Default Parameters for older browser support

function multiply(a, b) {
	  b = (typeof b !== 'undefined') ?  b : 1;
	  return a * b;
}

Remove circular references in JSON

function removeCircularJSON(object){
    var simpleObject = {};
    for (var prop in object ){
	if (!object.hasOwnProperty(prop)){
		continue;
	}
	if (typeof(object[prop]) == 'object'){
		continue;
	}
	if (typeof(object[prop]) == 'function'){
		continue;
	}
	simpleObject[prop] = object[prop];
    }
    return simpleObject; // returns cleaned up JSON
};

print specific contents of document

var print_css = "<style> body{ font-family: Courier, monospace; font-weight: bold;} </style>";
var prtContent = $(".response");
var WinPrint = window.open();
console.log(prtContent.html());
WinPrint.document.write(print_css + prtContent.html());
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

Code for Printing all the existing cookies

$(document).ready(function(){
	var clog = document.cookie.split(";");
	console.log(clog);
});

Matching the url for testing on specific page

var pathlist = location.pathname.split("/"); //gets the path without the domain

if (pathlist[1]==="Wlochy" && pathlist[2]==="Mieszkanie-apartament" && pathlist[3]==="Cervo" && pathlist[4]==="Nido_di_Venere"){
	//code
}

Code for detaching and appending elements of specific class

for(var i=0; i<4;i++){
	var detachedElement = $(".weather_temperature:nth-of-type(" + i + ")").detach();
	detachedElement.appendTo(".province_text:nth-of-type(" + i + ") p");
}

Print javascript object in console

http://www.programmerinterview.com/index.php/javascript/how-to-print-a-javascript-object/

and:

var sampleObject = { x:1, y:2, z:3  };
var myObject = JSON.stringify(sampleObject);
alert(myObject); //this will output {"x":1, "y":2, "z":3}

find spans with ID attribute and convert to set of IDs (Array)

var IDs = $("div[id^='datetimepicker']").map(function() { return this.id; });

Code for printing a div of the page

function printCoupon(data){	// Not used at the moment as the print logic is in js/validation.js
	var print_css = "<style> body{ font-family: Courier New, monospace; font-weight: bold; font-size:13px; text-align:center;} img{ margin: 0 auto; display: block;} @page{ margin: 0cm; }</style>";
	var prtContent = data;
	var ieJs = "";

	// detect IE
	var ua = navigator.userAgent;
	var ie = false;
	if( (ua.indexOf('Trident/') > 0) || (ua.indexOf('MSIE ') > 0)) {
		ie = true;
		ieJs = "<script>\
					window.onload = function(){\
						window.print();\
						setTimeout(function() {window.close();}, 500);\
					};\
				</scr" + "ipt>";
	}

	var WinPrint = window.open('','_blank');
	WinPrint.document.write(print_css + prtContent + ieJs);
	WinPrint.document.close();
	WinPrint.focus();
	if(!ie){
		WinPrint.onload = function(){
			WinPrint.print();
			WinPrint.close();
		};
	}
	window.location = window.location.href;
}

Code for printing mouse position in canvas upon click

canvas.addEventListener("mousedown", function(evt){
    var rect = canvas.getBoundingClientRect();
    var x = evt.clientX - rect.left;
    var y = evt.clientY - rect.top;

    console.log("x: " + x + "  y: " + y);
}, false);

Pretty print json in console

console.log(JSON.stringify(json, null, '\t'));

Checking 'this' context

if(this instanceof Client){
	console.log("Yes - Client");
}else{
	console.log("No -" + this.constructor.name);
}

Administrative top

Download file via scp

scp keno@kenodebian:/var/log/apache2/error.log.1 /c/dev/

Bash return codes

http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/exitcodes.html

Command for viewing info(creation time, modification time) of a file/directory in linux

stat <filename/dirname>

Get ethernet adapter

Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.AdapterType -like "*Ethernet*"}

For logging function in gvim

Open file and put command: :set autoread (not working because it expects shell command to reload the buffers)

command: set nolz | while 1 | e | redraw | $ | sleep 1 | endw (is working. check http://www.mail-archive.com/vim@vim.org/msg05900.html)

Autoread question: http://stackoverflow.com/questions/2490227/how-does-vims-autoread-work

Useful Plugins: largeFile, LogViewer

Cronjobs

Location of file: /var/spool/cron/crontabs

Link for guidance: https://docs.oracle.com/cd/E23824_01/html/821-1451/sysrescron-24589.html

Log files

tail -f /var/log/apache2/error_log

(to get out of tail: ctrl + c )

SSH

http://askubuntu.com/questions/134975/copy-ssh-private-keys-to-another-computer

Command for compressing files with ImageMagick through windows cmd (it replaces the files in the directory that we are in!)

for %G in ("*.jpg") do convert -strip -interlace Plane -quality 74% %G %G

VM Share Folder

sudo mount -t vboxsf vmshare /home/raspberry/share

vmshare = Host OS folder defined in VBox settings. Acts like the media that is inserted
/home/raspberry/share = Guest Folder shared with Host. Is the folder where we mount the media


Plesk top

Subdomain Logs Location

/var/log/plesk-php71-fpm


Git top

Tool Notes

  • For Mintty we have the following code in .minttyrc :
BoldAsFont=-1
ClicksPlaceCursor=yes
Window=max
  • For Git Bash we have the following code in .bashrc :
#!/bin/bash
cd C:/dev/wamp64/www/projects/cosmic
git fetch
git status
alias g='git'
  • For the Git Configuration in .gitconfig is:
[user]
	email = vaggalanis@jokersattractions.com
	name = Vangelis Galanis
[alias]
	st = status
	tree = log --graph --color --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --decorate --all

Git default editor commit

It's not a Git error message, it's the editor as git uses your default editor.

To solve this:

    press "i"
    write your merge message
    press "esc"
    write ":wq"
    then press enter

Best (and safest) way to merge a git branch into master

git checkout master
git pull origin master
git merge test
git push origin master

Set Local Branch to be the same with Remote Branch

git reset --hard origin/master

Set Local Branch to be the same with Remote Branch

git clean -dfx(n)

Git show tree

git log --oneline --decorate --graph --all

See Git insertions/deletions before commit

git diff --stat HEAD

Git create local/remote branch and delete it

  • Create Local branch
git branch <branch_name>
git branch -d <branch_name>
  • Delete Remote branch
git push origin --delete <branch_name>

See changed files after fetch and before merge

git diff --stat HEAD origin/master

Save a Stash with name and retrieve it by this name

git stash save "guacamole sauce WIP"

And we Retrieve it by:

git stash apply stash^{/guacamo}

Git create tags, push them and delete them

  • Create Local Tag
git tag -a <tag_name> <commit_hash> -m "<text>"
  • Create/Delete Remote Tag
git push --tags
  • Delete Local Tag
git tag -d <tag_name>

Stage specific lines from file

git add -p <file>

While in the patching procedure, 's' input triggers further splitting of the changes

Centos top

  • Print the log of the vhost
 tail -f /var/log/apache2/error.log

Vagrant top

  • To install vagrant in windows and to use as a development environment.
https://www.drupal.org/forum/support/post-installation/2014-09-07/to-install-vagrant-in-windows-and-to-use-as-a-development	

Typing vagrant from the command line will display a list of all available commands.

Be sure that you are in the same directory as the Vagrantfile when running these commands!

Creating a VM

  • vagrant init -- Initialize Vagrant with a Vagrantfile and ./.vagrant directory, using no specified base image. Before you can do vagrant up, you'll need to specify a base image in the Vagrantfile.
  • vagrant init <boxpath> -- Initialize Vagrant with a specific box. To find a box, go to the public Vagrant box catalog. When you find one you like, just replace it's name with boxpath. For example, vagrant init ubuntu/trusty64.

Starting a VM

  • vagrant up -- starts vagrant environment (also provisions only on the FIRST vagrant up)
  • vagrant resume -- resume a suspended machine (vagrant up works just fine for this as well)
  • vagrant provision -- forces reprovisioning of the vagrant machine
  • vagrant reload -- restarts vagrant machine, loads new Vagrantfile configuration
  • vagrant reload --provision -- restart the virtual machine and force provisioning

Getting into a VM

  • vagrant ssh -- connects to machine via SSH
  • vagrant ssh <boxname> -- If you give your box a name in your Vagrantfile, you can ssh into it with boxname. Works from any directory.

Stopping a VM

  • vagrant halt -- stops the vagrant machine
  • vagrant suspend -- suspends a virtual machine (remembers state)

Cleaning Up a VM

  • vagrant destroy -- stops and deletes all traces of the vagrant machine
  • vagrant destroy -f -- same as above, without confirmation

Boxes

  • vagrant box list -- see a list of all installed boxes on your computer
  • vagrant box add <name> <url> -- download a box image to your computer
  • vagrant box outdated -- check for updates vagrant box update
  • vagrant boxes remove <name> -- deletes a box from the machine
  • vagrant package -- packages a running virtualbox env in a reusable box

Saving Progress

-vagrant snapshot save [options] [vm-name] <name> -- vm-name is often default. Allows us to save so that we can rollback at a later time

Tips

  • vagrant -v -- get the vagrant version
  • vagrant status -- outputs status of the vagrant machine
  • vagrant global-status -- outputs status of all vagrant machines
  • vagrant global-status --prune -- same as above, but prunes invalid entries
  • vagrant provision --debug -- use the debug flag to increase the verbosity of the output
  • vagrant push -- yes, vagrant can be configured to deploy code!
  • vagrant up --provision | tee provision.log -- Runs vagrant up, forces provisioning and logs all output to a file

Plugins

  • vagrant-hostsupdater : $ vagrant plugin install vagrant-hostsupdater to update your /etc/hosts file automatically each time you start/stop your vagrant box.

Notes

  • If you are using VVV, you can enable xdebug by running vagrant ssh and then xdebug_on from the virtual machine's CLI.

R top

  • Install new library in R
 install.packages("dslabs")
  • Display available data
 data()

Magento 2 top

  • Enable Module
 magento module:enable Gim_Contacts
  • Flush Cache
 magento cache:flush
  • reindex
 magento indexer:reindex

Symfony top

  • Symfony clean install
  composer create-project symfony/website-skeleton my-project
  • Running your symfony application
   php bin/console server:run
  • Storing your project in git
   git init
   git add .
   git commit -m "Initial commit"
  • Checking for security vulnerabilities
 composer require sensiolabs/security-checker --dev
  • Checking for security vulnerabilities
 composer require sensiolabs/security-checker --dev
  • Symfony debug tools
 To install
 Composer require profiler --dev
 Composer require debug --dev
 
 Functions
 Template  {{ dump() }}
 ArticleController dump($slug,$this);
 

Robot framework top

  • Robot framework installation in Ubuntu
sudo apt-get install python-wxgtk3.0
sudo apt-get install python-pip
sudo pip install robotframework robotframework-selenium2library robotframework-ride

svn co svn+ssh://robot_framework_tests@subversion.mdgms.com/trunk
svn co svn+ssh://robot_framework_tests@subversion.mdgms.com/branches/show
svn co svn+ssh://robot_framework_tests@subversion.mdgms.com/branches/live
  • PyCharm External Tools
Program: /usr/local/bin/pybot or C:\Python27\Scripts\pybot.bat
Working directory: $FileParentDir$

Parameters:
Single Test: -t "$SelectedText$" -s $FileNameWithoutExtension$ "$ProjectFileDir$"
Suite Test: -s $FileNameWithoutExtension$ "$ProjectFileDir$"
Project Test: "$ProjectFileDir$\$FileDirRelativeToProjectRoot$"

Cucumber project top

4 terminal tabs

1st npm start
2nd npm run browser
3rd webdriver-manager start
4th npm run cucumber-test

mp project top

Activate the env
~/projects/mp/mp: source bin/activate

Run the django server
python manage.py runserver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment