Rss

  • youtube
  • linkedin
  • google

Download Odin 3

Odin allows you to update your Android firmware without fuss.

Odin3 is a free PC (Windows) application which can flash (and root) some Android-based cell phones.

With Odin3, you can flash roms in your Samsung cell phone. You can install any supported version of the Android OS on your smartphone before your phone manufacturer has released an update, putting you on the bleeding edge of software. Once your phone has been rooted

Continue Reading >>

Using jQueryMask Plugin to format dates in different patterns

jQuery Mask Plugin is a great Javascript library to format fields for presentation and/or to force a properly input by users.

Here, I show how to deal with input or another HTML element to display dates when the source date has a different format from target element.

Example:

  • We have a datetime with Year-Month-Day Hour:Minute:Seconds and need to show only the Year/Month/Day part.
  • We have da date in Year-Month-Day and need to format to Day/Month/Year.

jQueryMask is very simple to use. It do not need to much to mask whatever you need. Take a look at examples on his website.

If you need to format a simple date field (even in a non-input element), just use the code below.

jQuery('[data-role="date"]).mask("TC99/M9/D9", {
        placeholder: "____/__/__",
        translation: {
            "D": {pattern: /[0-3]/, optional: false, recursive: true},
            "M": {pattern: /[01]/, optional: false, recursive: true},
            "T": {pattern: /[12]/, optional: false, recursive: true},
            "C": {pattern: /[09]/, optional: false, recursive: true}
        }
    });

The code above can mask and pre-validate dates in YEAR/MONTH/DAY format.

With an input like

<input type="text" data-role="date" value="2018-06-11 15:47" />

would be changed his value to 2018/06/11.

If you try to type another date (after clear, of course) you cannot begin with a number different from 1 or 2. This reason is that our mask have a translation to be done when allowing chars. If the pattern does not match, the char is erased.

The meaning of “TC99/M9/D9” mask is:

  • Must begin with 1 or 2 (Translation T: /[12]/ – Custom format)
  • Must have number 0 or 9 (Translation C: /[09]/ – Custom format)
  • Must have a number (any) (Translation 9 – MaskPlugin Core format)
  • Must have a number (any) (Translation 9 – MaskPlugin Core format)
  • A slash will be added automatic ( / )
  • Must have number 0 or 1 (Translation M: /[01]/ – Custom format)
  • Must have a number (any) (Translation 9: MaskPlugin Core format)
  • A slash will be added automatic ( / )
  • Must have number 0, 1, 2 or 3 (Translation D: /[0-3]/ – Custom format)
  • Must have a number (any) (Translation 9: MaskPlugin Core format)

Of course, there is no real validation. You can type “2999/19/39” and this is not a valid date, but is almost done.

So, to format in another way, just change mask parameter order.

But, if the source date is in a different pattern, like MONTH/DAY/YEAR, the mask do not work. The date output for “06/11/2018 15:40” will be weird “1018/15/0“.

To handle different date formats will be needed more than simple mask. We will need a function.

