terça-feira, 5 de maio de 2015

Python (2.7 and 3.0) - get/set and operators

Python continue surprising me.

Is possible verify attribute's value using the annotation @ATTR.setter on set method, too you can modify attribute's return using the annotation @property on get method.

 Finalizing this post, is possible with python, override classes' operators like c++.

See the example below. Details in references links.

class Div(object):

    def __init__(self, op, di):
        self.op = op
        self._di = di 
 
    # GET di
    @property
    def di(self):
        return self._di 
 
    # SET di
    @di.setter
    def di(self, value):
        if (value == 0): 
            raise ValueError('Invalid value')
        else:
            self.di = value 
 
    # OPERATOR ADD
    def __add__(a, b): 
        x = Div(0, 0)
        x.op = a.op + b.op
        x._di = a.di + b.di
        return x

    def __str__(self):
        return ("%s/%s") % (self.op, self.di)
    

x = Div(1,3)
y = Div(2,2)

z = x + y 

print(x)
print(y)
print(z)

x.di = 0 
 
Execution's Result:
1/3
2/2
3/5
Traceback (most recent call last):
  File "/tmp/exemplo1.py", line 38, in 
    x.di = 0
  File "/tmp/exemplo1.py", line 15, in di
    raise ValueError('Invalid value')
ValueError: Invalid value

References:

domingo, 12 de abril de 2015

How to access Yosemite MAC partition from Linux

As an addict and old user of the i3 tiling wm. I couldn't use MAC OS more that 6 months, than I decided install Linux in my MAC bookair :D

However this computer offers only 128GB of SSD and I was with many work files, than I needed access this files on my MAC partition, for this I installed the hfsplus-tools avaliable in my Linux distribution, but I can't mount my MAC partition :(

Some research found that Yosemite change its partition from HFS+ to "Core Storage", but is possible do you convert Yosemite’s Core Storage partition back to HFS+. Let's go.

On MAC terminal use the command shown below to get the lvUUID for the partition.

diskutil cs list

This will give you a list of partitions similar to this:

CoreStorage logical volume groups (1 found)
|
+-- Logical Volume Group B6308EC8-132D-44BD-9212-6BD867F6331B
    =========================================================
    Name:         OS X Test
    Status:       Online
    Size:         29349998592 B (29.3 GB)
    Free Space:   204955648 B (205.0 MB)
    |
    +-< Physical Volume 3325F333-C8E3-3EEE-9357-5E0C21A600D1
    |   ----------------------------------------------------
    |   Index:    0
    |   Disk:     disk0s4
    |   Status:   Online
    |   Size:     29349998592 B (29.3 GB)
    |
    +-> Logical Volume Family E8CB0EB7-AA33-48AA-AA13-5DE30867901B
        ----------------------------------------------------------
        Encryption Status:       Unlocked
        Encryption Type:         None
        Conversion Status:       NoConversion
        Conversion Direction:    -none-
        Has Encrypted Extents:   No
        Fully Secure:            No
        Passphrase Required:     No
        |
        +-> Logical Volume 2F7B1893-07E8-4298-840B-F2552042E055
            ---------------------------------------------------
            Disk:                  disk1  
            Status:                Online 
            Size (Total):          28809494528 B (28.8 GB)
            Conversion Progress:   -none-
            Revertible:            Yes (no decryption required)
            LV Name:               OS X Test
            Volume Name:           OS X Test
            Content Hint:          Apple_HFS


If the partition says “Revertible: Yes”? That means we can convert it back.
Use the command shown below to revert this partition to HFS+

diskutil coreStorage revert 2F7B1893-07E8-4298-840B-F2552042E055

Now, come back to Linux and mount your MAC partition normally.

mount -t hfsplus -o force,rw /dev/sda2 /mnt/apple

Good luck

References: http://awesometoast.com/yosemite-core-storage-and-partition-woes/

terça-feira, 7 de abril de 2015

Comunicação Web Service REST e Android

 Este post tem o principal intúito de mostrar a comunicação entre um dispositivo Android e um servidor webservice REST através de classes que realizam o trabalho sujo de transformar objetos em mensagens REST e vice-versa.

