Category Archives: Android

Posts on Android development

Simple examples of using SVN on Mac OS X

Let’s assume that you need to download some sources using SVN on your Mac from Internet, from some URL.

Creation of new directory
mkdir /Users/user/Documents/TwtAPI

Going to directory
cd /Users/user/Documents/TwtAPI

Example of download command
svn checkout http://svn.cocoasourcecode.com/MGTwitterEngine/

Another example, but it’s depricated because Google Translate is no longer available through API:
1. mkdir /Users/user/Documents/GoogleTranslateAPI
2. cd /Users/user/Documents/GoogleTranslateAPI
3. svn checkout http://objc-google-translate-api.googlecode.com/svn/trunk/ objc-google-translate-api-read-only

Objective C wrap over Microsoft Translator V2 API

We all know, that Google has stopped Google Translate Service for applications and made Google Translate API depricated. So I decided to use Microsoft Bing Translate API for my purposes of online word translation.

I managed to make an objective C wrap over Microsoft Bing Translate API for translation of one word. It is analogous to the wrap for Google Translate API, but it is much simpler because it doesn’t use any JSON or XML parsing.

I just extract a translated word from a string that I get by HTTP GET Method in Obj. C. In the first function I check weather I have an Internet connection setup properly and I start running a background function for translation. I make it in background thread not to freeze user interface.

Then I produce a url and make a request. When I get a contents string, I cut it a little bit to get a translation of word. That’s all.

Please post any comments if this was useful.


#define URL_STRING @"http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=here your own app id&text="

- (IBAction) translateBing:(id)sender
{
SimpVocAppDelegate *appDelegate = (SimpVocAppDelegate *)[[UIApplication sharedApplication] delegate];
// Флаг состояния Translate
appDelegate.translateActive = YES;

// Проверка соединения
if (appDelegate.internetActive == NO){
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Internet Connection problem"
message:@"There is no Internet Connection. Please, type translation yourself or leave blank"
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
// Флаг состояния Translate
appDelegate.translateActive = NO;
return;
}
// Проверка доступности Bing Translate
if (appDelegate.hostActive == NO){
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Translate Service problem"
message:@"Translation Service is not available. Please, type translation yourself or leave blank"
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
// Флаг состояния Translate
appDelegate.translateActive = NO;
return;
}

[self performSelectorInBackground:@selector(performLongTaskInBackground) withObject:nil];
}