Look the code below

        var maskBehaviorDateTime = function (val, e, field) { // This function must return a MASK
                    var msk = "TC99/M9/D9"; // Our desired format
                    var v = field.is('input') ? field.val() : field.text(); // is a input or another html element??
                    v = v.replace(/\D/g, ''); // stripe non digits
                    if (v != '') { // has value?
                        if ((/^[01]\d[0-3]\d\d{4}$/).test(v)) { //test if pattern match Month/Day/Year only
                            v = v.replace(/^(\d{4})(\d{2})(\d{2})$/, '$3/$2/$1');
                        } else if ((/^[01]\d[0-3]\d\d{4}[012]\d[0-5]\d$/).test(v)) { //test if pattern match Month/Day/Year Hour:Minute
                            v = v.replace(/^(\d{2})(\d{2})(\d{4})(\d{2})(\d{2})$/, '$3/$2/$1');
                            // If we need to show hour and minute, returned mask must be changed too
                            // v = v.replace(/^(\d{2})(\d{2})(\d{4})(\d{2})(\d{2})$/, '$3/$2/$1 $4:$5');
                            // msk = 'TC99/M9/D9 h9:m9'; // h and m must be exists in Translation options
                        }
                        field.is('input') ? field.val(v) : field.text(v);
                    }
                    return msk;
                },
                optionsDateTime = {
                    placeholder: "____/__/__",
                    translation: {
                        "D": {pattern: /[0-3]/, optional: false, recursive: true},
                        "M": {pattern: /[01]/, optional: false, recursive: true},
                        "T": {pattern: /[12]/, optional: false, recursive: true},
                        "C": {pattern: /[09]/, optional: false, recursive: true},
                        "h": {pattern: /[0-2]/, optional: true, recursive: true},
                        "m": {pattern: /[0-5]/, optional: true, recursive: true}
                    }
                };
        jQuery('[data-role="date"]').mask(maskBehaviorDateTime,  optionsDateTime);

Now we have two more Translation Pattern (h and m). h means that the n-index position must have numbers 0, 1 or 2 and m numbers between 0 and 5. Keep in mind that CASE matters.

With the above code, we can format and show date in several ways. just change .test() and .replace() pattern to fill your desired pattern.

This is the code that I am using to format Database datetime fields with YEAR-MONTH-DAY HOUR:MINUTE:SECOND in html elements with DAY/YEAR/MONTH HOUR:MINUTE

    var maskBehaviorDateTime = function (val, e, field) {
            // Caso já exista um valor, o formata no padrão dd/mm/yyyy com o opcional hh:mm:ss
            var msk = "TC99/M9/D9 h9:m9:s9";
            if (field.attr("data-original-value") == undefined) {
                var o = field.is('input') ? field.val() : field.text();
            } else {
                var o = field.attr("data-original-value");
            }
            v = o.replace(/\D/g, '');
            if (v != '') {
                field.attr("data-original-value") == undefined && field.attr("data-original-value", o);
                if ((/^[12][09]\d{2}[01]\d[0123]\d$/).test(v)) { // year/month/day
                    v = v.replace(/^(\d{4})(\d{2})(\d{2})$/, '$3/$2/$1');
                    msk = "D9/M9/TC99";
                } else  if ((/^[12][09]\d{2}[01]\d[0123]\d[012]\d[0-5]\d$/).test(v)) { // year/month/day hour:minute
                    v = v.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$3/$2/$1 $4:$5');
                    msk = "D9/M9/TC99 h9:m9";
                } else if ((/^[12][09]\d{2}[01]\d[0123]\d[012]\d[0-5]\d[0-5]\d$/).test(v)) { // year/month/day hour:minute:second
                    v = v.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$3/$2/$1 $4:$5:$6');
                    msk = "D9/M9/TC99 h9:m9:s9";
                }
                field.is('input') ? field.val(v) : field.text(v);
            }

            return msk;
        },
        optionsDateTime = {
            placeholder: "__/__/____",
            translation: {
                "D": {pattern: /[0-3]/, optional: false, recursive: true},
                "M": {pattern: /[01]/, optional: false, recursive: true},
                "T": {pattern: /[12]/, optional: false, recursive: true},
                "C": {pattern: /[09]/, optional: false, recursive: true},
                "h": {pattern: /[0-2]/, optional: true, recursive: true},
                "m": {pattern: /[0-5]/, optional: true, recursive: true},
                "s": {pattern: /[0-5]/, optional: true, recursive: true}
            },
        };
    jQuery('[data-role="date"]').mask(maskBehaviorDateTime,  optionsDateTime);

With an input like

<input type="text" data-role="date" value="2018-06-11 15:40">

Output will be

11/06/2018 15:40

Hope this help you!

Binding several values in PDO SQL Statement (PDOStatement)