Object JSON

Objeto que será transformado em JSON durante o processo de comunicação. 
public class Product {

 String name;
 int qty;
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getQty() {
  return qty;
 }

 public void setQty(int qty) {
  this.qty = qty;
 }

 @Override
 public String toString() {
  return "Product [name=" + name + ", qty=" + qty + "]";
 }
}

REST Server WebService

Webservice JSON REST

Classe de webservice que define endereços REST para os processos GET e POST. Exemplo simplesmente armazena os valores vindos do POST em uma lista de objetos que é devolvida quando requisitado o endereço GET.
@Path("/json/product")
public class JSONService {

        private static List lstProducts = new ArrayList();

 @GET
 @Path("/get")
 @Produces("application/json")
 public List getProductInJSON() {
  return lstProducts; 
 }

 @POST
 @Path("/post")
 @Consumes("application/json")
 public Response createProductInJSON(Product product) {
                lstProducts.add(product);
  String result = "Product created : " + product;
  return Response.status(201).entity(result).build();
 }
}

Link do projeto server-webservice: rest-server-example


Android

A mesma classe Produto foi copiada para projeto Android.

Enviando dados

Classe que envia dados utilizando POST

public class RestPutTask extends AsyncTask<Product, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Product... params) {

        Boolean ret = Boolean.FALSE;

        try {
            final String urlPost = "http://MY_SERVER:8080/test/json/product/post";

            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

            String sRet;
            sRet = restTemplate.postForObject(urlPost, params[0], String.class);
            Log.i("Retorno", sRet);
            ret = sRet != null;

        } catch (Exception e) {
            Log.e("MainActivity", e.getMessage(), e);
        }

        return ret;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
    }

}

Recebendo dados

Classe que recupera objetos através de GET
public class RestGetTasks extends AsyncTask<List<String>, ArrayAdapter, Product[]>{

    private ArrayAdapter adapter;

