Archive for the ‘Linux Shell’ Category

16
dic

Here a unix command line script to count code lines for your project (or something else!).

In this example it counts lines in an Objective-C iOS Application (.h or .m files).

1
2
3
4
$
$find . \( -name '*.h' -o -name '*.m' \) -print -exec cat {} \; | wc -l
  25812
$


Explanation:

find . \( -name ‘*.h’ -o -name ‘*.m’ \) -print

- list all files endings with .H or .M recursively from current folder (.).

-exec cat {} \;

- while it finds files, exec a cat on current file

wc -l

- count lines of current file and sum it to total.

25812 lines of code! Sounds good!

enjoy!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , ,

16
dic

Great idea!
Follow this link: http://appsumo.com/~_z6T and you can win a paid account for Github!
You need only respond to a simple question! :)

Do you know GitHub.com?

git·hub /’ɡɪtˌhʌb/
GitHub is the best way to collaborate with others. Fork, send pull requests and manage all your public and private git repositories.


Github Free Account

Click here http://appsumo.com/~_z6T and Win!

Enjoy!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

24
set

Do you want use google speech api to recognize text from a dictate?

If you want to add in your “test” project, (test project because it’s not a public API), you need to read Chrome Browser source code.

Here chromium url: src.chromium.org/viewvc/chrome/trunk/src/content/browser/speech

Chrome records audio chunks, accepts only a FLAC file, an open source audio codec (free lossless audio codec) file with a sample rate of 16000.0!

After upload to server:

https://www.google.com/speech-api/v1/recognize

and server responds with a json like this:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "status": 0,
    "id": "f3847b5dcu4d657f6667f3pk4sc0a8ca-2",
    "hypotheses": [
    {
        "utterance": "it works",
        "confidence": 0.8012238
    },
    {
        "utterance": "it works"
    }]
}

Now, using ASIFormDataRequest we can send in POST a file to google url waiting for JSON.
Objective-c code:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void) SpeechFromGooglezzz {
  NSURL *url = [NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US"];

  ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  NSString *filePath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.flac"];

  NSData *myData = [NSData dataWithContentsOfFile:filePath];
  [request addPostValue:myData forKey:@"Content"];
  [request addPostValue:@"audio/x-flac; rate=16000" forKey:@"Content-Type"];
  [request startSynchronous];

  NSLog(@"req: %@", [request responseString]);
}

But now is there a big problem… objective-c and iphone don’t recognize FLAC files, you need an intermediate passage to send the correct audio file.

Set up your server with FFMPEG (an audio/video converting/editing tool) and prepare a PHP/JSP/etc. that accept in post an audio file, call a PHP EXEC and launch ffmpeg with flac codec.
Then upload from server to google and return response!

Here code to record and listen audio file from iPhone. Create two buttons and copy/paste code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (IBAction)StartRec:(id)sender {  
  NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithFloat: 16000.0],                 AVSampleRateKey,
                            [NSNumber numberWithInt: kAudioFormatMPEGLayer3],    AVFormatIDKey,
                            [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                            [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                            nil];
 
  NSError *error;
  NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"]];
  recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
 
  if (recorder) {
    [recorder prepareToRecord];
    [recorder record];
  }
  else NSLog(@"%@", [error description]);
}
1
2
3
4
5
6
7
8
9
10
11
12
- (IBAction)PlayAudio:(id)sender {
 NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"];
 
 SystemSoundID soundID;  
 NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
 AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
 AudioServicesPlaySystemSound(soundID);
}

- (IBAction)StopRec:(id)sender {
  if (recorder) [recorder stop];
}

That’s all, enjoy!

…and remember that speech function of google it’s a private API. You can’t use in a commercial app!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , ,

07
apr

Hi all,
a promemoria to MERGE Device + Simulator libraries in a “fat” lib with XCODE.

Usage:

1. Create a static lib project
2. Select the Target
3. right-click and “Add … New Build Phase … New Run Script Build Phase”
4. Copy/paste the script below into the box

After that, customize script as you want!

In your BUILD folder you can see Release-Universal folder that contains merged libs with headers file!




Ref: albertopasca.it

Here the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
### EXECUTED ONLY WITH SIMULATOR->RELEASE->MyTarget

#!/bin/sh

### CONFIG VARS
MY_TARGET="MyTarget"
IS_VALID="FALSE"
SDK_VERSION=$(echo ${SDK_NAME} | grep -o '.\{3\}$')
ALREADYINVOKED="false"
UNIVERSAL_NAME="Release-universal"
BUILD_DEV_PATH=${BUILD_DIR}/${UNIVERSAL_NAME}/tmp-dev/
BUILD_SIM_PATH=${BUILD_DIR}/${UNIVERSAL_NAME}/tmp-sim/

### CONF CHECK
CheckConfig() {
 # YOUR COMPILE RULES
 if [ ${CONFIGURATION} == "Release" ] &&
    [ ${ACTION} == "build" ] &&
    [ ${TARGET_NAME} == ${MY_TARGET} ] &&
    [ ${PLATFORM_NAME} == "iphonesimulator" ]
 then
  IS_VALID="TRUE"
 fi
}

### MKDIRS
CreateFolders() {
 mkdir -p "${SYMROOT}/${UNIVERSAL_NAME}/"
 mkdir -p  ${BUILD_DEV_PATH}
 mkdir -p  ${BUILD_SIM_PATH}
 mkdir -p "${SYMROOT}/${UNIVERSAL_NAME}/include"
}

### MULTIPLE BUILDS
BuildLibs() {
 # BUILD DEVICE
 xcodebuild -configuration "Release" -target "PGLib" -sdk "iphoneos4.3" build RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_DEV_PATH}" BUILD_ROOT="${BUILD_DEV_PATH}"
 # BUILD SIMULATOR
 xcodebuild -configuration "Release" -target "PGLib_Simulator" -sdk "iphonesimulator4.3" build RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_SIM_PATH}" BUILD_ROOT="${BUILD_SIM_PATH}"
}

