Wednesday, December 26, 2012

ExtJS4: paggingtoolbar refresh button is not working propertly

The refresh button wasn't refreshing when I was clicking it. After hours of searching on the web I finally got the problem. The initial code was a definition of a gridpanel:


Ext.define('WebMonitorClass.view.BodegaGridPanel', {    
    extend: 'Ext.grid.Panel'
    ,alias: 'widget.bodegaGridPanel'

...
...
...
,store: Ext.create('WebMonitorClass.store.BodegasCrudGridPanelStore')
,bbar: {
            xtype: 'pagingtoolbar'
            ,dock: 'bottom'
            ,store : Ext.create('WebMonitorClass.store.BodegasCrudGridPanelStore')                                   
        }
...
...
...

}

The way to make it work is instantiating the store an setting it to the grid store and to the paging toolbar. All this occurs in the initComponent method  :

Ext.define('WebMonitorClass.view.BodegaGridPanel', {    
    extend: 'Ext.grid.Panel'
    ,alias: 'widget.bodegaGridPanel'
...
...
...
,initComponent: function() {
        
           this.store = Ext.create('WebMonitorClass.store.BodegasCrudGridPanelStore'); // initialize store
        
        this.bbar = Ext.create('Ext.toolbar.Paging', {
            // se obtiene error Uncaught TypeError: Cannot read property 'id' of undefined             
            //xtype: 'pagingtoolbar'
            dock: 'bottom'
            ,store : this.store // setting the previously initialized store to the pagging toolbar
            ,displayInfo: true
            ,displayMsg: 'Displaying topics {0} - {1} of {2}'
            ,emptyMsg: "No topics to display"
            ,listeners: {                
                afterrender: function (component){
                    //component.down('#refresh').hide()
                }
            }                              
            });
        
        this.callParent();
        
    }
...
...
...

}

Resource:
http://try.sencha.com/extjs/4.1.1/community/extjs4-mvc-paging-grid/

Monday, December 24, 2012

ExtJS 4.1: “Uncaught TypeError: Cannot call method 'substring' of undefined”

I was getting the error :

“Uncaught TypeError: Cannot call method 'substring' of undefined”

When I was trying to initialize an object from this class definition:


Ext.define('WebMonitorClass.view.CrearBodegaFormPanel', {    
    extend: 'Ext.form.FormPanel'
    ,alias: 'widget.crearBodegaFormPanel'       
    ,layout:'absolute'
    ,border:false
    ,padding : '0 0 5 0'
    ,bodyStyle:'background-color: #DFE9F6;'
    ,width:360
    ,height:110
    ,initComponent: function() {                                                    
        this.callParent();                                    
    }
    ,items:[
        {xtype: 'bodegaDatosBasicosFieldSet'}
    ]
    ,buttonAlign:"center"
    ,buttons:[]
});

the solution was adding the require config parameter importing the file which that contains the definition of the bodegaDatosBasicosFieldSet class:

,requires: [ 'WebMonitorClass.view.BodegaDatosBasicosFieldSet' ]

So, the resulting class definition was


Ext.define('WebMonitorClass.view.CrearBodegaFormPanel', {    
    extend: 'Ext.form.FormPanel'
    ,requires: [ 'WebMonitorClass.view.BodegaDatosBasicosFieldSet' ] // here is what I added
    ,alias: 'widget.crearBodegaFormPanel'       
    ,layout:'absolute'
    ,border:false
    ,padding : '0 0 5 0'
    ,bodyStyle:'background-color: #DFE9F6;'
    ,width:360
    ,height:110
    ,initComponent: function() {                                                    
        this.callParent();                                    
    }
    ,items:[
        {xtype: 'bodegaDatosBasicosFieldSet'}
    ]
    ,buttonAlign:"center"
    ,buttons:[]
});



Friday, December 21, 2012

Django: _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

Trying to init my Django project I was getting this error:


_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

I was using this configuration


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'backendtest',                      # Or path to database file if using sqlite3.
        'USER': 'remoteuser',                      # Not used with sqlite3.
        'PASSWORD': '123456789',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}

the solution is pretty simple, change the host value from 'localhost' to 127.0.0.1:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'backendtest',                      # Or path to database file if using sqlite3.
        'USER': 'remoteuser',                      # Not used with sqlite3.
        'PASSWORD': '123456789',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Now all works fine

Reference:

Thursday, December 20, 2012

MySQL: grant remote access


GRANT ALL PRIVILEGES ON backendtest.* TO remoteuser@'%' IDENTIFIED BY '123456789';

Resource:
http://31bit.com/technology/86-mysql-database/302-how-to-grant-remote-access-to-a-mysql-database

MySQL: Adding foreing keys


ALTER TABLE phone ADD 
      CONSTRAINT FK_phone_person_num
      FOREIGN    KEY (person_num)
      REFERENCES person(num)

Resource:
http://www.sqlinfo.net/mysql/mysql_Create_foreign_key_contraints.php


Monday, December 3, 2012

ExtJS 4 : How to submit form or set listener to button without using Ext.getCmp and setting id

Use the up() method to get the ancestor element (ie form):

{
    xtype:'button' 
    ,text:'Crear Bodega'
    ,listeners: {                                      
         'click' : function(){               
              // get the form type ancestor which contains the button                                      
              var myFormPanelObj = this.up('form');
              var data  =   myFormPanelObj.getForm().getValues();
              console.log("data: " + Ext.JSON.encode(data));
                                             
           }
      }
}

Resource:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.button.Button-method-up

Friday, November 2, 2012

Java: REST Sample

Here is a simple and great example of a REST API written in Java using  JAX-RS

http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/

Javascript: sleep php like function for javascript


Use hold() method from StratifiedJS:

<script src="http://code.onilabs.com/apollo/0.13/oni-apollo.js"></script>
<script type="text/sjs">
  for (var i = 1; i < 4; i++) {
      alert(i);
      hold(1000);
  }
</script>

Reference:
http://stackoverflow.com/questions/10690801/sleep-function-in-javascript-without-using-recursion
http://onilabs.com/stratifiedjs

Thursday, November 1, 2012

Javascript: handling static methods and instance methods

<html>
    <head>
    </head>
    <body>        
        <script type="text/javascript">                
            
            // Calculator1 "class" declaration
            function Calculator1(){
                /* instance multiply sum that will be available for the
                Calculator1 objects but not for the Calculator1 "class" */
                this.multiply = function(val1 , val2){
                    return (val1*val2);
                }
            }
            
            /* instance method sum that will be available for the
            Calculator1 objects but not for the Calculator1 "class" */
            Calculator1.prototype.sum = function(val1 , val2){
                return (val1+val2);
            }
            
            // calculator1 object/instance
            var calc1 = new Calculator1();
            
            // call to multiply, that is an instance method
            console.log(calc1.multiply(4,3)); // 12
            
            /* error because multiply is an instance
            method not a Calculator1 "class" method */
            //console.log(Calculator1.multiply(4,3)); 
            
            // call to sum, that is an instance method
            console.log(calc1.sum(4,3)); // 7
            
            /* error because sum is an instance method
            not a Calculator1 "class" method */
            //console.log(Calculator1.sum(4,3)); 
            
            // Calculator2 "class" declaration
            function Calculator2(){}
            
            // static method of the "class" Calculator 2
            Calculator2.multiply = function(val1 , val2){
                return (val1*val2);
            }
            
            var calc2 = new Calculator2();
            
            // call to multiply, that is a Calculator2 "class" method
            console.log(Calculator2.multiply(4,3)); // 12
            
            /* error because multiply is a Calculator2 "class" method
              not an instance method and it doesn't get inherited to be called
              from instances, it can only be called from the Calculator2 "class" */       
            //console.log(calc2.multiply(4,3)); 
                    
        </script>    
    </body>
</html>

Resources:

Wednesday, October 31, 2012

ExtJS4: date formatting reference

Here is a nice guide to handle date formatting with ExtJS4:

http://senchaexamples.com/2012/05/03/formatting-dates-using-ext-js-4/

HTML5 : input date referred types not supported on almost all browsers

Be careful, most of the date referred types like date,datetime,time,month,week are not currently supported by Chrome or FF or IE,

http://www.quirksmode.org/html5/inputs.html

Jquery: change label text

in html file:

...
<label id="resultadoconsulta">my Old Text</label>
...

in javascript:

$('#resultadoconsulta').text("my New Text");

Resource:
http://stackoverflow.com/questions/3584145/change-text-of-label-in-jquery

JQuery Validation Plugin: simple demo

Javascript: convert from string to integer

Use parseInt:

var myString = "34";
var myIntegerFromString = parseInt(myString); // 34 (integer)

console.log("myString ");
console.log(myString); // 34
console.log(typeof myString); //string

console.log("myIntegerFromString ");
console.log(myIntegerFromString); // 34
console.log(typeof myIntegerFromString); //integer

Resource:
http://www.javascripter.net/faq/convert2.htm
http://www.javascriptkit.com/javatutors/determinevar2.shtml


Python: delete element from dict

Use del:

dict2 = {"key1":"value1","key2":"value2","key3":"value3"}

print "############### print before del#################"
for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)
    