    public RestGetTasks(ArrayAdapter adapter) {
        this.adapter = adapter;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Product[] doInBackground(List... params) {


        try {
            final String urlPost = "http://MY_SERVER:8080/test/json/product/get";

            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

            String sRet;
            Product[] products = restTemplate.getForObject(urlPost, Product[].class);
            params[0].clear();

            for (Product p : products) {
                Log.i("Produto:", p.getName() + ":" + p.getQty());
                params[0].add(p.getName() + ":" + p.getQty());
            }


        } catch (Exception e) {
            Log.e("MainActivity", e.getMessage(), e);
        }

        return null;

    }

    @Override
    protected void onPostExecute(Product[] products) {
        super.onPostExecute(products);

        adapter.notifyDataSetChanged();
    }
}

Link do projeto android rest example: android-rest-example

Referências:

segunda-feira, 22 de outubro de 2012

Linux: weird intermittent Atheros Wifi solved


Download http://linuxwireless.org/download/compat-wireless-2.6/compat-wireless.tar.bz2
Unpack and compile as root:

./scripts/driver-select atheros
make -j3
make install

make unload
make wlunload
make btunload

rmmod ath9k
modprobe ath9k

domingo, 4 de março de 2012

Linux: Find Dell Service Tag

Type the following command to find out Dell service tag:
# dmidecode | grep -i serial

OR
# dmidecode -t 1

The following command will only display service tag:
# dmidecode -s system-serial-number

Referência: Red Hat / CentOS Command To Find Dell Service Tag

Linux: Locking/Unlocking An Account

Task: Linux Locking an Account

The syntax is as follows:
# passwd -l {username}

The -l option disables an account by changing the password to a value which matches no possible encrypted value. In this example, lock user account named vivek. First, login as a root user and type the following command:
# passwd -l vivek

Task: Linux Unlocking an Account

The syntax is as follows:
# passwd -u {username}

The -u option re-enables an account by changing the password back to its previous value i.e. to value before using -l option. To unlock user account named vivek. Login as a root user and type following command:
# passwd -u vivek

Referência: Linux Locking An Account

Linux: Find Out Maximum RAM Supported By The Server BIOS / Motherboard

Most modern server supports 16GB, 32GB, 64GB or more RAM and has 4 or more DIMM slots. To find out what is the maximum system can support type the following command as root user:
# dmidecode -t 16

You can find out currently installed memory information (DIMM and its slots) by typing the following command:
# dmidecode -t 17

Referência: Linux / Unix: Find Out Maximum RAM Supported By The Server BIOS / Motherboard

Shell: Cat Command Examples

To create a file called "foo.txt", enter:
cat >foo.txt
Unix is the best.
<control-D>

You can combine two files and creates a new file called report.txt, enter:
cat score.txt names.txt > report.txt

To append (add data to existing) data to a file called foo.txt, enter:
cat >>foo.txt
A champion is someone who gets up, even when he can't
<control-D>

You can send files to sound devices such as /dev/dsp or /dev/audio to make sure sound output and input is working:

cat filename >/dev/dsp
cat recording.au >/dev/audio

You can simply use the following command for recording voice sample and play back with it cat command:

dd bs=8k count=4 </dev/audio >testing123.au
cat testing123.au >/dev/audio

No cat cannot print in reverse order but tac command can concatenate and print files in reverse:

tac fileName
cat fileName | tac
tac <<<"$myFileName"

Referência: Linux / Unix: Cat Command Examples

sexta-feira, 21 de outubro de 2011

Linux: getting flash videos from almost deleted files


#!/bin/sh

DATE=$(date +%Y.%m.%d-%H:%M:%S)

lsof | grep Flash | while read LINE; do
PID=$(echo "${LINE}" | awk '{ print $2 }')
FD=$(echo "${LINE}" | awk '{ print $4 }' | sed s/[a-zA-Z]//)
cat /proc/${PID}/fd/${FD} > ~/"${DATE}"-${FD}.flv
done

exit 0


It used to be easy: if you wanted to save a video played using Flash plugin, it was as easy as copying a file from browser's cache. Why use special webpages or plugins, when you could just:

cp /tmp/Flash* ~/video.flv

In other words: you already had that file downloaded by the flash plugin! But it seems Adobe changed this in one of recent updates, and there is no /tmp/Flash* file anymore... or maybe it is?

The cached movie is still written to the filesystem. It is quickly unlinked (a filesystem term for deleting a file) by the plugin, but the plugin still keeps a handle to the file. The result is that the cache file is no longer visible in the directory, but it occupies space on disk and can be read by that handle. This is how filesystems on Linux operate: as long as there is at least one handle to a file, such file won't be deleted from the filesystem.

Now we need to use two tools. First is lsof, which shows all opened handles by all processes. The key knowledge is that the deleted file is still created as /tmp/Flash*. Lets find the handle:

liori% lsof|grep Flash
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
firefox-b 23220 liori 83u REG 254,0 10565348 929 /tmp/FlashXXQCq4K0 (deleted)
I added lsof's header to make it clearer. Note that funny (deleted) remark—when you check the contents of /tmp, you won't see that file! We're interested in the PID and the FD number. FD is the opened handle's number, and PID is an identifier used to distinguish different programs.

Second tool is the /proc filesystem. This is a special directory existing on all commonly used Linux installations. It contains data about running system: driver settings, process list, diagnostic information. What's most interesting is that it contains files representing all opened file handles. In our case (PID=23220 and FD=83) the handle representing our deleted file is /proc/23220/fd/83. Again, if you just try to list that directory, you will only see a broken symlink. But what if you do this?

liori% cat /proc/23220/fd/83 >video.flv
...you'll get the contents of the deleted file!

This technique is of course not only useful to grab videos downloaded by your flash plugin. Any time you delete a file, but realize that it is still opened by some program, you can recover it.

http://liori.jogger.pl/2010/11/08/getting-flash-videos-from-almost-deleted-files/

sábado, 27 de agosto de 2011

Fedora 15: Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller

I get a black screen upon boot if inteldrmfb is enabled. So I needed to boot with the option "nomodeset". But with this option I could just use the vesa driver in Xorg.



One solution is:

1) Remove "nomodeset" and "vga" options from kernel boot parameters

2) Add this options to kernel parameters:

i915.modeset=1 video="inteldrmfb:1440x900"

