2015 m. lapkričio 10 d., antradienis

Mysql Backup via CMD / cron

Visu failu backup i viena faila sugzipinta, su datos reiksme
mysqldump -u username -pPASWORDAS --opt --all-databases | gzip >   DailyDB_`date '+%Y-%m-%d_%T'`.sql.gz

Arba skriptas - backupu darymas i atskirus failus pagal duombazes
#!/bin/bash

USER="dfdsf"
PASSWORD="sdfdsf"
OUTPUT="/path/to/dir/"

databases=`mysql -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`

for db in $databases; do
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]] ; then
        echo "Dumping database: $db"
        mysqldump -u $USER -p$PASSWORD --databases $db  | gzip > $OUTPUT/$db._`date '+%Y-%m-%d_%T'`.sql.gz
    fi
done
 you save the code in file backup.sh $ chmod +x

2015 m. rugsėjo 30 d., trečiadienis

php date interval

$dates = array_map(function($dt) { return $dt->format('Y-m');}, iterator_to_array(new DatePeriod(new DateTime(date('Y-m-01')), DateInterval::createFromDateString('-1 month'), 12)));

2015 m. rugsėjo 26 d., šeštadienis

SQL join`inimas po vieną naujausią eulutę

SELECT c.*, p1.*
FROM customer c
JOIN purchase p1 ON (c.id = p1.customer_id)
LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
    (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
WHERE p2.id IS NULL;
source: http://stackoverflow.com/questions/2111384/sql-join-selecting-the-last-records-in-a-one-to-many-relationship

jQuery perdavima x-auth-token

$.ajax({
   url : myurl,
   headers: {
        'X-Auth-Token' : token
   });

PHP / ajax apsauga, su kintamu raktu ir laiko žyma

$time = time();
$hash = md5($key . $time);
$url =  "http://domain.com/iframe?hash=$hash&time=$time";
On the other side you should first check if the timestamp is in the limits (e.g. not older than five minutes) and than rehash with the key and the submitted timestamp. If you get the same hash the request is valid.

2015 m. rugsėjo 24 d., ketvirtadienis

Unikalūs SEO URL / SLUG

tarkime, jūs formuojate straipsnių URL iš straipsnių antraščių. Kyla poreikis išvengti vienodų URL jei bus du tokie pat straipsniai, pvz.: 'test-slug-1', 'test-slug-2' and 'test-slug-3'

Tam pagelbės funkcija

$slug = preg_replace("/-$/","",preg_replace('/[^a-z0-9]+/i', "-", strtolower($title)));
Just hit the database once, grab everything at once, chances are that's the biggest bottleneck.
$query = "SELECT * FROM $table_name WHERE  $field_name  LIKE '".$slug."%'";
Then put your results in an array (let's say $slugs)
//we only bother doing this if there is a conflicting slug already
if(mysqli_num_rows($result) !== 0 && in_array($slug, $slugs)){
    $max = 0;

    //keep incrementing $max until a space is found
    while(in_array( ($slug . '-' . ++$max ), $slugs) );

    //update $slug with the appendage
    $slug .= '-' . $max;
}
We use the in_array() checks as if the slug was my-slug the LIKE would also return rows such as
my-slug-is-awesome
my-slug-is-awesome-1
my-slug-rules
šaltinis: http://stackoverflow.com/questions/15971685/creating-unique-page-title-slugs-php

2015 m. rugpjūčio 28 d., penktadienis

php image classes

https://github.com/claviska/SimpleImage     php 5.3 + GD
http://imagine.readthedocs.org/en/latest/index.html php 5.3 GD/imagick
http://phpthumb.sourceforge.net/ php 4+/5 GD/imagick

imagick pamokos: http://www.phpro.org/tutorials/Imagick.html

PHP URL shortening functions

Integer konvertavimas.

Jigu tinka - ir _ simboliai

function encode($number) {
    return strtr(rtrim(base64_encode(pack('i', $number)), '='), '+/', '-_');
}
function decode($base64) {
    $number = unpack('i', base64_decode(str_pad(strtr($base64, '-_', '+/'), strlen($base64) % 4, '=')));
    return $number[1];
}

jeigu norima tik raidyno ir skaiciu

  1. function encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  2. // can't handle numbers larger than 2^31-1 = 2147483647
  3. $str = '';
  4. do {
  5. $i = $val % $base;
  6. $str = $chars[$i] . $str;
  7. $val = ($val - $i) / $base;
  8. } while($val > 0);
  9. return $str;
  10. } 
  11. function decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  12. $len = strlen($str);
  13. $val = 0;
  14. $arr = array_flip(str_split($chars));
  15. for($i = 0; $i < $len; ++$i) {
  16. $val += $arr[$str[$i]] * pow($base, $len-$i-1);
  17. }
  18. return $val;
  19. }


paprastam url konvertavimui

function base64url_encode($data) {
  return 
rtrim(strtr(base64_encode($data), '+/''-_'), '=');
}

function 
base64url_decode($data) {
  return 
base64_decode(str_pad(strtr($data'-_''+/'), strlen($data) % 4'='STR_PAD_RIGHT));

2015 m. rugpjūčio 24 d., pirmadienis

2015 m. rugpjūčio 19 d., trečiadienis

2015 m. rugpjūčio 11 d., antradienis

Word macro - visu paveikslu dydzio nuresetinimas i 100%

word uzseiviname naujausiu formatu kad nebutu vompability mode. Einame i view -> macro  ir sukuriame funkcija

  Sub AllGraphicsTo100()

      Dim ILS As Word.InlineShape
      Dim SHP As Word.shape

      For Each ILS In ActiveDocument.InlineShapes
        If ILS.Type = wdInlineShapePicture Or ILS.Type = wdInlineShapeLinkedPicture Then
            ILS.ScaleHeight = 100
            ILS.ScaleWidth = 100
        End If
      Next ILS

      For Each SHP In ActiveDocument.Shapes
        If SHP.Type = msoPicture Or SHP.Type = msoLinkedPicture Then
            SHP.ScaleHeight 1#, True
            SHP.ScaleWidth 1, True
        End If
      Next SHP

    End Sub

2015 m. liepos 29 d., trečiadienis

Teksto lygiavimas vertikaliai

This solution will work for a single line and multiple lines of text, but still requires a fixed height container:
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
The CSS just sizes the <div>, then vertically center aligns the <span> by setting the <div>'s line-height equal to its height, and making the <span> an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the <span> so its contents will flow naturally inside the block.
div {
  width: 250px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;      
}

2015 m. liepos 27 d., pirmadienis

memcache

yum install memcached
yum install php-pecl-memcache
apachectl restart 

$mkey = 'song_'.$s['id'];
$memcache = new Memcache; 
$memcache->connect('localhost', 11211);

$rez = $memcache->get($mkey);
if (!$rez) {
$memcache->set($mkey, 'sdsadasd', MEMCACHE_COMPRESSED, 60*60*24);

 }

2015 m. liepos 24 d., penktadienis

MYSQL optimizavimas

//query profiling
 $db->query('SET profiling = 1');
 $db->query("SELECT COUNT(id) `0` FROM tbl` WHERE......");
 $timings = $db->getRows('SELECT QUERY_ID, SUM(Duration) `DURATION` FROM information_schema.profiling GROUP BY `QUERY_ID`  ');
var_dump($timings);
               

2015 m. liepos 21 d., antradienis

Aptikimas mobiliųjų įrenginių

http://stackoverflow.com/questions/11381673/detecting-a-mobile-browser

Using Regex (from detectmobilebrowsers.com):

Here's a function that uses an insanely long and comprehensive regex which returns a true or false value depending on whether or not the user is browsing with a mobile.
window.mobilecheck = function() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
}
For those wishing to include tablets in this test (though arguably, you shouldn't), you can use the following function:
window.mobileAndTabletcheck = function() {
  var check = false;
  (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  return check;
}

The Original Answer

You can do this by simply running through a list of devices and checking if the useragent matches anything like so:
function detectmob() { 
 if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 || navigator.userAgent.match(/Windows Phone/i)
 ){
    return true;
  }
 else {
    return false;
  }
}
However since you believe that this method is unreliable, You could assume that any device that had a resolution of 800x600 or less was a mobile device too, narrowing your target even more (although these days many mobile devices have much greater resolutions than this)
i.e
function detectmob() {
   if(window.innerWidth <= 800 && window.innerHeight <= 600) {
     return true;
   } else {
     return false;
   }
}