### MERGE LIBS
FatLibs() {
 LIB_DEV="${BUILD_DEV_PATH}/Release-iphoneos/libPGLib-DEV.a"
 LIB_SIM="${BUILD_SIM_PATH}/Release-iphonesimulator/libPGLib-SIM.a"
 LIB_UNI="${SYMROOT}/${UNIVERSAL_NAME}/libPGLib.a"
 HEADERS="${BUILD_DEV_PATH}/Release-iphoneos/usr/local/include/"

 cp "${HEADERS}"/* "${SYMROOT}/${UNIVERSAL_NAME}/include"

 lipo -create "${LIB_DEV}" "${LIB_SIM}" -output "${LIB_UNI}"
}

### CLEAN WORKING DATA
ClearTemporary() {
 rm -rf "${BUILD_DEV_PATH}"
 rm -rf "${BUILD_SIM_PATH}"
}

#
### MAIN
#
if [ "true" != ${ALREADYINVOKED:-false} ]; then  # SKIP APPLE RECURSION
 CheckConfig
 ALREADYINVOKED="true"

 if [ ${IS_VALID} == "TRUE" ]; then  # DO WORK
  CreateFolders
  BuildLibs
  FatLibs
  ClearTemporary

  echo "Custom script on RELEASE/SIMULATOR/${MY_TARGET} executed!";
 else
  echo "Custom script SKIPPED execution!";
 fi
fi

enjoy coding!!!






Ref: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

30
set

I forget often this string….

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  date +"%Y%m%d" -d "91 days ago"
    [ 20100701 ]

  date -d "91 days ago"
    [ Thu Jul  1 10:40:27 CEST 2010 ]

  date +"%m-%d-%y" -d "91 days ago"
    [ 07-01-10 ]

  date +"%T"
    [ 10:40:59 ]

  #set variable
  NOW=$(date +"%m-%d-%Y")
  echo $NOW

done.

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

08
lug

As a Linux user, you may have to get the following error:

bash: /bin/rm: Argument list too long

There are a lot of methods to resolve this issue, but I use this stupid and simple one:

Here the code (copy, type vi rmany.sh, paste the code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#
# rmany.sh
#  - List or delete a lot of files...
#    ...specially in this folder!
#
# (c)apasca
#
#
#!/bin/bash
#
for X in *.$1
do
$2 "$X";
done
#
# FIRST:
#   chmod +x rmany.sh
#   alias rmany='./rmany.sh'
#
# USAGE:
#   rmany [EXTENSION] [COMMAND]
#

You need to make it executable (chmod +x rmany.sh) and optionally add it as alias (alias rmany=’./rmany.sh’).





If you have created an alias you can type on console simply “rmany txt rm” and press enter!

Your input is rmany [EXTENSION] [COMMAND]

!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , ,

07
giu

Un .sh come promemoria per macchine a 64bit, non si sa mai…

Versione OPTIMIZED:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Clean everything
if test -d optimized; then \
  cd optimized; \
  make distclean; \
  cd ..; \
fi;

# Do autoconf & friends
make -f Makefile.cvs
mkdir optimized
cd optimized

# Configure for debug build
export CXXFLAGS="-O2 -Wno-deprecated -Wall -g0"
../configure

# Build
make


Versione DEBUG:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Clean everything
if test -d debug; then \
  cd debug; \
  make distclean; \
  cd ..; \
fi;

# Do autoconf & friends
make -f Makefile.cvs
mkdir debug
cd debug

# Configure for debug build
export CXXFLAGS="-O0 -Wno-deprecated -g3"
../configure

# Build
make

yep.

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , ,

25
feb

Bene,

abbiamo un file di log da 600Mb con 8.791.937 milioni di righe… in formato access.log.gz fatto in questo modo:

1
2
3
[...]
IP.IP.IPP.IPP - - [14/Sep/2009:00:01:22 +0200] "GET /xml.php/getall?cmd=tile&format=jpeg&x=3777&y=5143&z=16&extra=2&ts=256&q=60&rdr=0&sito=test HTTP/1.1" 200 1713 "http://www.ilmiosito.it/call?v=373" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; GTB6)"
[...]

Cosa ci serve? L’url e i suoi parametri? Ok…

Da shell possiamo usare un ZCAT per leggere il file zippato senza aprirlo e magari fare un redirect con meno righe, giusto per fare dei test:

1
$ zcat /tmp/access.log.gz | grep "&x=" | head -2500 > /tmp/small.log

ora abbiamo un file più piccolo…

1
cut -d\" -f2 /tmp/small.log | cut -d\? -f2 | cut -d\  -f1 > CLEAR.log

ora abbiamo un file contenente solo l’url da parsare! Già meglio vero?


Adesso, con C# mettiamo su un parser senza perderci troppo tempo in shell e carichiamo il file!

Può essere comodo usare le liste, in modo da salvare la coppia:

(valore_che_serve),(quante_volte_si_ripete)

1
      var CityList = new Dictionary<string , int>();

e ovviamente salvare o incrementare i valori trovati:

1
2
3
4
       if ( ! CityList.ContainsKey( VALORE ))
              CityList.Add(VALORE, 1);
        else
              CityList[VALORE] = CityList[VALORE] + 1;

così abbiamo per ogni chiave il suo numero di ripetizioni!

Ma poi? Tutto disordinato?
No, no, mettiamo un pò di ordine, magari salvando un file CSV separato da “;” con i valori ordinati dal più ripetuto al memo ripetuto…

1
2
3
4
5
6
7
8
StreamWriter sw = new StreamWriter(@"Z:\alb\ordine.dat");

foreach (KeyValuePair</string><string , int> item in CityList.OrderByDescending(key => key.Value))
{
        sw.WriteLine(item.Key + ";" + item.Value);
        sw.Flush();
}
sw.close();

Ah, per usare le Dictionary e il metodo OrderBy, sono necessarie queste due librerie:

using System.Collections.Generic;
using System.Linq;


Bene, tutto qui!

Adesso abbiamo un file CSV ordinato, con il nostro valore preferito (IP, la città, un url…) e quante volte viene ripetuto!
Per ogni utilizzo!

enjoy.

[ref -> albertopasca.it]

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , ,

23
lug

Real player usa due file per visualizzare il video in questo formato.
Il file .camv contiene l’xml con le informazioni utili al video e l’altro (rm) contiene l’audio.

real player


Ecco come convertire entrambi, unendoli in un filmato .AVI in linux shell.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash

convert()
{
   echo Analyzing $FOLDER...
   mencoder -audiofile $FOLDER/*.rm $FOLDER/*.camv -ovc lavc -lavcopts vcodec=mpeg4:vpass=1 -oac pcm -o /dev/null
   mencoder -audiofile $FOLDER/*.rm $FOLDER/*.camv -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell:vpass=2 -oac pcm -o $FOLDER.avi
}

LST=`ls -1 .`
for FOLDER in $LST;
do
    convert
done

in realtà può essere fatto anche su Windows.
E’ scaricabile da sourceforge: http://sourceforge.net/projects/mewig/.

[ref -> albertopasca.it]

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , ,

Switch to our mobile site