Marius van Witzenburg We fight for our survival, we fight!

23Jul/111

Ixy and her “What are you looking at!” look to the camera

Posted by mariusvw

It seems that Ixy likes seeing her self in the camera... She even doesn't get scared when I come with my hands near her. Normally she flies away even if you just point at her ;-)

17Jul/112

PHP Performance – isset() versus empty() versus PHP Notices

Posted by mariusvw

I’m cleaning up a lot of PHP code and always program with PHP error_reporting set to E_ALL and display_errors turned on so that I make sure to catch any PHP messages that come up. Since starting on this site, I have fixed literally hundreds (maybe thousands) of PHP Notices about using uninitialized variables and non-existent array indexes.

I have been fixing problems like this where $somevar is sometimes undefined:

if ($somevar)

by changing it to:

if (isset($somevar) && $somevar)

This successfully gets rid of the NOTICEs, but adds some overhead because PHP has to perform two checks. After fixing a lot of this in this manner, I’ve noticed that the pages seem to be generated a little slower.

So, to provide some conclusive results to myself, I wrote up a quick benchmarking script - available at php_empty_benchmark.php. It goes through 1,000,000 tests using each of these methods:

  1. if ($a) - This generates a notice if $a is not set
  2. if (isset($a)) - A simple clean way to check if the variable is set (note that it is not equivalent to the one above)
  3. if (isset($a) && ($a) - The one that I have been using which is equivalent to if($a), but doesn’t generate a notice.
  4. if (!empty($a)) - This is functionally equivalent to if($a), but doesn’t generate a notice.

It measures the time to perform 1 million tests using a defined percentage of values that are set. It then computes the difference as a percentage of the time taken for the original test (the one that generates the notices). A ‘diff’ of 100 means that the execution time is the same, greater than 100 means that it is faster, and less than 100 means that it is slower. A typical test produced these results:

With NOTICE: 0.19779300689697
With isset:  0.19768500328064 / Diff: 100.05463419811
With both:   0.21704912185669 / Diff: 91.128222590815
With !empty: 0.19779801368713 / Diff: 99.997468735875

In summary, using the if (isset($a) && $a) syntax is about 8-10% slower than generating the PHP Notice. Using !empty() should be a drop-in replacement that doesn’t generate the notice and has virtually no performance impact. Using ifset() also has no performance impact, but is not exactly the same as ‘if($a)’ since isset() will return true if the variable is set to a false value. I included it here, because it often make the code a little more readable than the !empty($a) syntax. For example:

$myvalue = !empty($_REQUEST['myvalue']) ? $_REQUEST['myvalue'] : '';

Versus

$myvalue = isset($_REQUEST['myvalue']) ? $_REQUEST['myvalue'] : '';

Source:
http://www.brandonchecketts.com/archives/php-performance-isset-versus-empty-versus-php-notices

Geëtiketeerd als: , , , 2 Reacties
17Jul/113

How to download sexdumpert.nl photo’s or video’s with a simple Bash script

Posted by mariusvw

Here is the simple script which downloads all photos from sexdumpert.nl

Just save the file as run.sh in a directory and run it. It will save all photos found.

#!/bin/bash
 
if [ ! -d 'files' ]
then
    mkdir files
fi
 
for ((a = 0; a <= 999; a++))
do
    ca=`printf "%03d" $a`
    for ((b = 0; b <= 999; b++))
    do
        cb=`printf "%03d" $b`
        for ((c = 0; c <= 999; c++))
        do      
            cc=`printf "%03d" $c`
            for ((d = 0; d <= 999; d++))
            do      
                cd=`printf "%03d" $d`
 
                url="http://mediadata.sexdumpert.nl/$ca/$cb/$cc/$cd.jpg"
                echo $url
                /usr/bin/curl $url -o "files/$ca-$cb-$cc-$cd.flv"
 
            done    
        done    
    done    
done

Here is the simple script which downloads all video's from sexdumpert.nl

Just save the file as run.sh in a directory and run it. It will save all video's found.

#!/bin/bash
 
if [ ! -d 'files' ]
then
    mkdir files
fi
 
for ((a = 0; a <= 999; a++))
do
    ca=`printf "%03d" $a`
    for ((b = 0; b <= 999; b++))
    do
        cb=`printf "%03d" $b`
        for ((c = 0; c <= 999; c++))
        do      
            cc=`printf "%03d" $c`
            for ((d = 0; d <= 999; d++))
            do      
                cd=`printf "%03d" $d`
 
                url="http://mediadata.sexdumpert.nl/$ca/$cb/$cc/$cd.flv"
                echo $url
                /usr/bin/curl $url -o "files/$ca-$cb-$cc-$cd.flv"
 
            done    
        done    
    done    
done

Hope this for fills some people their needs ;-)

