Tuesday, January 28, 2014

Passing arguments to "int main()" function in c language

This program waits for one argument.
If none was write it will output "what do you want from me?"
If pass argument with name "open" then it will do something in this case print "This is top secret information"
#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(int argc, string argv[]) 
{
if (argc<2)
{
printf("what do you want from me?\n");
return 1;
} else {

if (strcmp(argv[1],"open")==0) {
printf("This is top secret information\n");
}
}

}
argc will initialize argument counter.
zero argument argv[0] will always be the name of application.
To pass the arguments with spaces like "how you doin" you need to use double quotes.
Otherwise argv[1]="how", argv[2]="you", argv[3]="doin".

Convert lower case letters to upper in c language

This is how to do without knowing the ascii table
#include <stdio.h>
#include <string.h>
#include <cs50.h>

int main(void)
{
string s = GetString();
string sm = "abcdefghijklmnopqrstuvwxyz";
string bi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int cycle=0;
for (int i = 0, n = strlen(s); i < n; i++)
    {
        for (int n=0,a=strlen(sm)+1; n < a ;n++) 
            {
            cycle++;
                if (s[i] == sm[n])
                    {
                        printf("%c", bi[n]);
                        break;
                    } 
                else
                    { 
                        if (n+1 == a) printf("%c", s[i]);
                    }
            }
    }
printf("\n");
printf("cycles taken: %i\n",cycle);
}
Using ASCII map character set we can figure out to convert to upper case by distracting 32.
This is possible cause c language understand single character as numbers from 0-255.
So 'B'+32='b', 'C'+33='d', 'a'-64='!' and so on..
image from http://www.catonmat.net/blog/ascii-cheat-sheet/

Here goes the second program
#include <stdio.h>
#include <string.h>
#include <cs50.h>

int main(void)
{
string s = GetString();
int cycle=0;
for (int i = 0, n = strlen(s); i < n; i++)
    {
        cycle++;
        if (s[i] >= 'a' && s[i] <= 'z')
            {
            printf("%c", s[i] - 32);
            }
        else
            {
            printf("%c", s[i]);
            }
    }
printf("\n");
printf("cycles taken: %i\n",cycle);
}
I have added the cycle counter to booth programs.
For example if i input
This is brilliant application! Well how YOU doin'?
The first program will count 799 cycles but the second program will count only 50 cycles. It must be the same as the string length.

Related:
https://www.youtube.com/watch?v=i42GUZbKTPU
http://cs50.tv/2013/fall/#l=psets/

Monday, January 27, 2014

Bad and good "for" loop in c, strlen

This will work but it takes more CPU to proceed cause the strlen(s) will be calculated i times
#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void) {
string s = GetString();

//check if you not input dumb string
if (s != NULL)
{
    for (int i=0;i <strlen(s); i++)
    {
    printf("%c\n", s[i]);
    }
}
}
This is better. Note that there is also , NOT ; inside "for" loop
#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void) {
string s = GetString();

//check if you not input dumb string
if (s != NULL)
{

    for (int i=0,l=strlen(s);i<l; i++)
    {
    printf("%c\n", s[i]);
    }
}
}
Related: https://www.youtube.com/watch?v=i42GUZbKTPU
http://cs50.tv/2013/fall/#l=psets/

Procedure and function in c

Procedure do not return value
#include <cs50.h>
#include <stdio.h>

void GetPositiveInt()
{
int i;
    do {
        printf("Give me some positive int: ");
        i = GetInt();
        if (i<0) printf("wtf? Give me some positive!\n");
        if (i==0) printf("what the cake? You act like a zero!\n");
        if (i>0) printf("You are positive!\n");
    } while (i<=0);
}    

int main(void)
{

GetPositiveInt();

}
Function return value
#include <cs50.h>
#include <stdio.h>

int GetPositiveInt()
{
int i;
    do {
        printf("Give me some positive int: ");
        i = GetInt();
        if (i<0) printf("wtf? Give me some positive!\n");
        if (i==0) printf("what the cake? You act like a zero!\n");
        if (i>0) printf("You are positive!\n");
    } while (i<=0);
    return i;
}    