del dict2["key2"]

print "############### print after del#################"
for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)

Resource:
http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary

Python: validate if attribute is a instance method


Use type() or isinstance() functions:

# test.py

import types

class Person():
    def __init__(self,fistname,lastname):
        self.fistname = fistname
        self.lastname = lastname
        
    def run(self):
        print "run"
        
    def jump(self):
        print "jump"

myPerson = Person("jack","smith")
for name in dir(myPerson):
    print "name: %s" % (name)
    myAttrib = getattr(myPerson, name)
    print "myAttrib: %s" % (myAttrib)    
    print "(type(myAttrib)) == types.MethodType: %s" % ((type(myAttrib)) == types.MethodType)
    print "isinstance(myAttrib, types.MethodType: %s" % (isinstance(myAttrib, types.MethodType))
   
Result:


C:\Users\John\Desktop>python test.py
name: __doc__
myAttrib: None
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: __init__
myAttrib: <bound method Person.__init__ of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: __module__
myAttrib: __main__
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: fistname
myAttrib: jack
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: jump
myAttrib: <bound method Person.jump of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: lastname
myAttrib: smith
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: run
myAttrib: <bound method Person.run of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True

Resources:
http://stackoverflow.com/questions/624926/how-to-detect-whether-a-python-variable-is-a-function
http://docs.python.org/2/library/types.html
http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python