Sometimes we need to search a single value through several columns when building SQL instructions.

Suppose the table below

  • [ENTITY_ONE]
    • ID
    • COLUMN_A
    • COLUMN_B
    • COLUMN_C
    • COLUMN_D
    • COLUMN_E

If we need search a single value on columns B,D and E we will need use the following instruction

SELECT ID, COLUMN_A,(...COLUMNS..), COLUMN_E 
FROM ENTITY_ONE WHERE COLUMN_B LIKE '%search_value%' OR COLUMN_D LIKE '%search_value%' OR COLUMN_E LIKE '%search_value%';

In PHP code we can do

$q = '%search_value%';
$sql = "SELECT * FROM ENTITY_ONE WHERE COLUMN_B LIKE '$q' OR COLUMN_D LIKE '$q' OR COLUMN_E LIKE '$q'; 
$pdo = new PDO($dsn, $user, $pass); 
$stmt = $pdo->query($sql);

Well, this can work but we know that isn’t the best approach. We need use Binding Values to avoid SQL injection and other malicious treats.

So, the code can be modified to

$q = '%search_value%'; 
$sql = "SELECT * FROM ENTITY_ONE WHERE COLUMN_B LIKE ? OR COLUMN_D LIKE ? OR COLUMN_E LIKE ?; 
$args = [$q, $q, $q]; // We need one entry for each "?" on instruction
$pdo = new PDO($dsn, $user, $pass); 
$stmt = $pdo->prepare($sql);
$stmt->execute($args);

Much better, but, when building complex SQL instruction, things can be confusing with lots of arguments and don’t forget: ORDER MATTERS.

Happily PDO can bind values in different order when using named bindings.

$q = '%search_value%'; 
$sql = "SELECT * FROM ENTITY_ONE WHERE COLUMN_B LIKE :first_arg OR COLUMN_D LIKE :second_arg OR COLUMN_E LIKE :third_arg; 

$pdo = new PDO($dsn, $user, $pass); 
$stmt = $pdo->prepare($sql); 
// One way
$args = [':first_arg' => $q, ':third_arg' =>$q, ':second_arg' => $q]; // We need one entry for each ":name" on instruction 
$stmt->execute($args); 
// Another way
$stmt->bindValue(':third_arg'. $q);
$stmt->bindValue(':first_arg', $q); 
$stmt->bindValue(':second_arg', $q);

$stmt->execute(); 

Hmm, seems that this isn’t good enough. We only change the use of 1-indexed placeholder to a :named placeholder. There’s no gain beyond of code readable and the possibility to bind in any order.

Yes, but now we can do the best approach when using one unique search term in several columns. We can use only one bind to one or more :named placeholders ’cause PDO is smart and clever. Look our final code here.

$q = '%search_value%'; 
$sql = "SELECT * FROM ENTITY_ONE WHERE COLUMN_B LIKE :unique_arg OR COLUMN_D LIKE :unique_arg OR COLUMN_E LIKE :unique_arg; 
$pdo = new PDO($dsn, $user, $pass); 
$stmt = $pdo->prepare($sql); 
// One way 
$args = [':unique_arg' => $q]; // We can bind all :name with only one term 
$stmt->execute($args); 
// Another way 
$stmt->bindValue(':unique_arg', $q); 
$stmt->execute(); 

Can save a lot of typing when writing many SQL instruction using same argument.

Correcting modules not loaded error on Centos 6. x

A common problem after upgrading a kernel via yum on Centos is not creating the new kernel modules.
An example of this error happens when you try to use grep as in the print below.


# iptables-L-n | grep "my ip"
FATAL: Could not load/lib/modules/2.6.32-042stab123.9/modules.dep: No such file or directory


#
This indicates that the directory 2.6.32-042stab 123.9 and therefore any module in your content can be loaded.

To correct this problem, the simplest way is this recipe:


# mkdir -p /lib/modules/uname -r


# cd /lib/modules/uname -r
[root@vps3 2.6.32-042stab123.9]# depmod
[root@vps3 2.6.32-042stab123.9]# ls -lah
total 64K
drwxr-xr-x 2 root root 4.0K Oct 18 16:11 .
dr-xr-xr-x 10 root root 4.0K Oct 18 16:11 ..
-rw-r--r-- 1 root root 45 Oct 18 16:11 modules.alias
-rw-r--r-- 1 root root 12 Oct 18 16:11 modules.alias.bin
-rw-r--r-- 1 root root 69 Oct 18 16:11 modules.ccwmap
-rw-r--r-- 1 root root 0 Oct 18 16:11 modules.dep
-rw-r--r-- 1 root root 12 Oct 18 16:11 modules.dep.bin
-rw-r--r-- 1 root root 73 Oct 18 16:11 modules.ieee1394map
-rw-r--r-- 1 root root 141 Oct 18 16:11 modules.inputmap
-rw-r--r-- 1 root root 81 Oct 18 16:11 modules.isapnpmap
-rw-r--r-- 1 root root 74 Oct 18 16:11 modules.ofmap
-rw-r--r-- 1 root root 99 Oct 18 16:11 modules.pcimap
-rw-r--r-- 1 root root 43 Oct 18 16:11 modules.seriomap
-rw-r--r-- 1 root root 131 Oct 18 16:11 modules.softdep
-rw-r--r-- 1 root root 49 Oct 18 16:11 modules.symbols
-rw-r--r-- 1 root root 12 Oct 18 16:11 modules.symbols.bin
-rw-r--r-- 1 root root 189 Oct 18 16:11 modules. usbmap
[root@vps3 2.6.32-042stab123.9]# iptables-L-n | grep "my ip"
[root@vps3 2.6.32-042stab123.9]#
This will create the directory and dependencies to modules for the kernel currently in use (uname -r).

If the problem is not resolved with the above commands. Try to reinstall the kernel via yum with the commands below.

mv /boot/grub/grub.conf /boot/grub/grub.conf.bak yum -y reinstall kernel

And then try the commands listed earlier.

I hope you find it useful both when it was for me.

Samsung USB Drivers for Mobile Phones

I advise you read the whole page before download.

This page is actually a kind of backup of the files that I need. To avoid becoming a searching and seeing hundreds of pages full of advertising available here for my own use and thus is available for you also.

The Samsung drivers that allow

Continue Reading >>

How to retrieve a cell phone Samsung Galaxy using the hardware-download mode

I play enough with cell phones. Currently I'm investing in equipment to do more than open an iPhone to replace battery or set Touch + Screen.

Had it in my hands not long ago a cell phone Samsung Galaxy Ace model GT-S5830C. I played a lot with him flashing ROMs and I taught my teenage son to do the basics and the phone ended up with him.

One day he came to tell me that there was flashed a wrong in the device ROM

Continue Reading >>

Using Notepad++ to remove accents

Today I share a tip to facilitate the replacement of accented characters using only Notepad++ and your HTML Tag Plugin.

Let’s do it!