Geëtiketeerd als: , , , , , 3 Reacties
17Jul/110

How to check if a key exists in an array with in_array for Bash

Posted by mariusvw

When working with Bash it might become handy to have a way to check if a record exists in an array. In PHP you have in_array for this... The below code adds a function similar to the PHP variant.

function in_array() {
  local x
  ENTRY=$1
  shift 1
  ARRAY=( "$@" )
  [ -z "${ARRAY}" ] && return 1
  [ -z "${ENTRY}" ] && return 1
  for x in ${ARRAY[@]}; do
    [ "${x}" == "${ENTRY}" ] && return 0
  done
  return 1
}
 
MASTER=()
CURRENT=()
FIRST=1
for SERVER in ${SERVERS}; do
  # collect all builds from server and populate CURRENT list
  COMMAND="${LS} -1fd ${WEBROOT}/${SITE}.*"
  BUILDS=`${SSH} ${SSHOPTS} root@${SERVER} "${COMMAND}"`
  for BUILD in ${BUILDS}; do
    CURRENT=( ${CURRENT[@]-} ${BUILD} )
  done
 
  # if this is our first time around, copy CURRENT to MASTER
  if [ ${FIRST} -eq 1 ]; then
    MASTER=( ${CURRENT[@]} )
    FIRST=0
  fi
 
  # now we do a compare between MASTER and CURRENT to see what builds
  # are common
  INTERSECT=()
  for ENTRY in ${CURRENT[@]}; do
    in_array "${ENTRY}" "${MASTER[@]}"
    RET=$?
    if [ "${RET}" -eq 0 ]; then
      INTERSECT=( ${INTERSECT[@]-} ${ENTRY} )
    fi
  done
  MASTER=( ${INTERSECT[@]} )
 
  # clear the CURRENT array
  CURRENT=()
done

Source: http://mykospark.net/tag/in_array/

Geëtiketeerd als: , , , Geen reacties
17Jul/110

How to add Base64 encoding and decoding in C

Posted by mariusvw

I found this page on the web while searching for something else but I thought this might be useful to others :-)

Overview
libb64 is a library of ANSI C routines for fast encoding/decoding data into and from a base64-encoded format. C++ wrappers are included, as well as the source code for standalone encoding and decoding executables.

Base64 uses a subset of displayable ASCII characters, and is therefore a useful encoding for storing binary data in a text file, such as XML, or sending binary data over text-only email.

Usage

#include <b64/encode.h>
#include <iostream>
int main() {
	base64::encoder E;
	E.encode(std::cin, std::cout);
	return 0;
}

You can read more info and download the package on the url below:

http://libb64.sourceforge.net/

Geëtiketeerd als: , , , , Geen reacties
14Jul/110

Convert pipe diameters from Inches, DN (Diametre Nominal) and mm (Millimeter)

Posted by mariusvw

Pipe is made of a wide variety of materials - like galvanized steel, black steel, copper, cast iron, concrete, and various plastics such as ABS, PVC, CPVC, polyethylene, polybutylene and more.