Python: iterate dict

dict2 = {"key1":"value1","key2":"value2","key3":"value3"}

for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)

Result:


C:\Users\John\Desktop>python test.py
key: key3 , value: value3
key: key2 , value: value2
key: key1 , value: value1


Resource:
http://stackoverflow.com/questions/6332691/python-dictionary-iteration


HTML5: show hint when input type text is empty

Use placeholder attribute:

<input type = "text" name="text" placeholder="Email Address">

Reference:
http://stackoverflow.com/questions/108207/how-do-i-make-an-html-text-box-show-a-hint-when-empty

Apache: Origin is not allowed by Access-Control-Allow-Origin.


Enable in the httpd.conf file:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

In the ./extra/httpd-proxy.conf file set:

ProxyRequests Off
ProxyPreserveHost On

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

Also add  the url you want ie, for /document:

ProxyPass /document http://192.168.2.12:8080/document
ProxyPassReverse /document http://192.168.2.12:8080/document
<Location /document>
    Order allow,deny
    Allow from all
</Location>


Finally restart apache

Resource:
http://stackoverflow.com/questions/7807600/apache-mod-proxy-configuring-proxypass-proxypassreverse-for-cross-domain-ajax

JQuery Validation Plugin: validate onclick


$('#link').click(function() 
   { 
      // call .valid() method for each field
      if ($("input[name=name]").valid() && $("input[name=email]").valid()) 
      { 
         // do some stuff 
      } 
      else 
      { 
         // just show validation errors, dont post 
      } 
   });

Reference:
http://stackoverflow.com/questions/9129029/jquery-validation-onclick

Tuesday, October 30, 2012

ExtJS4: date format reference

There is a very useful link with the reference of the Extjs4 date formatting

http://senchaexamples.com/2012/05/03/formatting-dates-using-ext-js-4/

Google Maps V3: get latitude and longitude by location name


var geocoder = new google.maps.Geocoder();
var address = "bogota, colombia";
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK)
  {
      // do something with the geocoded result
      var myLat = results[0].geometry.location.Ya;
      var myLng = results[0].geometry.location.Za;
      console.log("latitude: " +myLat );
      console.log("longitude: " +myLng );
  }
});

Reference:
http://stackoverflow.com/questions/3490622/get-latitude-and-longitude-based-on-location-name-google-maps-api