First of all, we must have HTML Tag Plugin installed. If you already have it, jump to step 4.

  1. Open Notepad++ and look for Plugins in Main Menu.
    Notepad Plugins Menu Item
  1. If HTML Tag is absent, open Plugin Manager->Show Plugin Manager and find HTML Tag Plugin on the list.
    HTML Tag Plugin on Notepad++ Plugin Manager
  2. Select the desired Plugins and hit Install button. Notepadd++ will restart to complete the install.
    Now we can translate special characters to yours HTML entities. We need to do it first to remove accents from our text.
  3. Put your text on the window and make Select All with Ctrl + A or Edit -> Select All in Main Menu.
  4. Open Plugins->HTML Tag->Encode Entities in Main Menu or CTRL + E.
    Now, all special characters will be in html entities.
    Notepad++ With Special Characters Encoded in HTML
  5. Open the Replace Form (CTRL + H or Search->Replace) and fill the Find What field with
    &([a-zA-Z])(:?grave|acute|circ|uml|aring|cedil|slash|tilde); and Replace with field with

    $1

    Select Regular Expression in Search Mode and hit Replace All button.
    Notepad++ Replace Form
    The text will be replaced with no accents characters, but all other special chars will be in HTML entity.
    Notepad++ HTML replaced text

  6. Now we can return all other chars to your originals but is better to use your text in UTF-8 encoding. Go to Encoding Menu and change text encoding if is not Utf-8. You can return to another encoding after this step.
    To decode HTML use CTRL + Shift + E or Plugins->HTML Tag->Decode Entities.
    Notepad++ Final Text convertion

I Hope that help someone.

 

Relembrando o passado…

Mexendo nos meus arquivos pessoais encontrei esta mensagem que escrevi logo após o término das eleições presidenciais de 2014. Não sei porque não estava publicada no meu blog pessoal, mas lembro de ter publicado no Facebook. Como quase não estou mais usando Facebook vou [re]publicar o texto na íntegra.

Principais Candidatos Eleições 2014

Principais Candidatos Eleições 2014

 

Acho engraçado que algumas pessoas usem o Facebook para tentar me convencer de alguma coisa subjetiva como se ela fosse bem mais esperta que os outros (e que eu, já que isso aqui “lemos” sozinho e não em grupo) e não aceitam discordâncias. Alguns, após 2 ou 3 comentários contrários apelam para “ESSA CONTA DE FB é MINHA, POSTO O QUE EU QUISER”.
Será que nunca entenderam o que quer dizer “COPO MEIO CHEIO OU MEIO VAZIO?”
Tudo que é subjetivo costuma não ter escolha certa ou errada. Se uma coisa ou situação tem fatos comprobatórios, já não é mais subjetivo, é concreto e nesse caso é questão de aceitar ou não, como uma demissão que você não imaginava ou seu time que está bem, perder do lanterna. O que é subjetivo é alcançado a conclusão mediante experiência pessoal e estado de espírito.
Talvez porque eu “quase” nunca tente convencer ninguém de que estou certo e me abro a discussão para que argumente seu ponto de vista, fico indignado quando vejo intolerantes, preconceituosos, arrogantes e inflexíveis disseminando sua inteligência superior.
Antes de tentar convencer alguém com argumentos tirados de capas de revistas, títulos de artigos ou vídeos de usuários do facebook a qual a conta nunca é confirmada, dê-se trabalho ao menos de ler esses conteúdos sob um prisma crítico. As pessoas para quem você vai se dirigir podem ser aquelas que leem 20 livros por ano, diversos jornais nacionais e internacionais em português ou outro[s] idioma[s] e podem derrubar seus argumentos em poucos segundos se você não estiver embasado em algo concreto.
Estou escrevendo isso pensando nas mensagens sobre divisão do país divulgadas principalmente por paulistas. Quando vêem torcedores do Rio Grande do Sul cantarem o hino do RS sobre o hino nacional em algum evento acham absurdo. Pregam união, e repudiam as atitudes separatistas, mas quando uma grande parte do país não segue sua ideologia política a primeira coisa que começa a defender é algo que repudia nos outros.

Reprodução da postagem do deputado eleito Coronel Telhada (PSDB) que gerou polêmica

Reprodução da postagem do deputado eleito Coronel Telhada (PSDB) que gerou polêmica

Essa indignação seletiva paulista é nojenta, atrasada e maléfica.
Aconselho a você que se deu ao trabalho de ler até aqui e se irritou com minhas palavras a ler Vidas Secas, Grande Sertão Veredas e ouvir histórias do Suassuna. Vai se tornar uma pessoa bem melhor.