- (void) performLongTaskInBackgroundBing
{
// Set up a pool for the background task.
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

SimpVocAppDelegate *appDelegate = (SimpVocAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *tText = wordTextField.text;

if ([tText isEqualToString:@""]==NO){
NSString *translation;
NSString *fromL;
NSString *toL;

fromL = [appDelegate.lang objectForKey:appDelegate.languageFrom];
toL = [appDelegate.lang objectForKey:appDelegate.languageTo];

NSMutableString* urlString = [NSMutableString string];
[urlString appendString: URL_STRING];
[urlString appendString: self.wordTextField.text];
[urlString appendString:@"&from="];
[urlString appendString: fromL];
[urlString appendString:@"&to="];
[urlString appendString: toL];

NSURL* url = [NSURL URLWithString: urlString];
NSURLRequest* request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 60.0];
NSURLResponse* response; NSError* error;
NSData* data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
if (data == nil) {
//NSLog(@"Could not connect to the server: %@ %@", urlString, [error description]);
return nil;
} else {
NSString* contents = [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
//NSLog(@"# %@ %@ %@", fromL, toL, contents);
//return [self translateCharacters: [[[contents JSONValue] objectForKey: @"responseData"] objectForKey: @"translatedText"]];

NSRange match;
match = [contents rangeOfString: @">"];
contents = [contents substringFromIndex: match.location+1];

match = [contents rangeOfString: @"<"]; translation = [contents substringWithRange: NSMakeRange (0, match.location)]; //NSLog(@"%@", contents); translationTextField.text = translation; // Флаг состояния Translate appDelegate.translateActive = NO; } [self performSelectorOnMainThread:@selector(completeLongRunningTask) withObject:nil waitUntilDone:YES]; [pool release]; } }

Here you can get some information about Bing Translate API :

http://www.microsofttranslator.com/dev/
http://msdn.microsoft.com/en-us/library/ff512423.aspx

Регулярные выражения на сложном примере

Я столкнулся с задачей: Надо написать проверку, что перед каждым символом ‘a’ в строке находится нечётное число символов. Например, для строк ‘b’ и ‘ba’ эта проверка должна выдавать true, а для строк ‘a’ и ‘aa’ — false.

Начнем решать эту задачу поэтапно, так как ее решение выглядит следующим образом

Понять его сразу довольно сложно, а некоторые пишут, что смотреть чужие решения по регулярным выражениям и вовсе бессмысленно, так как их не прочитать. Но я хочу развеять этот миф и покажу вам, как прочитать данное решение или как к нему придти за 15 минут.

Итак, начнем. Первое, что нужно сделать – это разобраться с элементарными вещами, а именно:

Подробнее можно прочитать в списке литературы и особенно тут.

Двигаемся дальше. Нам нужно создать шаблон, который будет удовлетворять любому числу любых нечетных букв, находящемуся перед одной буквой а для начала. Для этого можно воспользоваться следующим приемом: создаем шаблон для четного числа букв и добавляем еще одну букву.

Согласно обозначениям сверху, следующая запись означает, что шаблон требует 2 любые буквы, кроме а.

Теперь объединяем эту запись в круглые скобки и ставим после нее звездочку. Это означает, что теперь 2 буквы кроме буквы а могут встречаться любое число раз, включая ноль:

Если мы перед предыдущей записью добавим еще одну букву, не равную а в обязательном порядке, то мы получим в итоге шаблон, который требует либо 1 букву, либо нечетное их число:

Допишем букву а в конце, это означает, что перед а – любое нечетное число букв и сама буква а добавилась:

Список использованных ссылок:

  1. http://www.learn-javascript-tutorial.com/RegularExpressions.cfm
  2. http://www.regular-expressions.info/javascriptexample.html – Инструмент для тестирования выражений
  3. http://www.javascriptkit.com/javatutors/re.shtml
  4. http://www.sql.ru/forum/actualthread.aspx?bid=34&tid=858526
  5. http://www.codeproject.com/KB/dotnet/regextutorial.aspx
  6. – самая полезная для меня статья оказалась

  7. http://msdn.microsoft.com/ru-ru/library/28hw3sce.aspx
  8. http://www.rsdn.ru/article/alg/regular.xml
  9. http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
  10. http://www.intuit.ru/department/ds/discrmath/1/ – немного дискретной математики и потом идет курс по конечным автоматам, полезно почитать

How to copy image from Excel(diagram) to Corel Draw using PDF

At first I tried to simply copy OLE Excel Diagram object to Corel Draw. I needed to make that diagram in eps format for TeX, that’s why I used Corel Draw. But it failed. OLE object was copied the wrong way and there were a lot of problems like this:

I solved this problem in the following way.

  1. Export diagram to pdf file with standarts. The trick is to create pdf file in Excel with special standart. Look at the following pictures:

  2. Then import that pdf file to corel draw so that corel draw will use it’s native elements(lines, text, etc).

[ad#newad]

Solution of problem in Latex Editor (LEd) with Pictures of *.eps type

I like LEd but today I met a problem during PDFLatex compiling of my source with picture of *.eps type. It was telling that “unknown graphics extension: .eps”. Let’s look at it(Click to enlarge):

I was very upset because all my work was done in LEd and I got pretty used to this editor and I didn’t want to change my editor to another, for example WinEDT or other. So I tried to solve this problem. And I found an answer here.

To solve this problem, try the following:

  1. Locate eps file in true directory and try to change it’s name
  2. Compile with LaTeX compilation and then DVI conversion to PDF.

VBScript for automatic opening of programs, files and folders

Here I will explain a simple VBScript that I wrote today to make opening of some programs and folders automatic. This problem occured in my work because I needed to open frequently my postgraduate dissertation and some other TeX files and needed to open some folders and other programs fastly when I need. So let’s look at the script:

Dim objShellApp, WshShell

'проверка на уверенность

Set WshShell = CreateObject ("WScript.Shell")
Set objShellApp = CreateObject ("Shell.Application")

a = WshShell.Popup ("Ты уверен(а), что хочешь запустить все нужные программы? =))",,"Подумай!", 4+32)
If a = 7 Then WScript.Quit

WshShell.CurrentDirectory = "C:\Program Files\LEd"
WshShell.Run "LEd.exe"
WshShell.Run "LEd.exe"
WshShell.Run "LEd.exe"
objShellApp.ToggleDesktop

WshShell.CurrentDirectory = "C:\totalcmd"
WshShell.Run "TOTALCMD.exe"
objShellApp.ToggleDesktop

WshShell.CurrentDirectory = "C:\Documents and Settings\wzbozon\Рабочий стол"
WshShell.Run "ImageSaver.exe"
objShellApp.ToggleDesktop

objShellApp.Open("C:\Documents and Settings\wzbozon\Рабочий стол\TeX Books")

WshShell.CurrentDirectory = "C:\Documents and Settings\wzbozon\Рабочий стол\Alwawee\Приложения Alwawee\TexRef"
WshShell.Run "TexDatabase.xlsx"

WshShell.CurrentDirectory = "C:\Program Files\Google\Chrome\Application"
WshShell.Run "chrome.exe"

WshShell.CurrentDirectory = "c:\Аспирантура\DIPLOM\"
WshShell.Run "final.doc"

objShellApp.ToggleDesktop

First of all I should say, that this is a usual text file, called StartAll.vbs, that is edited in NotePad++. It can be edited on usual Notepad also, but I strongly recommend you to use Notepad++.

Here, at first I create 2 objects, that are used to manipulate the file system in Windows Script Host. Then I ask with a popup window if the user is sure to run this script. I do this, because I don’t need to run script, if user or me just press two times on it, because this script makes a lot of things. Then Led.exe program is opened 3 times from a directory, where it is located and then Desktop is toggled. Then I open Total Commander, ImageSaver.exe and TeX Books folder. The rest is analogous. It is noteworthy that Excel and Word files can be opened directly with Run method.

Tweaking Windows XP to speed up Boot and Shutdown

In this post I will talk about some tweaks to speed up Windows XP Booting and Shutdown process, since sometimes it can become so long that you begin to think about reinstallation. Please, note that it is about Booting and Shutdown only. There are plenty of videos on youtube to speed up Windows XP. For instance, this one. With the following tweaks I remarkably speeded up my own Windows XP booting. May be they can also be used for other versions of Windows. So let’s begin.

  1. Remove programs from Autorun. To do this you can choose two ways. One is to delete some records in Windows registry. And the second, which I recommend, is to just open Start->Run->msconfig->Autorun and press “Switch off all”. Or switch off just some programs except, for example, antivirus.
  2. Remove loading Windows Logo. To do this open the same msconfig and on Boot.ini Tab check the /NOGUIBOOT checkbox. This will remove Windows Logo on start and so speed up Windows booting a bit.
  3. Decrease WaitToKillServiceTimeout. Open registry by Start->Run->regedit. Then open HKEY_LOCAL_Machine -> SYSTEM -> CurrentControlSet -> Control. Right-click on WaitToKillServiceTimeout, press change and change the value to 5000. This is a time that systems waits a service to stop after it asks it to stop while shutting down system. You can read about it here
  4. Decrease Boot.ini timeout by opening msconfig one more time, choosing Boot.ini tab and typing in Timeout textbox value 3 instead of 30 secs. This is time that computer waits user to choose the option of loading. Actually, this tweak is not very useful and almost useless if your computer always loads normally and doesn’t ask for safe mode, etc.
  5. Switch off unneeded Services in msconfig/services.
  6. Decrease startup delay by editing the following registry entry: HKEY_LOCAL_MACHINE -> SYSTEM -> CurrentControlSet -> ContentIndex -> Startup Delay to 40000 in Decimal values. The delay was put into windows years ago, the idea was to give users a lot of time to choose boot options (e.g. press for safe mode) before windows takes over. Here some people say it didn’t help them, but still I tried it myself and recommend you to change this.

Some tweaks do not work. Mind this, for instance, changing prefetcher value to 5 is useless

References:

  1. http://www.youtube.com/watch?v=G6ESlqGhDv0&feature=related
  2. http://www.youtube.com/watch?v=KqxpnemxQeo
  3. http://oreilly.com/windows/archive/how-to-remove-startup-programs.html
  4. http://technet.microsoft.com/en-us/library/cc976045.aspx
  5. http://forums.guru3d.com/showthread.php?t=232228

Solution of Internet Connection Problem After Uninstalling Dr. Web

Today I tried to uninstall Dr. Web antivirus and suddenly recognized that after this my internet connection got lost. I have Windows XP. I tried to figure out what the problem was in for about 4 hours. I read forums, for example, this topic, but it didn’t help. I tried this:

First, export the registry branch
HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ WinSock2
Then
Start-Run (Run)
netsh winsock reset
Ok.

But it also didn’t help. Also I tried to install Dr. Web antivirus again to make my internet start working at least, but I failed. I tried to use special utilities for uninstallation, that some people recommend, but it also didn’t help me.

Then I began to think by my own head and finally I solved the problem. No, I didn’t reinstall Windows. First of all, I recognized, that I had problems in Control Panel/System/devices/network devices. Also I saw that I got lost my Local Network Connection. What I did to solve those problems:

  1. Uninstalled Dr.Web
  2. Deleted all network devices in Control Panel/System/devices/network devices. Unforturnately, I have russian Windows, I hope you will understand what it is.
  3. Made automatic configuration update to get my network devices get installed. And here is the trick: when the network card is installed, the Local Network Connection is automatically set up for all network cards by default. So I got my Local Network Connection installed.
  4. I configured my Internet connection in TCP/IP settings of Local Network Connection (but this depends on your provider)

I hope this will help you.

String manipulation in iPhone applications

These examples of string manipulation in iPhone apps were taken from the Internet and I don’ pretend on the authority rights for them.

  1. Appending string to another string:

    NSString *myString = @"This";
    NSString *test = [myString stringByAppendingString:@" is just a test"];

  2. Method with wide possibilities to format string and concatenate several strings:

    - (NSString*) concatenateString:(NSString*)stringA withString:(NSString*)stringB {
    NSString *finalString = [NSString stringWithFormat:@"%@%@", stringA, stringB]; return finalString; }



    The advantage of this method is that it is simple to put text between the two strings (e.g. Put a “-” replace %@%@ by %@ – %@ and that will put a dash between stringA and stringB

  3. String Length:

    - (int) stringLength:(NSString*)string { return [string length]; //Not sure for east-asian languages, but works fine usually }

  4. Remove text from string:

    - (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input { return [input stringByReplacingOccurrencesOfString:textToRemove withString:@""]; }

  5. Uppercase / Lowercase / Titlecase:

    - (NSString*)uppercase:(NSString*)stringToUppercase { return [stringToUppercase upercaseString]; }

    - (NSString*)lowercase:(NSString*)stringToLowercase { return [stringToUppercase lowercaseString]; }


  6. Find/Replace:

    - (NSString*)findInString:(NSString*)string replaceWithString:(NSString*)stringToReplaceWith { return [input stringByReplacingOccurrencesOfString:string withString:stringToReplaceWith]; }

  7. String comparison Case Sensitive:

    if ([category isEqualToString:@"Some String"])
    {
    doSomething = YES;
    }



    Case Insensitive:

    if (!([category compare:@"Some String" options:NSCaseInsensitiveSearch]))
    {
    doSomething = YES;
    }



References:

  1. http://stackoverflow.com/questions/1778227/string-manipulation-in-objective-c
  2. http://www.techotopia.com/index.php/Working_with_String_Objects_in_Objective-C – The best reference on this topic

How to speed up web page loading

There are some tips and tricks, that I discovered while creating our web page:

  1. It is better not to use cookies, if possible. And better use less Javascript. I used cookies in the following code to save a number of the current image. Then I took this number and tried to load a fresh image when user enters to the cite after a while.
    ————————————————————————————–

    var currentN=0;
    currentN = get_cookie("currentN");
    //alert("Read currentN = " + currentN.toString());
     

    function changecenterimg(img_name)
    {
    var N = getRandomArbitary(1, 4);
    N = Number(currentN) + Number(1);

    while(N == currentN)
    {
    N = getRandomArbitary(1, 4);
    }

    if (N != currentN)
    {
    currentN = N;
    var img_src = 'images/c'+ N.toString() + '.jpg';
    document[img_name].src=img_src;
    }
    set_cookie("currentN", currentN);
    //alert("Set currentN = " + currentN.toString());
    }

    function init()
    {
    //alert("init started");
    changecenterimg('centerimg');
    }

    function set_cookie ( cookie_name, cookie_value )
    {
    document.cookie = "currentN=" + currentN.toString();
    }

    function get_cookie ( cookie_name )
    {
    var cookie_string = document.cookie ;
    if (cookie_string.length != 0) {
    var cookie_value = cookie_string.match (
    '(^|;)[\s]*' +
    cookie_name +
    '=([^;]*)' );
    return decodeURIComponent ( cookie_value[2] ) ;
    }

    ————————————————————————————–

    And I understood after some time, that this code was seriously lowering web page loading. After this I tried to change center image loading process to the following:

    ————————————————————————————–

    function changecenterimg(img_name)
    {
    N = Number(currentN) + Number(1);
    if (N > 4)
    {
    N = 1;
    }
    currentN = N;
    var img_src = 'images/c'+ N.toString() + '.jpg';
    document[img_name].src=img_src;
    }

    ————————————————————————————–

    Less Javascript we have – faster the page loads. Also I removed infinite cycle in generating new random image number. Although this cycle didn’t work more than two times. It’s noteworthy that in Javascript to make a sum of two numbers we should write:

    ————————————————————————————–

    N = Number(currentN) + Number(1);

    ————————————————————————————–

    Because if we write just

    ————————————————————————————–

    N = currentN + 1;

    ————————————————————————————–

    we will get concatenation of strings, so that for example N will become 11 after 1+1.


  2. Images can be optimized to be smaller in size and unfortunately in quality. The following link was very useful for this purpose: http://tools.dynamicdrive.com/imageoptimizer/index.php I managed to make my images more than two times smaller from 24 kbyte to 10 kbyte

  3. Try to avoid reloading whole page and try to reload or change only some elements. For example, I was reloading page to refresh image after user clicks on it:

    ————————————————————————————–
    <div id="center-column">  

    <a href="index.html">

    <img src="#" alt="Image" width="350" height="250" />

    </a>

    </div>

    ————————————————————————————–

    I changed this to the following to reload only one image:

    ————————————————————————————–
    <div id="center-column">

    <a href="javascript:changecenterimg('centerimg');">

    <img name="centerimg" src="#" alt="Image" width="350" height="250">

    </a>

    </div>
    ————————————————————————————–