Friday, October 26, 2012

Apache: [warn] (OS 64)The specified network name is no longer available. : winnt_accept: Asynchronous AcceptEx failed.

If you get this error:

[warn] (OS 64)The specified network name is no longer available.  : winnt_accept: Asynchronous AcceptEx failed. 

Try adding the following line to your httpd.conf file:

Win32DisableAcceptEx

Resource:
http://www.apachelounge.com/viewtopic.php?p=10611
http://www.mydigitallife.info/winnt_accept-asynchronous-acceptex-failed-error-in-apache-log/

Monday, October 22, 2012

Javascript: count number of attributes of an Object

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
var myObjectPropertiesCount = 0;
         
 for (var myObjectElement in myObject){
      myObjectPropertiesCount++;
 }

console.log(myObjectPropertiesCount);//3

Resource:
http://stackoverflow.com/questions/1345939/how-do-i-count-a-javascript-objects-attributes


Friday, October 19, 2012

PHP: Unable to load dynamic library 'php_oci8.dll' , the procedure entry point ocilobread2 could not be located

Situation:

The Apache service wasn't starting

in the Apache error.log file I was getting the following error:

"Warning: PHP Startup: Unable to load dynamic library 'C:/php/ext/php_oci8.dll' - The specified procedure could not be found. \r \n in Unknown on line 0"

the I tried to execute from windows console the php command and I got the following error in an emerging window:

"the procedure entry point ocilobread2 could not be located in the dynamic link library oci.dll"

And also, in the PHP console, I got the error that I mentioned in the beginning of this post : "... Unable to load dynamic library .... "

Solution:

- download and unzip instantclient_10_2

- set PATH variable with the instantclient_10_2 folder route ie (C:\instantclient_10_2) . Note: Is VERY important that the instantclient path must be added at beginning of PATH variable or VERIFY the PATH variable in order to avoid having other routes to a different instanclient.

- check up php command in console

- restart APACHE


Resource:

https://forums.oracle.com/forums/thread.jspa?messageID=2324855

http://ivoronline.com/Coding/Languages/PHP/Tutorials/PHP%20-%20Errors%20-%20The%20specified%20procedure%20could%20not%20be%20found.php



Wednesday, October 10, 2012

Windows 7: One way ping

I have two machines connected to the same wireless network:

  • Machine1: SO: Windows7 , IP 192.168.10.20
  • Machine2: SO: Windows7 , IP 192.168.10.11
#Ping from machine1 to machine 2
>ping 192.168.10.11
Pinging 192.168.10.11 with 32 bytes of data:
Reply from 192.168.10.11: bytes=32 time=362ms TTL=128
Reply from 192.168.10.11: bytes=32 time=74ms TTL=128
Reply from 192.168.10.11: bytes=32 time=99ms TTL=128

#ping from machine2 to machine1
>ping 192.168.10.20
Pinging 192.168.10.20 with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 192.168.10.20:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss)

I solved the problem enabling a firewall rule in the machine1 following these steps:

1. Click on Start Icon
2. Type "Windows Firewall"
3. Click on Windows Firewall with Advanced Security
4. Click on Inbound Rules 
5. Look for the following rule:
    • Name: "File and Printer Sharing (Echo Request - ICMPv4-In)"
    • Profile: "Private,Public"
6. Right Click on the rule
7. Click on "enable rule"

Resource:


Extjs4.1: center buttons in formPanel

use the config buttonAlign:

{
   ...
   ,...
   ,buttonAlign: "center" // here

   ,buttons: [
     { text: 'Button 1' }
   ]

}

Resource:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.form.Panel-cfg-buttonAlign

Ubuntu11.04 : cp: cannot create symbolic link: Operation not permitted


The problem is because your destination device doesn't support the symbolic link creation, mainly because of it's format. In my case, the destination device format was Fat-32. Then there are 2 options:

1. Format your destination device with a format that support the symbolic link creation like NTFS format. And try again the cp command

2. Copy the entire file instead of the symbolic link, using -L option in the cp command:

cp -rL source_dir dest_dir

Resource:
http://diogomelo.net/node/46

Tuesday, October 9, 2012

ExtJS4.1: Modal Window

Use the modal config:


                      var myWindow = Ext.create("Ext.Window",{
                                width : 200
                                ,height: 200
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : true
                                ,modal:true // here
                            }).show();