Pipes are identified by "nominal" or "trade" names that are loosely related to the actual dimensions. For instance, a 2-inch galvanized steel pipe has an inside diameter of about 2 1/8 inches and an outside diameter of about 2 5/8 inches.

In plumbing pipe size is referred to as nominal pipe size - NPS, or "Nominal Pipe Size". The metric equivalent is called DN or "diametre nominel". The metric designations conform to International Standards Organization (ISO) usage and apply to all plumbing, natural gas, heating oil, and miscellaneous piping used in buildings. The use of NPS does not conform to American Standard pipe designations where the term NPS means "National Pipe Thread Straight".

Convert the pipe diameters with the inner and outer diameter in millimeters, the inner surface and wall thickness.

Related links:
NPS - 'Nominal Pipe Size' and DN - 'Diametre Nominal'
Difference between Pipes and Tubes

Geëtiketeerd als: , , , , , , Geen reacties
14Jul/110

How to grab the mouse position in a browser with jQuery and HTML5

Posted by mariusvw

Depending on what your plans are it might become handy to know the mouse position.
The script below gives you the position relative to the page, relative to the browser window and relative to the DIV with the green color.

HTML (index.html)

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="javascript.js"></script>
    <link href="style.css" type="text/css">
</head>
<body>
    <div id="object"></div>
    <div id="page" class="info">Page: <span></span></div>
    <div id="client" class="info">Client: <span></span></div>
    <div id="container" class="info">Container: <span></span></div>
</body>
</html>

CSS (style.css)

* {
    margin: 0px;
    border: 0px;
    padding: 0px;
}
#object {
    width: 595px;
    height: 842px;
    margin: 10px;
    background: #cfc;
    border: 1px solid #666;
    float: left;
}
.info {
    padding-top: 100px;
}

JavaScript (javascript.js)

$(function() {
    $("#object").mousemove(function(e) {
        var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
        var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
        var cLeft = e.pageX - $(this).offset().left;
        var cTop = e.pageX - $(this).offset().top;
        var containerCoords = "( " + cLeft + ", " + cTop + " )";
        $("#page span").text("( e.pageX, e.pageY ) - " + pageCoords);
        $("#client span").text("( e.clientX, e.clientY ) - " + clientCoords);
        $("#container span").text("( e.clientX, e.clientY ) - " + containerCoords);
    }).click(function(e) {
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        var containerCoords = "( " + x + ", " + y + " )";
        alert("You clicked: ( e.clientX, e.clientY ) - " + containerCoords);
    });
});

Related links:
http://docs.jquery.com/Tutorials:Mouse_Position

Geëtiketeerd als: , , , , Geen reacties
13Jul/110

How to modify HTTP headers with PHP header() function

Posted by mariusvw

Many examples that show how to use the header() function of PHP.

Hint:
If you want to check your headers, you can use web based tools like: web-sniffer.net, web-browser extensions (e.g. LiveHTTPHeaders, ieHTTPHeaders) or another third-party software tool.

// See related links for more status codes
 
// Use this header instruction to fix 404 headers
// produced by url rewriting...
header('HTTP/1.1 200 OK');
 
// Page was not found:
header('HTTP/1.1 404 Not Found');
 
// Access forbidden:
header('HTTP/1.1 403 Forbidden');
 
// The page moved permanently should be used for
// all redrictions, because search engines know
// what's going on and can easily update their urls.
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $url);
exit();
 
// Server error
header('HTTP/1.1 500 Internal Server Error');
 
// Redirect to a new location:
header('Location: http://www.example.org/');
 
// Redriect with a delay:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';
 
// you can also use the HTML syntax:
// <meta http-equiv="refresh" content="10;http://www.example.org/ />
 
// override X-Powered-By value
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');
 
// content language (en = English)
header('Content-language: en');
 
// last modified (good for caching)
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');
 
