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

Drunk Penguins

Drunk Penguins
Drunk Penguins