вторник, 30 ноября 2010 г.

Что такое дедлок? Что такое мьютекс? Объяснение на пальцах.

http://software.intel.com/ru-ru/articles/61852/

Как разобрать XML в Python? / How to parse XML with Python?

from xml.dom import minidom                                    
xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml')
print xmldoc.toxml()
childnodes = xmldoc.childNodes
for childnode in childnodes:
  name = one_child.nodeName
  if name == "id":
    id = childnode.nodeValue

Как установить Sun JDK в Ubuntu Linux? / How to install Sun JDK in Ubuntu Linux?


$sudo nano /etc/apt/sources.list
добавьте в конец / add to end:
deb http://archive.canonical.com/ubuntu lucid partner
deb-src http://archive.canonical.com/ubuntu lucid partner
$sudo apt-get update
$sudo apt-get install sun-java6-jre sun-java-jdk sun-java6-plugin sun-java6-fonts

Как просто и быстро установить lamp-сервер + tomcat6 в Ubuntu Linux? / How to install LAMP server quickly and simple in Ubuntu Linux?


$sudo apt-get install lamp-server^
$sudo apt-get install tomcat6

Как создать статический метод в классе Python? / How to create static method in Python class?

class SomeClass:
  def some_method(somekey):
    #...
  some_method = Callable(some_method)

#now works
SomeClass.some_method(some_key)

Как использовать memcache в AppEngine с Python? / How to use memcache in AppEngine with Python?

class AppEngineCache:
  lifetime = 3600 #in seconds, 1 hour


  def get_data(key):
    data = memcache.get(key)
    if data is not None:
      return data
    else:
      data = self.query_for_data()
      memcache.add(key, data, 60) #key, value, time in seconds
      #or set multiple values:
      memcache.set_multi({ "USA_98105": "raining","USA_94105": "foggy","USA_94043":    
          "sunny"
          },key_prefix="weather_", time=3600)
    return data

Как отправить POST-запрос в Python? / How to send POST request with Python?


#with httplib
import httplib
def printText(txt):
    lines = txt.split('\n')
    for line in lines:
        print line.strip()

httpServ = httplib.HTTPConnection("127.0.0.1"80)
httpServ.connect()

quote = "test"
httpServ.request('POST', '/cgi_form.cgi', 'name=Brad&quote=%s' % quote)

response = httpServ.getresponse()
if response.status == httplib.OK:
    print "Output from CGI request"
    printText (response.read())

httpServ.close()

Как отправить GET-запрос в Python? / How to send GET-request with Python?


#with httplib
import httplib  


def printText(txt):     
  lines = txt.split('\n')     
  for line in lines:         
    print line.strip()  


httpServ = httplib.HTTPConnection("127.0.0.1", 80) 
httpServ.connect()  
httpServ.request('GET', "/test.html")  
response = httpServ.getresponse() 
if response.status == httplib.OK:     
  print "Output from HTML request"     
  printText (response.read())  
  
httpServ.request('GET', '/cgi_form.cgi?name=Brad&quote=Testing.')  
response = httpServ.getresponse() 
if response.status == httplib.OK:     
        print "Output from CGI request"     
        printText (response.read())  
httpServ.close()

Как прочитать контент веб-страницы на Python? / How to read web content with Python?


#with urllib2
import urllib2
response = urllib2.urlopen(url)
content = response.read()
print content

Как настроить журналирование с помощью Log4j в Java?

В pom.xml:
 

log4j
    log4j
    1.2.15


// Import log4j classes.
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class MyApp {
    // Define a static logger variable so that it references the
    // Logger instance named "MyApp".
    static Logger logger = Logger.getLogger(MyApp.class);

    public static void main(String[] args) {

        // Set up a simple configuration that logs on the console.
        BasicConfigurator.configure();

        logger.info("Entering application.");
        Bar bar = new Bar();
        bar.doIt();
        logger.info("Exiting application.");
    }
}

Как отправить POST-запрос через HTTPS в Java?