int main(void)
{

int x = GetPositiveInt(void);
printf("You input %i\n",x);

}
Related: https://www.youtube.com/watch?v=i42GUZbKTPU
http://cs50.tv/2013/fall/#l=psets/

Sunday, January 26, 2014

Declare variable inside a loop

This program is wrong and impossible to compile cause while (n <= 0) do not understands n cause it is declared inside the loop.
#include <stdio.h>
#include <cs50.h>

int main(void)
{
    do
    {
    printf("Give me some positive int: ");
    int n = GetInt();
    } while (n <= 0);
    
    printf("Thanks for the candy!\n");
    
}
When you declare variable inside a { and } it only exist in that scope. After the scope ends it has been removed from memory.

This is good
#include <stdio.h>
#include <cs50.h>

int main(void)
{
int n;
    do
    {
    printf("Give me some positive int: ");
    n = GetInt();
    } while (n <= 0);
    
    printf("Thanks for the candy!\n");
    
}
Source:
https://www.youtube.com/watch?v=yMAvmUyrwlc

Related:
http://cs50.tv/2013/fall/#lectures

Compare two strings in c

I create a program for input team names.
There is future to net let you create empty string. Do not let you input string with length 0.
I use an array to store the team values.

The problem is than c do not understand two equivalent strings
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define number 4

int main(void) {

int flag;
string team[number];

for (int i=0;i<number;i++)
    {
    
    //check for repeated team.
    //set flag to zerro
    do {
    flag=0;
    
        //do not leave empty string
        do
            {
                printf("Whats the %i name: ",i+1);
                team[i]=GetString();
            } while ( strlen(team[i]) < 1);
           
           //check if new team name is not alreay taken.
           //If name exis then set flat to 1 and stop checking for remaining team titles
           for (int f=0;f<i;f++) {
           if (team[f]==team[i]) flag=1;
           printf("f=%i, i=%i, flag=%i, team[f]=%s, team[i]=%s\n",f,i,flag, team[f],team[i]);
           if (flag == 1) break;
           } 
            
           } while (flag==1);
            
    }

    //set random winner!
    srand(time(NULL));
    int r=rand() % number;
    printf("The winner is %s\n",team[r]);
}
The solution is to use string define string using char* and use string compare function strcmp(a,b).
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define number 4

int main(void) {

int flag;
string team[number];

for (int i=0;i<number;i++)
    {
    
    //check for repeated team.
    //set flag to zerro
    do {
    flag=0;
    
        //do not leave empty string
        do
            {
                printf("Whats the %i name: ",i+1);
                team[i]=GetString();
            } while ( strlen(team[i]) < 1);
           
           //check if new team name is not alreay taken.
           //If name exis then set flat to 1 and stop checking for remaining team titles
           for (int f=0;f<i;f++) {
           char* a=team[f];
           char* b=team[i];
           if (strcmp(a,b) == 0) flag=1;
           printf("f=%i, i=%i, flag=%i, team[f]=%s, team[i]=%s\n",f,i,flag, team[f],team[i]);
           if (flag == 1) break;
           } 
            
           } while (flag==1);
            
    }

    //set random winner!
    srand(time(NULL));
    int r=rand() % number;
    printf("The winner is %s\n",team[r]);
}
Related:
https://d2o9nyf4hwsci4.cloudfront.net/2011/fall/lectures/4/src4.pdf
http://cs50.tv/2013/fall/#l=psets/

Saturday, January 25, 2014

More comfortable, linux shell

These are notes from
http://www.youtube.com/watch?v=EXSijgdztCg

~ - my home directory
. - current directory
.. - up one directory
./ - launch the executable

cd - change directory
cd same as cd ~ - go to your home directory
cd . - change directory to current directory. useless
cd .. - go back one directory.
cd - - brings you to the last directory where you have been one step back

ls - list the files
ls -l - full list
ls -a - list files including hidden ones
ls -la - full column list with all files including hidden files.

popular command line editors like wim, emacs, nano

IDE - integrated development environment

Use tab to complete.

clear - clear the screen. Also can clear the screen with ctrl+l.