Resources:
http://stackoverflow.com/questions/6053847/how-to-make-a-full-modal-window-in-ext-4

ExtJS4.1: Set background color to Panel

Use bodyStyle config:

 new Ext.Panel({
    width:200,
    height:200,
    bodyStyle:'background-color: #DCE8EA;' // here  
});

Resources:
http://www.sencha.com/forum/showthread.php?75830-Panel-background-color

ExtJS4.1 : Uncaught TypeError: Cannot call method 'getWidth' of undefined


I created a formpanel, which has a predefined width and height:

var myCrearUsuarioFormPanel = Ext.create('WebMonitorClass.view.CrearUsuarioFormPanel');

Know I needed to put my myCrearUsuarioFormPanel into a window. I needed to set the window width and height the same as the myCrearUsuarioFormPanel width and height:
                         
                            var myWindow = Ext.create("Ext.Window",{
                                width : myCrearUsuarioFormPanel.getWidth() //  here I tried that
                                ,height: myCrearUsuarioFormPanel.getHeight() // here I tried that
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : false                                
                                ,items:[myCrearUsuarioFormPanel]
                            }).show();

But I Got:

Uncaught TypeError: Cannot call method 'getWidth' of undefined 

in this line

width : myCrearUsuarioFormPanel.getWidth()

The solution is to use the offsetWidth and offsetHeight properties:


                          var myWindow = Ext.create("Ext.Window",{
                                width : myCrearUsuarioFormPanel.offsetWidth // Here is the solution
                                ,height: myCrearUsuarioFormPanel.offsetHeight // Here is the solution
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : false                                
                                ,items:[myCrearUsuarioFormPanel]
                            }).show();

Resource:
http://stackoverflow.com/questions/5249723/wrong-div-width-when-getting-it-with-javascript
http://stackoverflow.com/questions/10634282/in-extjs-when-dragdrop-offsetwidth-is-null-or-not-an-object-error-for-ie7

Monday, October 8, 2012

Microsoft Visio 2007: Create Sitemap


Open Microsoft Visio 2007 and go Go to "File" > "New" > "Software and Database" > "Conceptual Web Site (Metric)".

Here is a complete Guide Video:
http://www.youtube.com/watch?v=RZpRaU2UYOQ

Sunday, October 7, 2012

Javascript: substring


var str="Hello world!";
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,7));

Reference:
http://www.w3schools.com/jsref/jsref_substring.asp

Javascripy: simple encode/decode Json LIbrary

Use the Extjs JSON library

// create new object
var myObject = new Object();
// set properties to the object
myObject["RB"] = "(aBc+ABC)";
myObject["RA"] = "(aBC+AbC)";
myObject["SA"] = "(abc+ABc)";
myObject["SB"] = "(abC+Abc)";
//from javascript object to json text:
var myJsonString = Ext.JSON.encode(myObject);


//from jsontext to javascript object
var myResponseString = '{"RB":"(aBc+ABC)","RA":"(aBC+AbC)","SA":"(abc+ABc)","SB":"(abC+Abc)"}';
var myResponseObject = Ext.JSON.decode(myResponseString);
alert(myResponseObject["RB"]) // "(aBc+ABC)"
alert(myResponseObject["RA"]) // "(aBC+AbC)"
alert(myResponseObject["SA"]) //  "(abc+ABc)"
alert(myResponseObject["SB"]) //  "(abC+Abc)"

Resources:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.JSON
http://www.sencha.com/forum/showthread.php?3333-json-encode-decode

Java: Converting Jsontext to JavaObject

Look at this great sample:


import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Reference:
http://stackoverflow.com/questions/1688099/converting-json-to-java/1688182#1688182

Javascript: Remove Duplicate Values from Array

Using JQuery:


var names = ["Mike","Matt","Nancy","Mike","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
alert(uniqueNames);// ["Mike","Matt","Nancy","Jenny","Carl"];

Resource:
http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array

Javascript: convert numbers to equal ASCII character

Use String.fromCharCode() method:

var myInt = 65;
var myString = String.fromCharCode(myInt); // A

Resource:
http://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript

Javascript: zerofill function

function zeroFill( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}

Resource:

Saturday, October 6, 2012

Javascript: calculating logarithm of a number in any base

Given that the javascript log() method returns the natural logarithm of the given number. You have to use the logarithms property using the natural logarithms. For example to calculate the log of x with 10 base or 2 base:


 So,


function log(val, x) {
  return Math.log(val) / Math.log(X);
}

where x is the base, and val is the number you want to calculate the logarithm.

Resources:
http://www.w3schools.com/jsref/jsref_log.asp
http://stackoverflow.com/questions/3019278/any-way-to-specify-the-base-of-math-log-in-javascript

Javascript: getting selected item


Html:

<select id="estadosiniciales">
                    <option value ="sydney">Sydney</option>
                    <option value ="melbourne">Melbourne</option>
                    <option value ="cromwell" selected>Cromwell</option>
                    <option value ="queenstown">Queenstown</option>
</select>

Javascript:


var selectIni = document.getElementById("estadosiniciales");      
alert(selectIni.options[selectIni.selectedIndex].text);


Resources:
http://www.java2s.com/Tutorial/JavaScript/0200__Form/Findtheselectedoption.htm

Javascript: adding options to select dynamically

Your html:


<select id="estadosiniciales">
                    <option value ="sydney">Sydney</option>
                    <option value ="melbourne">Melbourne</option>
                    <option value ="cromwell" selected>Cromwell</option>
                    <option value ="queenstown">Queenstown</option>
</select>

Your Javascript:


var newOption = new Option("newStateName","newStateName");
var selectIni = $("#estadosiniciales"); // using Jquery
selectIni.append(newOption)


Resources:
http://www.devguru.com/technologies/ecmascript/quickref/option.html
http://stackoverflow.com/questions/4647863/trouble-dynamically-adding-options-to-select

Wednesday, October 3, 2012

Eclipse: Svn error : RA layer request failed

If you get this error:

RA layer request failed
svn: Commit failed (details follow):
svn: PROPFIND request failed on '/repo/path/!svn/vcc/default'
svn: PROPFIND of '/repo/path/!svn/vcc/default': Could not read status line: connection was closed by server. (http://example.com)

Switch from JavaHL(JNI) to SVNKit(Pure Java) in Eclipse:

  1. in eclipse go to Help –> Install New Software…
  2. Work with: –> choose the community.polarion.com update site
  3. expand Subversive SVN Connectors
  4. choose the SVNKit version corresponding with your version of subversion
  5. click Next, and then follow the instructions to complete installation
  6. Window –> Preferences –> expand "Team" –> select "SVN" –> select the "SVN Connector" tab –> change the SVN Connector to SVNKit –> OK


Resource:
http://languor.us/eclipse-subversion-ra-layer-request-failed-could-not-read-status-line-errors

PHP: REST APl Sample

Here is a simple and great example of a REST API using PHP

http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/

Windows 7 : Enable Telnet Client

When you try yo execute telnet command:


C:\Users\John>telnet localhost 80

You get:

'telnet' is not recognized as an internal or external command,
operable program or batch file.

Do this:


  1. Start
  2. Control Panel
  3. Programs And Features
  4. Turn Windows features on or off
  5. Check Telnet Client
  6. Click 'OK' button

After that you can start Telnet via Command Prompt.

Resource:
http://www.fettesps.com/windows-7-enable-telnet/

Tuesday, August 28, 2012

Linux: Process Backgound/Foreground

To send a currently running process to background press: Ctrl+Z

~$ sudo unzip Acappella_METRO.zip
Archive:  Acappella_METRO.zip
   creating: Acappella_METRO/
  inflating: Acappella_METRO/.project
  inflating: Acappella_METRO/.pydevproject
   creating: Acappella_METRO/.settings/
  inflating: Acappella_METRO/.settings/org.eclipse.core.resources.prefs
   creating: Acappella_METRO/birt-runtime-2_2_2/
  inflating: Acappella_METRO/birt-runtime-2_2_2/about.html
   creating: Acappella_METRO/birt-runtime-2_2_2/about_files/
   creating: Acappella_METRO/birt-runtime-2_2_2/about_files/CVS/
 extracting: Acappella_METRO/birt-runtime-2_2_2/about_files/CVS/Entries
 extracting: Acappella_METRO/birt-runtime-2_2_2/about_files/CVS/Repository
 extracting: Acappella_METRO/birt-runtime-2_2_2/about_files/CVS/Root
  inflating: Acappella_METRO/birt-runtime-2_2_2/about_files/LICENSE.txt
  inflating: Acappella_METRO/birt-runtime-2_2_2/birt.war  ^Z
[1]+  Stopped                 sudo unzip Acappella_METRO.zip

To bring back the process to foreground type: fg 1

inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/mapper.py
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/mapper.pyc
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/properties.py
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/properties.pyc
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/query.py
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/query.pyc
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/scoping.py
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/scoping.pyc
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/session.py
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/session.pyc
  inflating: Acappella_METRO/thirdparty/sqlalchemy/orm/shard.py

Wednesday, August 22, 2012

Friday, August 10, 2012

Python: Split a string into array with each character

use list() mehod:


numbers = "342"
lst = list(numbers)
print lst // ['3','4','2']

Reference:
http://ubuntuforums.org/showthread.php?t=541931

Python: iterate for loop backwards

use reversed() method:


>>> array=[0,10,20,40]
>>> for i in reversed(array):
...     print i

reference:
http://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python

Thursday, August 9, 2012

Windows 7: You need to format the disk in drive before you can use it

If you get this error:

"You need to format the disk <DriveLetter> in drive before you can use it"


Just follow the followoing steps :

1. Go to start button on windows.
2. Type "cmd"  and right click on "cmd" search result icon and click "Run as Administrator"
3. C:\Windows\system32>
4. Now type :     chkdsk <Your hard disk letter>: /f

For e.g If my hard disk is named "f" then just type ----------   chkdsk f: /f

Try it out...I guess it will work.

Reference:
http://answers.microsoft.com/en-us/windows/forum/windows_vista-system/you-need-to-format-the-disk-in-drive-j-before-you/4e153784-3217-4425-9c39-48030af82a13

Monday, August 6, 2012

Toad For Windows: Installation and Configuration

Her is a great article with all the steps to install Toad For Windows

Here is the link:
http://jorgeehumir.wordpress.com/2011/05/15/instalacion-y-configuracion-de-toad-for-oracle-10-5/

Ps: the instant client url is here http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html, you have to install the windows 32 bits version, because there are some issues with the Instant Client 64Bits version: "Cannot load OCI DLL: " http://toadfororacle.com/thread.jspa?threadID=24227

Tuesday, July 31, 2012

Microsoft Word 2007: Automatic content table

Go to References tab > Content Table > insert content table.
 PD: you have to handle the styles to be able to generate automatic content table

Here is a video tutorial about that:
http://www.youtube.com/watch?v=8sMzWVGiBQ4

Monday, July 30, 2012

Python: split string by given separator

use .split() method:


myString = "1-2-3-4-5-6-7-8"
mySplittedStringArray = myString.split('-')
print mySplittedStringArray # ['1', '2', '3', '4', '5', '6', '7', '8']


Resource:
http://www.tutorialspoint.com/python/string_split.htm
http://jolthgs.wordpress.com/2012/02/12/metodos-join-y-split-en-python/

MSSQL 2008 : Cannot open database requested by the login. The login failed

I got this error:

sqlalchemy.exc.ProgrammingError: (ProgrammingError) ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "ICBF_GDOC_TESTS" requested by the login. The login failed. (4060) (SQLDriverConnect); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "ICBF_GDOC_TESTS" requested by the login. The login failed. (4060)') None None.

In my case, the issue was that the database name was wrong , that was all :/

Wednesday, July 25, 2012

PHP: decode HTML special Chars


<?php
$str = "<p>this -&gt; &quot;</p>\n";


echo htmlspecialchars_decode($str); // <p>this -> "</p>


// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES); // <p>this -> &quot;</p>
?>


Reference:
http://php.net/manual/en/function.htmlspecialchars-decode.php

Tuesday, July 24, 2012

Python: Pass a method as a parameter


def method1():
    return 'hello world'


def method2(methodToRun):
    result = methodToRun()
    return result


method2(method1)


Reference:
http://stackoverflow.com/questions/706721/how-do-i-pass-a-method-as-a-parameter-in-python

Python: weird SyntaxError: invalid syntax

The code was apparently normal:

def myFunctionTestOK():
   return "hi there ok"

def myFunctionTestFail():
   return "hi there fail"

and the error was:

Traceback (most recent call last):  
  File "C:\mytest.py", line 5
    return "hi there fail"
                          ^
SyntaxError: invalid syntax

I was using the Pydev Eclipse Plugin. After a lot of time trying to identify the error I decide to open the file using Notepad ++ http://notepad-plus-plus.org/

clicking in the 'show all characters' button:


I found out that there was missing a (LF) just after the line return "hi there fail":




so I put the cursor just after "hi there fail" and pressed enter:




And finally deleted the line with the single (CR):




Now everything works smoothly.

Python: UnicodeEncodeError: 'ascii' codec can't encode character in position : ordinal not in range(128)

If you get this error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Use the .encode() method instead of using str():


a = u'bats\u00E0'
print a # batsà
print str(a) # UnicodeEncodeError: 'ascii' codec can't encode ...
print a.encode('utf-8') # batsà


Reference:
http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20

Monday, July 23, 2012

Python: try except generic exception

   try:
       myInt = int ("100000A") # throws exception
       #myInt = int ("100000") # doesn't throw exception
       print "myInt:" , myInt
   except Exception, e:
       print "My Error: " , str(e)

Resource:
http://www.daniweb.com/software-development/python/threads/169976/python-try...except-printing-exception

Linux: change another's user password from root

To change the password for the user 'roger' (only you are logged in as root)...

passwd roger
Enter existing password (can be either roger's password or root's password)
Enter new password
Enter new password again (to validate)


Resource:
http://www.ahinc.com/linux101/users.htm

Simple WYSIWYG HTML Editor Sample

the file structure of the project is:

./project
./project/myWYSIWYGTest.html --- here is the source code of the example
./project/ckeditor --source code of the ckeditor lib, download where http://ckeditor.com/download

the code of the myWYSIWYGTest html page is:

<html>
    <head>
        <script type="text/javascript" src="./ckeditor/ckeditor.js">
        </script>
    </head>
    <body>
        <textarea class="ckeditor" name="editor1"></textarea>
    </body>
</html>

Reference:
http://nightly.ckeditor.com/7582/_samples/replacebyclass.html

Linux: cp command


cp -r /home/hope/files/* /home/hope/backup

Copies all the files, directories, and subdirectories in the files directory into the backup directory.

Example:

cp -r /home/john/Desktop/shared_folder/* /media/DISK/disk1


Reference:
http://www.computerhope.com/unix/ucp.htm

Thursday, July 19, 2012

SQL Server: update column with sequential value

I have a database table that has a lot of data already in the table and I need to add a new column to this table to include a new sequential number.  In addition to adding the column I also need to populate the existing records with an incremental counter.


So I can do this by doing the following:


// adds new columns
ALTER TABLE [dbo].[d_expedientes] ADD [type_expediente] [int] default 0;


// set the value of the new column to 1,2,3,4,5,...

DECLARE @type_expediente INT 
SET @type_expediente = 0 
UPDATE d_expedientes
SET @type_expediente = type_expediente = @type_expediente + 1 


Reference:
http://www.mssqltips.com/sqlservertip/1467/populate-a-sql-server-column-with-a-sequential-number-not-using-an-identity/

Wednesday, July 18, 2012

Oracle: condition CASE in select sentence


SELECT 
TRANSACCION.num_tarjeta
,TRANSACCION.fecha_hora_tran
, TRANSACCION.monto_1 as monto
,  CASE 
WHEN TRANSACCION.ciudad != ' ' 
THEN TRANSACCION.ciudad 
ELSE 'No Disponible' 
END AS ciudad 
, CLASE_TRANSA.DESCRIPCION AS MEDIO
FROM 
TRANSACCION 
left outer join CIUDADES 
ON TRANSACCION.ciudad = CIUDADES.cod_ciud  
left outer join CLASE_TRANSA
ON TRANSACCION.clase = CLASE_TRANSA.CODIGO


Reference:
http://www.adp-gmbh.ch/ora/sql/case_when.html

Saturday, July 14, 2012

Linux: find a file

find <dir_where_you_want_to_search> -name <file_nameyou_want_to_search>:


find /home/john -name 'httpd-xampp.conf'


Note: In ubuntu use sudo at the beginning :
sudo find /home/john -name 'httpd-xampp.conf'


Resource:
http://www.codecoffee.com/tipsforlinux/articles/21.html