try { 
     System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 
    URL url = new URL("https://example.com"); 
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setDoInput(true); 
    connection.setDoOutput(true);
    String cookieHeader = connection.getHeaderField("set-cookie"); 
    if(cookieHeader != null) { 
    int index = cookieHeader.indexOf(";"); 
    if(index >= 0) 
    cuki = cookieHeader.substring(0, index); 
    connection.setRequestProperty("Cookie", cuki); 
}
 
    connection.setRequestMethod("POST"); 
    connection.setFollowRedirects(true); 

String query = "user=" + URLEncoder.encode("gennad.zlobin@gmail.com"); 
query += "&"; 
query += "password=" + URLEncoder.encode("password"); 

//connection.setRequestProperty("Accept-Language","ru"); 
//connection.setRequestProperty("Accept", "application/cfm, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, //*/*"); 
//connection.setRequestProperty("Accept-Encoding","gzip"); 

connection.setRequestProperty("Content-length",String.valueOf (query.length())); 
connection.setRequestProperty("Content-Type","application/x-www- form-urlencoded"); 
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)"); 

// open up the output stream of the connection 
DataOutputStream output = new DataOutputStream( connection.getOutputStream() ); 

// write out the data 
int queryLength = query.length(); 
output.writeBytes( query ); 
output.close();

System.out.println("Resp Code:"+connection.getResponseCode()); 
System.out.println("Resp Message:"+ connection.getResponseMessage()); 
// get ready to read the response from the cgi script 
DataInputStream input = new DataInputStream( connection.getInputStream() ); 

// read in each character until end-of-stream is detected 
for( int c = input.read(); c != -1; c = input.read() ) 
 System.out.print( (char)c ); 
input.close(); 
} 
catch(Exception e){ 
    System.out.println( e ); 
    e.printStackTrace(); 
} 

Как отправить GET-запрос в Java?



public String sendGetRequest(String url, String requestParams)
{
    String result = null;
    if (endpoint.startsWith("http://")) {
        // Send a GET request to the servlet
        try {
            // Construct data
            StringBuffer data = new StringBuffer();
            // Send data
            String urlStr = endpoint;
            if (requestParameters != null && requestParameters.length () > 0) {
                urlStr += "?" + requestParameters;
            }
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection ();
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
            result = sb.toString(); 
    } 
    catch (Exception e) {
        e.printStackTrace();
    }
}
return result;
}

Как создать xml в Java?


DocumentBuilderFactory documentBuilderFactory = 
     DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = 
     documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();    
Element rootElement = document.createElement("rootelmt");
document.appendChild(rootElement);
Element eCmd = document.createElement("seclevelelmt");
eCmd.appendChild(document.createTextNode(cmd));
rootElement.appendChild(eCmd);    
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
java.io.StringWriter os = new java.io.StringWriter();
javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
transformer.transform(source,result);        
System.out.println(os.toString());

Как отправить POST-запрос в Java?


 String data = URLEncoder.encode("mydata", "UTF-8") + "=" + URLEncoder.encode("mydatavalue", "UTF-8");
data += "&" + URLEncoder.encode("mydata2", "UTF-8") + "=" + URLEncoder.encode("mydatavalue2", "UTF-8");
    try {        
         // Send the request
     URL url = new URL("http://example.com");
         URLConnection conn = url.openConnection();
         conn.setDoOutput(true);
         OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
         //write parameters
         writer.write(data);
         writer.flush();
         // Get the response
         StringBuffer answer = new StringBuffer();
         BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line;
         while ((line = reader.readLine()) != null) {
             answer.append(line);
         }
         writer.close();
         reader.close();
    }
    catch (Exception e) {
        //handle exception
    }

Как перевести из Windows Cp1251 в UTF-8 в Java


String utf8String= new String(cp1251String.getBytes("Cp1251"), "UTF-8");

четверг, 25 ноября 2010 г.

Как просмотреть структуру SQLite базы данных?

Для этого есть специальная программа, называемая sqlitebrowser.
В принципе, умеет почти все, что необходимо для работы с БД для тех, кто привык пользоваться phpmyadmin для MySQL.

Java classes to UML diagrams. ObjectAid

Some time ago I found a cool tool for Eclipse, ObjectAid.
It can build UML class diagram from your source code.
After installing through Eclipse's "install new software" you can create a new ObjectAid's file and just drag and drop your Eclipse classes on this diagram.
After that the program computes relationship, inheritance and so on.
Very useful for sorting out foreign code.
There also sequence diagram screenshots but it is not released yet.
Well, looking forward for this very useful feature!
BTW, it works with Eclipse 3.6 Helios too.

вторник, 23 ноября 2010 г.

How to fix Django's "model ‘MyModel’ is already registered" error?

To fix this, you need to place the admin.site.register line in a separate file called admin.py. This file should exists at the same level as models.py. This will ensure that admin class for a model is registered only once.