ctrl+k also clear the screen but you are not able to scroll up the window.

drwxr-xr-x - permissions

man ls - go to ls manual page
man printf - go to printf manual page
man 3 printf - go to c version of printf

Search in manual page with / and type the search keyword.

mkdir - make directory
mkdir i am - create one directory with name "i" and create second directory with name "am"

mkdir "i am" - create one directory with name "i am"

rm means remove

touch a - crate an empty file with name "a"

try to create a file, the a directory with name "a". This is impossible cause directories in linux systems also is files. only directory will be created
mkdir a
touch a
This is the same. Only file will be created.
touch a
mkdir a
This will create file "a" and directory "A".
touch a
mkdir A
rm a - remove "a" file in current directory with user prompt

rm -f b - remove file "b" without user prompt
rm -rf yeah same as rm -fr - remove directory yeah and all files and sub-directories what is inside. If some files can not be deleted then skip that files, but continues deleting last ones
rm -rf / same as rm -fr / - destroys all linux system in 1 second or less
. / is the root of all files and folders and -rf means delete all directories and files what is inside.

rm -rf ~ delete all files in your home directory
rm -rf ~/ logs the same as rm -rf ~ logs - delete all files in your home directory and try to remove sub-directory "logs" in directory where you currently standing
rm -rf * - remove all files and folders in directory where you currently standing
dr-xr-x--- the last three dashes at ls -l output for directory means "do not let any other users access this files".

mv a b - rename "a" file/directory to "b"
mv a . - move "a" file to current directory. useless.
mv a .. - move "a" file up one directory
mv a A - rename "a" file/directory to "A"
cp alfa beta - copy file "alfa" to "beta"
cp -r alfa alfa-backup - if want to copy directory use -r
history - see all history of typed commands.

echo "hi" - echo hi

> - output to a file
< - get the text from the file and pend to the program

| - pipe to map more commands

grep - purpose is search over text and looking for specified text or text pattern

history | grep "touch"

grep -r "fish" * - look for text "fish" in all files in sub-directories. finaly it reports the path/to/the/file together with all line that contains the "fish".
Basic source:
http://cs50.tv/2013/fall/#about,sections

Tuesday, January 21, 2014

Convert all canon mov files in subdirectories to mp4

This will take all mov files in directory and sub-directories and use x264 video with a CRF (Constant Quality) of 20 to encode the video, and encode the audio as 128 Kbps AAC.
for /R %%f in (*.mov) do HandBrakeCLI -i "%%f" -o "%%f.mp4" -e x264 -q 20 -B 128
This will add to default file name .mov additional .mp4 so together it will looks like filename.mov.mp4
You have to manually delete old files.

Related:
https://trac.handbrake.fr/wiki/CLIGuide

Monday, January 20, 2014

Install Harvard's test environment, mastering c language

mirror: https://drive.google.com/file/d/0B6sSIchK9wmMX2hNZlcwWklJOUk/edit?usp=sharing
c03bbf9f0d792ec20b33a6483a544fb7
908834be8017fe8d65c4f20e50d246d3754246ac

su account is disabled but all necessary thing are added to sudo command "Super User Do"

Introducing to printf function
#include <stdio.h>
int main(void){
printf("Let's face it!");
}
Lets face it and move cursor to the new line
#include <stdio.h>
int main(void){
printf("Let's face it!\n");
}
Print double quotes and move cursor to the new line
#include <stdio.h>
int main(void){
printf("Hello, \"Awesomeness\"!\n");
}
Output integer and move cursor to the new line
#include <stdio.h>
int main(void){
int x=6;
printf("yeah! the %i\n",x);
}
Output two integers and move cursor to the new line
#include <stdio.h>
int main(void){
int x=6;
int y=-9;
printf("Yeah! one integer is %i and second is %i\n",x,y);
}
Output string and integer and move cursor to the new line. This example can keep only one word in string.
#include <stdio.h>
int main(void){
char *n="Cat";
int x=6;
printf("My name is %s. I'm %i years old.\n",n,x);
}
Output string with multiple words
#include <stdio.h>
int main(void){
char n[]="Cat the Third";
int x=6;
printf("My name is %s. I'm %i years old.\n",n,x);
}
if statement
#include <stdio.h>
int main(void){

int x=6;
int y=-9;

if (x>y) {
printf("yeah! the %i is greater than %i\n",x,y);
}
else if (x<y) {
printf("yah! the %i is smaller than %i\n",x,y);
}
else {
printf("i gues %i is equalent to %i\n",x,y);
}

}
Output string
#include <stdio.h>
int main(void){
char *n="Anna";
printf("I gues you name is %s\n",n);
}
Output third character of string
#include <stdio.h>
int main(void){
char *n="Artur";
printf("third character in you name is \"%c\"\n",n[2]);
}
Count the characters in string
#include <stdio.h>
#include <string.h>
int main(void){
char *n="Artur";
printf("The string length is %i character\n",strlen(n));
}
for statement
#include <stdio.h>
#include <string.h>