3) Run setpci -s 00:02.0 F4.B=00 as root to turn the backlight back on. You can do this automatically on boot putting this command in /etc/rc.local



Now you can use intel driver in Xorg.



Reference: http://en.gentoo-wiki.com/wiki/Intel_GMA

quinta-feira, 11 de agosto de 2011

quarta-feira, 27 de julho de 2011

Linux: Automount USB external drive with autofs

To avoid any confusion with the base name of your USB block device, make alias using udev manager:

Making udev device name alias

Edit the file /etc/default/autofs and enable BROWSE and LOGGING:

-BROWSE_MODE="no"
+BROWSE_MODE="yes"

-#LOGGING="none"
+LOGGING="verbose"

Edit the file /etc/auto.master and comment all lines what are not commented.
Add to the end of /etc/auto.master this line:
/mnt /etc/auto.usbdrive --timeout=2

Create the file /etc/auto.usbdrive:
kingston -fstype=vfat,rw,uid=1000,gid=100,fmask=133,dmask=022,user :/dev/kingston1

Start autofs daemon:
$ (chmod +x /etc/rc.d/rc.autofs ; sh /etc/rc.d/rc.autofs start)

Plug-in the pendrive and see /var/log/messages:

Jul 27 13:29:46 keyra kernel: [17339.948942] sd 9:0:0:0: [sdb] Attached SCSI removable disk
Jul 27 13:30:00 keyra automount[5766]: attempting to mount entry /mnt/kingston
Jul 27 13:30:00 keyra automount[5766]: mount(generic): mounted /dev/kingston1 type vfat on /mnt/kingston
Jul 27 13:30:00 keyra automount[5766]: mounted /mnt/kingston
Jul 27 13:30:01 keyra automount[5766]: 1 remaining in /mnt

Unplug the device:

Jul 27 13:42:35 keyra automount[5766]: expiring path /mnt/kingston
Jul 27 13:42:35 keyra automount[5766]: unmounting dir = /mnt/kingston
Jul 27 13:42:35 keyra automount[5766]: expired /mnt/kingston
Jul 27 13:42:41 keyra kernel: [18115.356920] usb 2-2: USB disconnect, address 9

quarta-feira, 13 de julho de 2011

Shell: Using while loop to read file lines

while IFS= read -r LINE ; do echo "$(date) $LINE" ; done < 20110603-105216.log

Shell: Skip First Two Fields and Print the Rest of Line

Using awk:
$ echo 'This is a test blah foo bar etc' | awk '{print substr($0, index($0,$3))}'
a test blah foo bar etc

Using cut:
$ echo 'This is a test blah foo bar etc' | cut -d ' ' -f3-
a test blah foo bar etc

sábado, 9 de julho de 2011

Shell: Read An Array Using C Style For Loop

$ CONCEITO=("ruim" "fraco" "mediano" "bom" "muito bom" "excelente") ; \

for((i=1;i<11;i++)) ; do echo "#$i = ${CONCEITO[$(($RANDOM%6))]}" ; done



#1 = excelente

#2 = fraco

#3 = ruim

#4 = bom

#5 = ruim

#6 = excelente

#7 = mediano

#8 = mediano

#9 = excelente

#10 = muito bom





Obs: Array length: ${#CONCEITO[@]}

terça-feira, 5 de julho de 2011

Postgresql: show tables, show databases, show columns

mysql: SHOW TABLES
postgresql: \d
or
postgresql: SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';

mysql: SHOW DATABASES
postgresql: \l
or
postgresql: SELECT datname FROM pg_database;

mysql: SHOW COLUMNS
postgresql: \d table
or
postgresql: SELECT column_name FROM information_schema.columns WHERE table_name ='table';

Shell: Retrieve empty directories

$ find -type d -empty

domingo, 26 de junho de 2011

Shell: Count Number of Characters in a String

x="This is a test"
y="${x//[^s]}"
echo "$y"
echo "${#y}"


To match both 's' and 'S', enter:

x="This is a test. S"
y="${x//[^s|S]}"
echo "${#y}"

sexta-feira, 3 de junho de 2011

Drunk Penguins

Drunk Penguins
Drunk Penguins