How to hide *.pyc files in PyDev Eclipse

1. click on the package explorer -> ctrl+F10
2. click filters
3. enable checkbox Name filter patternss
4. enter there *.pyc

How to set up Eclipse to work with Github?

Firstly you need to install msysgit, after installing you need to open Git Bash and enter there these commands:

$ git config --global user.name "Gennadiy Zlobin" (your name)
$ git config --global user.email gennad.zlobin@gmail.com (your email)
$ ssh-keygen -C "gennad.zlobin@gmail.com" -t rsa (your email)

Now your generated keys are in C:\Users\username\.ssh (in Windows 7).
Next you load the content of your public key to your project on Github
In Eclipse open Window->Preferences->General->Network->SSH2 and set your ~/.ssh as SSH Home
After that go to Key Management tab and Load existing Key - set here your private key in ~/.ssh
After that you can push your project to Github (I used ssh protocol)

Передача аргумента по ссылке в Java. Передача объекта

Пример передачи аргумента объекта в метод Java:

public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Austin");
changeName(dog);
System.out.println("New dog's name outside changeName method: "+dog.getName()); //Mike
}

public static void changeName(Dog dog) {
System.out.println("Old dog's name in method: "+dog.getName()); //Austin
dog.setName("Mike");
System.out.println("New dog's name in changeName method: "+dog.getName()); //Mile
}
}

class Dog {
private String name;

public Dog(String name) {
this.name=name;
}

public String getName() {
return name;
}

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

По значению или ссылке передаются параметры в Java?

в Java методах все аргументы передаются по значению. В случае, когда аргумент – примитивный тип, передача по значению означает то, что метод не может изменить оригинальное значение. Когда же аргумент – ссылка на объект, создается локальная копия ссылки, которая указывает на тот же самый объект, при изменении которой оригинальное состояние объекта остается неизменным. (прим. редактора: верно - ВСЕ ПАРАМЕТРЫ В JAVA ПЕРЕДАЮТСЯ ПО ЗНАЧЕНИЮ. Если параметр — ссылка на объект, то ЗНАЧЕНИЕМ является ЗНАЧЕНИЕ самой ссылки, а не значение разнообразных полей в объекте, коих может быть великое множество, как по количеству, так и по разнообразию типов).

суббота, 20 ноября 2010 г.

Lifehack

Недавно благодаря одному человеку, я узнал, что такое GTD (Getting things done) - подход, который позволяет планировать дела.
Если честно, я сам как-то старался их планировать с помощью Google Tasks и Google calendar без всяких теоретических подходов к этому делу. А тут заинтересовался, скачал на Android приложение Astrid Tasks, буду придерживаться подхода в той или иной степени.

А ещё я относительно недавноузнал, что такое Lifehack.
В соответствии с Википедией, это
набор методик и приёмов «взлома» окружающей жизни для упрощения достижения поставленных целей при помощи разных полезных советов и хитрых трюков.
Это тоже очень похоже на меня, я всегда думал, как оптимизировать жизнь, чтобы сделать ее максимально эффективной (например, как переходить улицу, чтобы пройти ее максимально быстро или как водить автомобиль, наименее часто попадая в пробки и наиболее быстро добираясь из одной точки в другую, не превышая скорости.)
Вобщем, будем популяризировать это направление)

Возвращение)

Давненько я не писал в свой блог.
Связано это было с тем, что во-первых, банально не было времени, во-вторых, я иногда пишу в Twitter,а это отнимает тоже много времени, а во-вторых, я хотел сделать свой блог на AppEngine.
А с учетом того, что времени мало, этот процесс может растянуться на неопределенный промежуток времени.
Буду писать сюда.
Недавно занялся собственной продуктивностью, я считаю, что это очень важно.
Установил программу RescueTime. Пока только бесплатная версия, может как-нибудь куплю платную. Пока что из полезных функций обнаружил составлениее коэффицинта продуктивности - программа смотрит, чем вы занимаетесь на компе и если скажем сидите в контакте, или в фейсбуке, у вас большой минус к продуктивности, а если работаете в какой-нибуь полезной программе или сидит на каком-нибудь полезном сайте типа stackoverflow, это плюс. Рейтинг можно сравнивать с общим средним рейтингом других и тогда будешь знать, стоит ли снова заходить в контакт или нет :) Было бы здорово, если бы рейтинг выводился на экране поверх всех окон.