int main(void){

char *n="Artur";

int l=strlen(n);

printf("Name %s in reverse seems like ",n);
for (int c=0; c<l+1; c++) {
printf("%c",n[l-c]);
}
printf("\n");
}
Compare two strings
#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void) {
string pass;

printf("Input password: ");
pass = GetString();

if (strcmp(pass,"hello yelow")==0) printf("You are alowed to level 1\n");
if (strcmp(pass,"orlando")==0) printf("You are alowed to level 5\n");

}
Define numbers and names array
#include <stdio.h>
#include <string.h>

int main(void) {

int numbers[3] = {5433,332,43};
char* names[5] = {"Anna", "Eve", "Kate", "Orf", "Cory Williams"};

printf("The second number in array is %i\n",numbers[1]);
printf("The fifth element in names array %s\n",names[4]);

}
Declaring function
#include <cs50.h>
#include <stdio.h>

void PrintName(string name) {
printf("Hello, %s\n", name);
}

int main(void) {
string names[4] = {"Orf", "Kate", "Joe", "Cory"};
for (int n=0; n<4; n++) PrintName(names[n]);
}
Related:
http://cs50.tv/2013/fall/#l=psets/

Sunday, January 19, 2014

Thursday, January 16, 2014

Create bootable isolinux disk with ImgBurn

Select Create image file from files/folder

Browse for extracted iso image

Fo to Options
Set File System: ISO9660 + Joilet
Set Include Hidden Files
Set Include System Files

Set Allow More Than 8 Directory Levels
Set Allow More Than 255 Character In Path
Set Allow Files Without Extensions
Set Don't Add ';1' Version Number To Files

Set Allow Files Without Extensions

Set Make Image Bootable
Browse for isolinux.bin
Set to Patch Boot Information Table

Wednesday, January 15, 2014

Query Adobe Flash Player version, command line

Query locally
reg query HKLM\SOFTWARE\Macromedia /s

Query for remote computer using psexec.exe from
http://download.sysinternals.com/files/PSTools.zip
psexec /accepteula \\%1 reg query HKLM\SOFTWARE\Macromedia /s
Replace %1 with remote computer name

Another code to query local flash player version
@echo off
setlocal EnableDelayedExpansion
set m=HKLM\SOFTWARE\Macromedia

reg query HKLM\SOFTWARE\Macromedia > nul 2>&1
if !errorlevel!==0 (

	reg query %m%\FlashPlayerActiveX > nul 2>&1
	if !errorlevel!==0 (
	echo Version for FlashPlayerActiveX:
	reg query %m%\FlashPlayerActiveX /v Version | find "Version"
	)

echo.

	reg query %m%\FlashPlayerPlugin > nul 2>&1
	if !errorlevel!==0 (
	echo Version for FlashPlayerPlugin:
	reg query %m%\FlashPlayerPlugin /v Version | find "Version"
	)

)
endlocal
pause

Monday, January 13, 2014

Sunday, January 12, 2014

Compile c code on puppy linux, clang

Source code first.c
#include <stdio.h>
int main(void) {
	for (int i=0; i<10; i++) {
		printf ("lets count %d\n",i); 
	}
}
Install compiler clang
https://drive.google.com/open?id=0Bw6O2bpd3mobS0VnNW1wVUYxS0E
3930dde089d619f3066eea0743319f58
a5ef3caab8b804669c1e7920ad70cc174f9b07f9