// header for telling the browser that the content
// did not get changed
header('HTTP/1.1 304 Not Modified');
 
// set content length (good for caching):
header('Content-Length: 1234');
 
// Headers for an download:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"'); 
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');
 
// Disable caching of the current document:
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');
 
// set content type:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); // plain text file
header('Content-Type: image/jpeg'); // JPG picture
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/pdf'); // PDF file
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file
header('Content-Type: application/x-shockwave-flash'); // Flash animation
 
// show sign in box
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';

Source: http://www.jonasjohn.de/snippets/php/headers.htm

Related links:
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http://www.web-caching.com/mnot_tutorial/
http://reeg.junetz.de/DSP/node16.html

Geëtiketeerd als: , , , Geen reacties
10Jul/110

How to update your FreeBSD kernel and World system

Posted by mariusvw

Auto install using freebsd-update

See: How to use freebsd-update to update your FreeBSD kernel and world system

Manual Update World / Kernel

Its advised to run this in Screen, you can install it from /usr/ports/sysutils/screen.

First you have to update the SRC and Ports tree, follow the manual on this page to complete this step.

Next is to configure the make.conf so it won't install things we don't want.
Be sure you check out man make.conf for some make optimalisation settings.

Here is an example that I use:

WITHOUT_X11=yes
NO_GAMES=yes
NO_X=yes
 
# make optimalization (-j4, 4 = optimal for 1 cpu)
MAKEOPTS="-j4 -B"

In case you have edited (which is a 100% chance you did) files of the world installation you might need to edit the mergemaster.rc file and add some settings before running mergemaster.

Check this page to view an example: How to configure mergemaster to merge configurations on FreeBSD.

These are the steps to install a fresh kernel and world system. The TMPDIR that I use is because I disabled the ability to execute files on the standard /tmp mount.

mkdir /tmp_world
setenv TMPDIR /tmp_world
cd /usr/src
make clean
make buildworld
make buildkernel
make installkernel
make installworld

Merge the world system:

mergemaster

Be sure you check out man mergemaster. For example people use the -p argument. This can be handy in some situations.

Remove temp dir:

unsetenv TMPDIR
rm -r /tmp_world

Short versions (might be unsafe):

# Kernel & World
mkdir /tmp_world ; setenv TMPDIR /tmp_world; cd /usr/src; make clean
make buildworld && make buildkernel && make installkernel && make installworld
mergemaster
unsetenv TMPDIR; rm -r /tmp_world
 
# Kernel-only
mkdir /tmp_world ; setenv TMPDIR /tmp_world; cd /usr/src; make clean
make buildkernel; make installkernel
unsetenv TMPDIR; rm -r /tmp_world

Remove builded objects, only after a release upgrade:

cd /usr/obj
chflags -R noschg *
rm -rf *

Custom KERNEL

cd /usr/src/sys/i386/conf/
cp GENERIC YOURKERNEL
echo "# Kernel configuration" >> /etc/make.conf
echo "KERNCONF=YOURKERNEL" >> /etc/make.conf

Compile the same as above, only leave out the buildworld and installworld.

10Jul/110

How to configure mergemaster to merge configurations on FreeBSD

Posted by mariusvw

Ignore files for upgrade, for example you could add /etc/motd here.

Simply edit the file /etc/mergemaster.rc and add the following line:

IGNORE_FILES='/etc/motd'

Another example:

# Automatically install files that do not exist on the system already
AUTO_INSTALL=yes
 
# Automatically upgrade files that have not been user modified
AUTO_UPGRADE=yes
 
# Preserve files that you replace
PRESERVE_FILES=yes
PRESERVE_FILES_DIR=/var/tmp/mergemaster/preserved-files-`date +%y%m%d-%H%M%S`
 
# Files to always avoid comparing (space separated)
IGNORE_FILES='/etc/motd /etc/rc.conf'

For more information check out the manual page.

Page 1 of 3123