Use clang to compile the source code
clang -o blahblah first.c
Run the new object code with ./
./blahblah

Saturday, January 11, 2014

How do i count people in room using pseudocode?


Image from https://www.youtube.com/watch?&v=6hfOvs8pY1k

This is basic counting by one people per time
let n=0
for each person in room
	set n=n+1
Next level is counting by pairs
let n=1
for each pair of people in room
	set n=n+2
if 1 person remains then
	set n=n+1
How do i call "three person group"? Trio? :D
for each trio of people in room
	set n=n+3
if one pair remains then
	set n=n+2
if 1 person remains then
	set n=n+1
How do i call "four person group"? Let's say quartet
for each quartet in room
	set n=n+4
if one trio remains then
	set n=n+3
if one pair remains then
	set n=n+2
if 1 person remains then
	set n=n+1
Related:
https://d2o9nyf4hwsci4.cloudfront.net/2013/fall/lectures/0/w/notes0w/notes0w.html

Prompt for number in windows batch file

@echo off
echo Hello. Lets make a sum of two numbers.
set /p first=Type a first number:
set /p second=Type a second number:
set /a together=first+second
echo %together%
pause

Friday, January 10, 2014

docs.google.com direct link with python, automatically download

Holy cow! I totally did this.
This code will download file from docs.google.com automatically if the document is shared in "Anyone with the link" mode:

As you know google drive provides you quite good download speed.

Here is the deal:
from mechanize import Browser
import re
br = Browser()

br.set_handle_robots( False )
br.addheaders = [('User-agent', 'Firefox')]

id = "0Bw6O2bpd3mobVF94dUFpQjNrYjQ"

r = br.open('http://docs.google.com/uc?id='+id+'&export=download')

html = r.read()

confirm = re.findall('download&amp;confirm=(.+?)&amp;id',html)

filename = re.findall(id+'">(.+?)</a> \(',html)

print filename

download = 'http://docs.google.com/uc?export=download&confirm='+confirm[0]+'&id='+ id

f = br.retrieve(download,filename[0])[0]
Why some variables got [0] at the end? - That is cause it is an "paragraph" array!
confirm and filename is an array record which can contain multiple paragraphs
id is also an array but it only contains multiple letter array not multiple paragraphs.

When start the download then file also starts to cache in RAM

If your operating system reaches 4 GB then in 32-bit python version the download process breaks with message:
MemoryError: out of memory

That is happening cause 32-bit version python can not write more bytes in RAM if 4GB RAM is already taken.
The solution is to use 64-bit python version

Output docs.google.com confirm code with python

This is python code to get confirm code from document 0BxmEiwnrWfmmTjlIVmE0S01YM0U.
from mechanize import Browser
import re
br = Browser()

br.set_handle_robots( False )
br.addheaders = [('User-agent', 'Firefox')]

id = "0BxmEiwnrWfmmTjlIVmE0S01YM0U"

r = br.open('http://docs.google.com/uc?id='+id+'&export=download')

regex = 'download&amp;confirm=(.+?)&amp;id'
pattern = re.compile(regex)
html = r.read()
confirm = re.findall(pattern,html)
print confirm
download&amp;confirm= and &amp;id is just the identificator for start and end text 1:1 from html source.
There are no special characters.

(.+?) just says "Take the content between!"


Next one will print also filename
from mechanize import Browser
import re
br = Browser()

br.set_handle_robots( False )
br.addheaders = [('User-agent', 'Firefox')]

id = "0BxmEiwnrWfmmTjlIVmE0S01YM0U"

r = br.open('http://docs.google.com/uc?id='+id+'&export=download')

html = r.read()

confirm = re.findall('download&amp;confirm=(.+?)&amp;id',html)

filename = re.findall(id+'">(.+?)</a> \(',html)

print confirm

print filename
there are reg expression special character \(in id+'">(.+?)</a> \(


Install Python2 with mechanize and BeautifulSoup module for windows

Related:
http://www.pythonregex.com/

Blog Archive