четвъртък, 3 септември 2020 г.

JetBrains September coding challenge

I love JetBrains IDE's. They are really cool. I am also currently participating in JetBrains academy and I am trying to improve my Java skills. JetBrains academy is a perfect service where you can study Java, Python and Web development. I love the possibility to solve tasks directly in your IDE. I am creating this post because I am participating in JetBrains September codding challenge. The challenge is to solve at least one problem of a day in the academy.

The first one was OOP task.

Here is the description of the task:
"Write a class named User. It must have three string fields: login, firstName, lastName and a constructor with three parameters to initialize these fields. The order of parameters in the constructor must be the same as presented bellow. Do not make the fields and the constructor private."

The idea is the participant to train OOP a little bit. How to create a class in Java and how to create a constructor. Here is a short video which demonstrates the task:



Here is how the code looks:

The second task was:

"You want to create a program that models the behavior of cars. For this purpose, you've created a class named Car containing three fields: the int field yearModel, the string field make, and the int field speed. You want to add functionality to your cars, so you need methods. Add the following instance methods to your class: void accelerate() that adds 5 to the speed each time it's called; void brake() that subtracts 5 from the speed field each time it's called, the speed cannot be less than zero. Do not make the fields and methods private."
The idea is the participant to train OOP more to creating methods. Here the tricky part was that when the car speed cannot be less than 5 the car must stop. :) Here is a short video which demonstrates the task:

Here is how the code looks:



The same day I've implemented a task about multidimensional arrays. You must draw an asterisk in console using a matrix - two dimensional array. The task was a bit tricky but very funny:
The star figure
Given an odd number n, not exceeding 15. Create a two-dimensional array 
(matrix) from n×n elements,
 by filling it with "." symbols (each element of the matrix is a string
 containing a single symbol). 
Then fill the middle row of the matrix, the middle column, and the main 
and the secondary diagonals 
with the "*" symbols. As a result, all "*"s in the array must form the 
star figure. 
Output this matrix; elements of the array should be space separated.


Sample Input:
5

Sample Output:
* . * . *
. * * * .
* * * * *
. * * * .
* . * . *"

This is how my implementation looks: I also implemented Angular version for that task which can be viewed here. This Angular application displays how the shape looks with different matrix sizes.
After I finished the whole challenge I started to write the bellow part of the post.

The third thing which I did was that task:

Given the sequence of integer numbers (which ends 
with the number 0). Find the largest element of the sequence.

The number 0 itself is not included in the sequence 
but serves only as a sign of the sequence’s end.

Sample Input 1:

1
7
9
0

Sample Output 1:

9
And this is my code.

The fourth:

Declare an enum Currency.

It should include the following 
currency codes (according to ISO 4217):

    USD — United States dollar
    EUR — Euro
    GBP — Pound sterling
    RUB — Russian ruble
    UAH — Ukrainian hryvnia
    KZT — Kazakhstani tenge
    CAD — Canadian dollar
    JPY — Japanese yen
    CNY — Chinese yuan

You must include all of the codes presented above and nothing else. 
The constants in the enum can be declared in any order.
This is my code:

The fifth:

It was a sipmple question: 
What name should the class containing the main method have?
Of course it can have any name.


The sixth:

It was finishing of Stage 1/5 of the Tic-Tac-Toe project. You can check 
the whole finished project here 
in Github. 
Description

Tic-tac-toe is a game played by two players 
on a 3x3 field.

One of the players plays as 'X', and the other player is 
'O'. 'X' plays first, then the 'O' side plays, and so on.

The players write 'X' and 'O' on a 3x3 field.

The first player that writes 3 'X' or 3 'O' in a 
straight line (including diagonals) wins.

Your first task in this project is to print any state 
of the field in the console output.
Example

The example below shows how your output might look.

X O X
O X O
X X O 
Bellow you can check the code of that step:

The seventh:

It was finishing of Stage 2/5 of the Tic-Tac-Toe project: 
The user is the gamemaster 
Description

In this stage, you should write a program that 
reads 9 symbols from the input 
and writes an appropriate 3x3 field. Elements of 
the field can contain only 'X', 'O' and '_' symbols.

Note, that field has a specific format and should start 
and end with ---------, all lines in between should start 
and end with '|' symbol and everything in the middle 
should be separated with a single space.
Examples

Examples below show how your output should look.

Example 1:

Enter cells: O_OXXO_XX
---------
| O _ O |
| X X O |
| _ X X |
---------

Example 2:

Enter cells: OXO__X_OX
---------
| O X O |
| _ _ X |
| _ O X |
---------

Example 3:

Enter cells: _XO__X___
---------
| _ X O |
| _ _ X |
| _ _ _ |
---------
Bellow you can check the code of that step:

The eight:

It was finishing of Stage 3/5 of the Tic-Tac-Toe project: 
What's up on the field?  
Description

In this stage, you should analyze a Tic-Tac-Toe field.

Note. In this stage either 'X' or 'O' can start the game.

After printing the field, you need to find the state
in which the game is at the moment. Possible states:

    "Game not finished" - when no side has a 
    three in a row but the field has empty cells;
    "Draw" - when no side has a three in a row 
    and the field has no empty cells;
    "X wins" - when the field has three X in a
    row;
    "O wins" - when the field has three O in a 
    row;
    "Impossible" - when the field has three X 
    in a row as well as three O in a row. Or 
    the field has a lot more X's than O's or
    vice versa (if the difference is 2 or 
    more, should be 1 or 0).

Also, you can use ' ' or '_' to print empty 
cells - it's up to you.
Examples

The examples below show outputs for some 
predefined states. Your program should 
work in the same way.

Example 1:

Enter cells: XXXOO__O_
---------
| X X X |
| O O _ |
| _ O _ |
---------
X wins

Example 2:

Enter cells: XOXOXOXXO
---------
| X O X |
| O X O |
| X X O |
---------
X wins

Example 3:

Enter cells: XOOOXOXXO
---------
| X O O |
| O X O |
| X X O |
---------
O wins

Example 4:

Enter cells: XOXOOXXXO
---------
| X O X |
| O O X |
| X X O |
---------
Draw

Example 5:

Enter cells: XO_OOX_X_
---------
| X O   |
| O O X |
|   X   |
---------
Game not finished

Example 6:

Enter cells: XO_XO_XOX
---------
| X O _ |
| X O _ |
| X O X |
---------
Impossible

Example 7:

Enter cells: _O_X__X_X
---------
|   O   |
| X     |
| X   X |
---------
Impossible

Example 8:

Enter cells: _OOOO_X_X
---------
|   O O |
| O O   |
| X   X |
---------
Impossible
Bellow you can check the code of that step:

The ninth was the project of the day.

Write a program that reads an array of 
lowercase strings and checks whether the array is in alphabetical 
order or not.

There are some rules to compare a pair of strings
a and b:

    First chars of strings are compared: a[0] and b[0]. 
    If a[0] comes earlier than b[0] in the alphabet, 
    then a comes before b in terms of alphabetical order. 
    If the first chars are the same, then the second 
    chars are compared, and so on.
    If a position is reached where one string has no 
    more chars to compare while the other does, 
    then the shorter string is deemed to come first 
    in alphabetical order.
    Finally, identical strings are always in 
    alphabetical order.

You can use compareTo method of the String class to 
compare 2 strings. If this String object 
alphabetically precedes the argument string, 
then the result is a negative integer. The result 
is a positive integer if this String object alphabetically 
follows the argument string. The result is zero if the 
strings are identical. This is exactly what you need 
to compare 2 strings in terms of alphabetical order!

For example

System.out.println("abc".compareTo("acd")); // -1 "abc" < "acd"
System.out.println("abc".compareTo("aac")); //  1 "abc" > "aac"
System.out.println("abc".compareTo("abc")); //  0 "abc" = "abc"

Input data format

The single input line contains lowercase strings separated by spaces.

Output data format

Only a single word: true or false.
Report a typo

Sample Input 1:

a b c

Sample Output 1:

true

Sample Input 2:

a aa az aza

Sample Output 2:

true
Bellow you can check the code of that step:

The tenth was the daily step:

Here is the method named getNumberOfMaxParam that 
takes three integer numbers and returns the 
position of the first maximum in the order of the method parameters.

The method should return number 1, 2 or 3 respectively.

Write just a body of the method.
Report a typo

Sample Input 1:

12 3 12

Sample Output 1:

1
Here you can see my code:

The eleventh was the daily step:

Shape Switch statement
Write a program, which reads the 
number of the shape (1 – square, 
2 – circle, 3 – triangle, 4 – rhombus) 
and prints the text "You have chosen 
a square" (or circle, or triangle, 
or rhombus, depending on the number). 
If it is a number that doesn't correspond 
to any of the listed shapes, 
the program should output: 
"There is no such shape!".

Note: output text should exactly match 
the sample, including letters' 
case and location of spaces.
Report a typo

Sample Input 1:

1

Sample Output 1:

You have chosen a square 
Here you can see my code:

The twelfth was a daily step:

Given a sequence of natural numbers, 
not exceeding 30000. Find the maximum 
element divisible by 4. As input, the 
program gets the number of elements 
in the sequence, and then the elements 
themselves. In the sequence, there is 
always an element divisible by 4. The 
number of elements does not exceed 1000. 
The program should print a single number: 
the maximum element of the sequence divisible by 4.

Try to solve this problem by using a while-loop.
Report a typo

Sample Input 1:

10
76
18
69
63
36
18
49
16
12
50

Sample Output 1:

76
Here you can see my code:

The thirteenth was a daily step:



The cinema has n rows, each row consists of m seats (n and 
m do not exceed 20). 
The two-dimensional matrix stores the information on the
sold tickets, number 
1 means that the ticket for this place is already sold, 
the number 0 means 
that the place is available. You want to buy k tickets 
to the neighboring 
seats in the same row. Find whether it can be done.

Input data format

On the input, the program gets the number of n rows and m seats. 
Then, there are n lines, each containing m numbers (0 or 1) 
separated by spaces. The last line contains a number k.

Output data format

The program should output the number of the row with k 
consecutive available seats. If there are several rows 
with k available seats, output the first row with these 
seats. If there is no such a row, output the number 0.
Report a typo

Sample Input 1:

3 4
0 1 0 1
1 1 0 1
1 0 0 1
2

Sample Output 1:

3

Sample Input 2:

3 3
0 1 0
1 0 0
1 1 1
3

Sample Output 2:

0
You can see my code here:

The fourteenth was a daily step:

Write a program that reads a sequence of integer numbers in a 
loop and adds up all numbers. If a new number is equal to 0, 
the program must stop the loop and output the accumulated sum. 
When the sum is equal or exceeded 1000 (the barrier), 
the program should also stop and output the value equal to sum – 1000.

Note, the input can contain extra numbers. Just ignore them.
Report a typo

Sample Input 1:

800
101
102
300
0

Sample Output 1:

3

Sample Input 2:

103
105
109
0
1000

Sample Output 2:

317
Here you can check my implementation:

The fifteenth was completing of a stage for the Tic-Tac-Toe project.

Stage 4/5: First move!
Description

Now you need to implement player's moves.

Suppose the bottom left cell has the coordinates (1, 1) and the top 
right cell has the coordinates (3, 3) like in this table:

(1, 3) (2, 3) (3, 3)
(1, 2) (2, 2) (3, 2)
(1, 1) (2, 1) (3, 1)

The program should work in the following way:

    Get the 3x3 field from the input as in the previous stages,
    Output this 3x3 field with cells before the user's move,
    Then ask the user about his next move,
    Then the user should input 2 numbers that represent the cell
    on which user wants to make his X or O. (9 symbols representing 
    the field would be on the first line and these 
    2 numbers would be on the second line 
    of the user input),
    Then output the table including the user's most recent move.

Do not delete code that checks for table state; it will be useful 
in the future.

Note that in this stage user moves as X, not O. Keep in mind that the first 
coordinate goes from left to right and the second coordinate goes 
from bottom to top. 
Also, notice that coordinates start with 1 and can be 1, 2 or 3.

But what if the user enters incorrect coordinates? The user could 
enter symbols instead
of numbers or enter coordinates representing occupied cells. 
You need to prevent 
all of that by checking user's input and catching possible 
exceptions.

The program should also check user input. If the user input 
is unsuitable, 
the program should ask him to enter coordinates again.

So, you need to output a field from the first line of the 
input and then ask the
user to enter a move. Keep asking until the user enters 
coordinates that represent
an empty cell on the field and after that output the 
field with that move. 
You should output the field only 2 times: before the 
move and after a legal move.
Examples

The examples below show how your program should work.

Example 1:

Enter cells: X_X_O____
---------
| X   X |
|   O   |
|       |
---------
Enter the coordinates: 1 1
---------
| X   X |
|   O   |
| X     |
---------

Example 2:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------

Example 3:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 3 1
---------
|   X X |
| O O   |
| O X X |
---------

Example 4:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 3 2
---------
|   X X |
| O O X |
| O X   |
---------

Example 5:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 1 1
This cell is occupied! Choose another one!
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------

Example 6:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: one
You should enter numbers!
Enter the coordinates: one three
You should enter numbers!
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------

Example 7:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 4 1
Coordinates should be from 1 to 3!
Enter the coordinates: 1 4
Coordinates should be from 1 to 3!
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------
You can check my code below:

The sixteenth was completing the last stage of Tic-Tac-Toe project:

Description

Now it is time to make a working game!

In the last stage, make it so you can 
play a full game with a friend. First 
one of you moves as X, and then the other 
one moves as O.

You need to create a game loop. The game 
starts with empty cells and ends when 
someone wins or there is a draw. You 
need to output the final result 
after the end of the game.

Good luck gaming!
Example

The example below shows how your program should work.

---------
|       |
|       |
|       |
---------
Enter the coordinates: 2 2
---------
|       |
|   X   |
|       |
---------
Enter the coordinates: 2 2
This cell is occupied! Choose another one!
Enter the coordinates: two two
You should enter numbers!
Enter the coordinates: 1 4
Coordinates should be from 1 to 3!
Enter the coordinates: 1 3
---------
| O     |
|   X   |
|       |
---------
Enter the coordinates: 3 1
---------
| O     |
|   X   |
|     X |
---------
Enter the coordinates: 1 2
---------
| O     |
| O X   |
|     X |
---------
Enter the coordinates: 1 1
---------
| O     |
| O X   |
| X   X |
---------
Enter the coordinates: 3 2
---------
| O     |
| O X O |
| X   X |
---------
Enter the coordinates: 2 1
---------
| O     |
| O X O |
| X X X |
---------
X wins
You can see my implementation below:

The seventeenth was completing the Tic-Tac-Toe project and publishing it to Github.



Тhe eighteenth was completing a daily step:

You are creating a calculator that manipulates complex numbers. 
Write a class named Complex. It must have two double 
fields named real and imaginary.
Below you can check my code:

сряда, 11 декември 2019 г.

Lesson learnt about Hiper-V under Windows 10

I am not a Devop. I use VirtualBox sometimes when I need Nix* compatible system on my business PC. I use Ubuntu on my desktop PC at home. For a project I used to do it on regular basis. Some time ago I needed to install Docker and enabled Hiper-V on host PC. As a result my VirtualBox with Ubuntu stopped work and I was not able to start it even when I disabled Hiper-V completely from Windows interface and switched it off. Every time my VirtualBox was showing the following error:

Result Code:E_FAIL (0x80004005)Component:ConsoleWrap Interface:IConsole {872da645-4a9b-1727-bee2-5585105b9eed}


I researched the problem in Google but nothing helped. The box was not mandatory at that moment and I gave up to fix the issue because I already was working on another project which doesn’t required Nix* architecture. For that project I need Nix* only If I want to tests some bash script. Eventually I found a solution. If nothing helps you can try to fully remove Hyper-V feature with it's files and programs:

Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All


You need to do this in the PowerShell console which needs to be run as an administrator. This is the only thing which helped me. I am writing this post for someone with a similar problem in the future. Thanks to this Stackoverflow answer:

https://stackoverflow.com/a/37143600/907047

Just bear in the mind. Use this only if something other didn't helps.

понеделник, 15 август 2016 г.

Presentation about Babel

I will lead a presentation about Babel in Questers.
Babel is a in fact coverter from ECMAScript 6 to ECMAScript 5. If you want to use ES6 features you can use it into your code and after this you can transpile
it for production. Everione who is interested is welcome. The presentation will be conducted in the Bulgarian language. You can register here.

събота, 16 юли 2016 г.

How to have value like baseDirectory into singleton object in Sbt?


I am currently a lamer in sbt technology. Sbt stands for Simple build tool. This is a build system that is highly developed, modern and is the de facto standard build tool in the Scala world. Currently I'm using sbt for several job tasks and last week I came across a rather unpleasant problem that probably is very easy to solve for experienced Scala and sbt developer. I am writing this article to help people with a similar problem in the future. Sbt has several global settings. One of this global settings is
baseDirectory. Depending on the scope, this is the base directory for the build, the project, the configuration, or the task. You can easy get value of project base directory from sbt console. Just type
baseDirectory and you will get the value of this setting.
You can also use inspect baseDirectory and you will get additional information.
In sbt is a good practice to isolate long tasks into singleton object and keep build.sbt much shorter. This is very cool but in order to have some global settings into this singleton object there are several tricky things that you must to do. The same thing is true if you want to have streams available to the singleton object. My job task involved to process a certain way all the files that meet certain criteria. For this purpose, I had to have baseDirectory for project. When I tried to pass baseDirectory as a method argument in this way:
And this:
Every time I got error like this:
I tried several things. For example to pass baseDirectory.value in this way:
But I got errors that .value cannot be used in this way. In the end, I managed to solve the problem with using ".." into the singleton object, that means "the parent directory". But this solution is not good at all. What will happen if the location of .scala file is changed? I love stackoverflow. Sometimes you can ask and get valuable help and explanations. Also you can answer questions and thereby helping others. I asked the question and received a helpful guidance. So If you want to have baseDirectory or similar value into singleton object, you must define the object like this.
And into build.sbt this:
Or this:
I like second solution because looks much clearer.
You can also check example repository into github here. If you want you can check the stackoverflow question.

понеделник, 4 юли 2016 г.

Install latest maven 3 under Ubuntu.

Maven is the de facto standard build tool for Java. There is something that extremely annoys me under Ubuntu. That every time you need to install the latest maven 3 manually and never got it in the standard Personal Package Archives ('PPAs'). Of course there are external PPA, but always the question arises how much can be trusted their contributors. Today I again needed to update maven into one vagrant box so I repeat the exercise again. Maybe this bash script will be useful for the people with a similar problem in the future. The script just install the latest - 3.3.9 version of Maven. The idea is to can be modified easily in the future - just to change variables with name and path. I do not pretend that the script is good - I'm not bash programmer.

понеделник, 5 октомври 2015 г.

Jasmine Clock

Today I had to write unit tests for JavaScript time dependent code. I liked that Jasmine supported a way to make setTimeout or setInterval to behave synchronously. When we install clock with jasmine.clock().install(); into beforeEach we change behaviour of setTimeout and setInterval functions to be synchronous.
After this we can move forward in time like using time machine and check result of asynchronous process. We can go into future with jasmine.clock().tick function, which takes a number of milliseconds. This is small example code:

TimeoutSpec.js
1    describe("Jasmine Clock demo", function () { 
2     
3        // It is installed with a call to jasmine.clock().install  
4        // in a spec or suite that needs to manipulate time. 
5        beforeEach(function () { 
6            jasmine.clock().install(); 
7        }); 
8     
9        // Be sure to uninstall the clock after you are done  
10       // to restore the original functions. 
11       afterEach(function () { 
12           jasmine.clock().uninstall(); 
13       }); 
14    
15       it("setTimeout must behave synchronously", function () { 
16           var array = [1, 2, 3, 4, 5, 6]; 
17           var sum = 0; 
18           (function _handleArray() { 
19               sum += array.shift(); 
20               if (array.length != 0) { 
21                   setTimeout(_handleArray, 0); 
22               } 
23           }()); 
24    
25           // The cool part  
26           // We have something like 
27           // time machine and can  
28           // move time forward.  
29           jasmine.clock().tick(200); 
30           // 1 + 2 + 3 + 4 + 5 + 6 
31           // is equal to 21 
32           expect(sum).toEqual(21); 
33       }); 
34   }); 
35   
And here can be viewed this code: http://gonaumov.github.io/jasmineClockDemo/ running into Jasmine 2.3.4 with spec file.

четвъртък, 27 август 2015 г.

Get rid of crossdomain origin errors.

When developers work on web applications under Windows there are often crossdomain  origin errors. The old version of  Google Chrome browsers provides a  usefull feature
--disable-web-security command line argument for  chrome.exe but unfornatelly this option was deprecated.  When you try to use it under current version of Chrome
- Version 44.0.2403.157 m you will get the following error:
"You are using an unsupported command-line flag:   --disable-web-security. Stability and security will suffer.". I tried to download current Chromium build   but with no luck - this errors appear again. After a small time thinking I'm came to a solution that I want to share with other people with a similar problem. I download Opera that is based on Chrome. Under Opera this command line option
 works like a charm and you have the same tools available.  Even an emulator for mobile devices.


Here is small demo. Get response from yahoo when google is open. Executing of this small snippet
from console.

(function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.open('GET', '//www.yahoo.com/', true);
xhr.send();
}());

And here is the result: 


But if you want to use just a Google Chrome I write this script to make the starting of Google Chrome browser without security much easier than it was before. The script checks if there is running instances of chrome.exe and if there is a present instance, alerts the user that the running instance must be killed before Google Crome is started. If the user clicks on Yes button, the script will kill all instances of chrome.exe. After this, will open a new browser instance without security. If the user clicks on No button, the script will do nothing. If there is no present running instance of chrome.exe, the script will start Google Chrome without security. How to use it? Just clone this repository and fill correct path to chrome.exe. The script is tested on windows 8 with admin rigths. Don't hesitate to write to me with suggestions and feature requests.
https://github.com/gonaumov/chromeRunner

събота, 13 юни 2015 г.

Cucumber-js and Chai how to expect if element with given selector exist in DOM

This week I had one problem with protractor and cucumberjs. I read protractor documentation and asked question into stackoverflow. I want to share one very small learned lesson here also. If you want to expect if element with a given selector exist in DOM you must use isPresent() it returns a promise that will resolve to whether the element is present on the page.

    element(by.id('someId')).isPresent().then(function(isElementVisible) {
         expect(isElementVisible).to.be.true;   
    });
 
Or use chai with promises.

    expect(element.isPresent()).to.eventually.be.false
 
However, the word "eventually" sounds unpleasant. We want to be sure not eventually sure. :)
Here can be viewed the quesion into stackoverflow.  

вторник, 2 юни 2015 г.

Емилиян Кърчев и http://energyaudit.bg

Емил или за възпитанието. Горкият Русо. Това е цитат от Богомил Райнов. Не е измислен от мен. Викнахме въпросният господин да направи експертиза на един теч, който излезе в следствие на направен ремонт. Решихме, че сайта му е най-представителен и изглежда най-професионално от всички. На сайта на господина няма цени. Казал е на жена ми цена от 138лв. Аз дойдох след работа, за да може да се извърши диагностиката, но не бях чул добре цената, която трябва да се плати.  Бях чул нещо от сорта на 174лв. Е дадох му 180лв с идеята, че ще си хване, колкото му трябват. Господина си ми пусна касова бележка за 180лв. След това разправял на жена ми, че за да ни пусне констативен протокол трябвало да чукне още 48лв а снимките се обработвали със специален софтуер. Не, че е кой знае какъв проблем де, но е важен принципа в крайна сметка. Браво Емо. Тия 50лв. да ги дадеш за лекарства. Ето го и сайта на господина.
Промяна от 04.06.2015г.
Да допълня. Това, че няма цени на сайта не отговаря на истината. Мое недоглеждане. Денят ми беше твърде зает, за да гледам сайта на господина. По тази причина и му дадох 180лв с идеята да си хване колкото е цената, както съм писал по-горе. Притежавам и касова бележка за сумата. По долу показвам и текущите цени на сайта на господина.
Сметката пак не излиза. При промяна цените спрямо тази дата (03.06.2015г) могат да бъдат извлечени от всеки кеш на търсеща машина.

неделя, 5 октомври 2014 г.

Bot for sexgangsters game.

I love to write user scripts. These days I have some fun to write bot for a very nice online game. From the programming perspective interesting part is the use of MutationObserver, with his help the programmer easily can detect changes in the DOM structure.
I made the bot as a add-on for Mozilla Firefox and set as a project in github. There are some issues, which I'll fix in my spare time.
https://github.com/gonaumov/sexGangstersBizBot

вторник, 12 август 2014 г.

Dynamic routing in AngularJS App.config method.

Some time ago I had a work task required to make dynamic routing in App.config method of AngularJS application. Initially I wanted to do something like this:

someApp.config(['$routeProvider', '$httpProvider', 
    '$compileProvider', 'settings',
    function ($routeProvider, $httpProvider, 
        $compileProvider, settings) {

        var $http = angular.injector(['ng']).get('$http');
        var $q = angular.injector(['ng']).get('$q');
        var isUserLogged = $q.defer();

        $http.get(settings.apiUri + settings.loginStatus).
          success(function (data) {
            if (data.status == "NOT_LOGGED") {
                isUserLogged.reject();
            } else {
                isUserLogged.resolve();
            }
        });

        isUserLogged.promise.
          catch(function () {
             $routeProvider.
                 when('/home', {
                     templateUrl: 'partials/home.html',
                     controller: 'HomeController'
                 }).
                 otherwise({
                 redirectTo: '/home'
             });
        });

        isUserLogged.promise.
         then(function () {
            $routeProvider.
                when('/accountsettings', {
                    templateUrl: 'partials/accountsettings.html',
                    controller: 'AccountSettingsController'
                }).
                otherwise({
                    redirectTo: '/accountsettings'
                });
        });
    }]);

But routing did not work because .config method behaves as synchronous. When I remove the http query and promice logic everything worked perfectly. I asked a question in stackoverflow, but there was no answer. After reading the documentation and digging I came to the decision that satisfy me. I did a manual bootstrapping of the application. First I make request to determine whether the user is logged or not. Then I trigger custom event listener whose call .config method of application and do routing in accordance whether the user is logged or not. Below is the code of the decision to which I got (with abbreviations).

angular.element(document).one("userStatusIsCheked", 
                        function(event, userIsLogged) {
    appName.config(['$routeProvider', 
        '$httpProvider', '$compileProvider',
        function ($routeProvider, 
         $httpProvider, $compileProvider) {
            if (userIsLogged == true) {
                $routeProvider.
                    when('/resetpassword/:hashValue', {
                        templateUrl: 'partials/home.html',
                        controller: 'ResetPasswordController'
                    }).
                    when('/accountsettings', {
                        templateUrl: 'partials/accountsettings.html',
                        controller: 'AccountSettingsController'
                    }).
                    when('/changepassword', 
                      {
                        templateUrl: 
                        'partials/accountsettingschangepassword.html',
                        controller: 'ChangePasswordController'
                    }).
                    when('/edit', {
                        templateUrl: 'partials/accountsettingsedit.html',
                        controller: 'EditAccountController'
                    }).
                    when('/apikeymanagement', {
                        templateUrl: 'partials/apikeymanagement.html',
                        controller: 'APIKeyManagementController'
                    }).
                    when('/dashboard', {
                        templateUrl: 'partials/dashboard.html',
                        controller: 'DashboardController'
                    }).
                    when('/pipelines', {
                        templateUrl: 'partials/pipelines.html',
                        controller: 'PipeLinesController'
                    }).
                    when('/preferences', {
                        templateUrl: 'partials/preferences.html',
                        controller: 'PreferencesController'
                    }).
                    when('/reports', {
                        templateUrl: 'partials/reports.html',
                        controller: 'ReportsController'
                    }).
                    when('/logout', {
                        templateUrl: 'partials/logout.html',
                        controller: 'LogoutController',
                        resolve: {
                            logout: function (logout, $q) {
                                var deferred = $q.defer();
                                logout()['finally'](
                                    function() {
                                        deferred.resolve();
                                    }
                                );
                                return deferred.promise;
                            }
                        }
                    }).
                    when('/privacy', {
                        templateUrl: 'partials/privacy.html',
                        controller: 'PrivacyController'
                    }).
                    when('/tos', {
                        templateUrl: 'partials/tos.html',
                        controller: 'TosController'
                    }).
                    when('/currentStatus', {
                        templateUrl: 'partials/currentStatus.html',
                        controller: 'CurrentStatusController'
                    }).
                    otherwise({
                        redirectTo: '/dashboard'
                    });

            } else {
                /**
                 * If user is not logged default action is
                 * home.
                 */
                $routeProvider.
                    when('/home', {
                        templateUrl: 'partials/home.html',
                        controller: 'HomeController'
                    }).
                    when('/resetpassword/:hashValue', {
                        templateUrl: 'partials/home.html',
                        controller: 'ResetPasswordController'
                    }).
                    when('/privacy', {
                        templateUrl: 'partials/privacy.html',
                        controller: 'PrivacyController'
                    }).
                    when('/tos', {
                        templateUrl: 'partials/tos.html',
                        controller: 'TosController'
                    }).
                    when('/currentStatus', {
                        templateUrl: 'partials/currentStatus.html',
                        controller: 'CurrentStatusController'
                    }).
                    otherwise({
                        redirectTo: '/home'
                    });

            }
        }]);

        angular.bootstrap(document, ['appName']);
});

angular.element(document).ready(function() {
    var injector = angular.injector(['appName']);
    var settings = injector.get('settings');
    var $http = injector.get('$http');

    var functionFactory = function (userStatus) {
        return function () {
            this.lUserStatus = userStatus;
            return this.lUserStatus;
        }
    };

    /**
     * So here we will check if user is logged or
     * not and after this construct conditional routing
     * into config method (above).
     */
    $http.get(settings.apiUri + settings.loginStatus).
             success(function (data) {
        if(angular.isDefined(data.status) && 
            data.status == "NOT_AUTHENTICATED") {
            appName.service('userIsLogged', functionFactory(false));
            angular.element(document).trigger("userStatusIsCheked", [false]);
        } else if(angular.isDefined(data.status) && data.
                status == "AUTHENTICATED") {
            appName.service('userIsLogged', 
            functionFactory(true));
            angular.element(document).trigger("userStatusIsCheked", [true]);
        }
    });
});


Hope this helps someone with a similar problem.

New site dedicated to web development

My wife and I started to create a website dedicated to the development for the web. We hope that this site will be useful to all interested in the subject design and programming. http://codinghunters.com/

събота, 24 май 2014 г.

Bulgarian state institutions - a home for slackers and incompetents.

I am writing this material reluctantly. Unfortunately, in Bulgaria people that work in important state institutions are mostly illiterate and irresponsible. Yesterday I was shocked by a criminal negligence. Ministry of Education and Science is maintaining a web site service , located at this url: http://www2.mon.bg/adminrhe2/. In the question url, user can checks whether there are any university diploma on his behalf. Me, who last year defended a thesis in SULSIT as an upgrade over professional bachelor, did check that I have been in the register and noticed something that made me 'amazed' (I'm a web developer with years of experience). It's that uniform civil numbers of the users are sent to the system for inspection, using uncoded Protocol (http). This means that each route to a question asp script (http://www2.mon.bg/adminrhe2/default.asp), eg ISP user can access and capture sensitive personal information. This information is confidential and extremely important for the user. The screenshot below shows how easy it is to be caught this element of the request. I hid only the last digits of my number to protect my safety.
That so called "technical support", which takes place within the project "Information and telecommunication technologies in education" or ICT in Education (BG051PO001/3.1-01), is implemented by the Bulgarian company AdminSoft. Who knows how much money had been sunk into this project, which obviously was made by incompetents. My wife wrote this into a facebook group 'Marketing and Webmastering' and there was immediate reaction by an internet blogger, who wrote an article, explaining the importance of HTTPS and where were given another examples of the government institutions websites, which also don't have encryption.
The story has a sequel. I sent a complaint to the Bulgarian Commission of Protection of Personal Data, and after six months I received a response from them. I'm attaching here the document received by them only hiding my address and theirs documentation numbers. This document confirms that there was indeed a problem and it was resolved after intervention by the Commission.

събота, 5 април 2014 г.

Canonical will shutting down the Ubuntu One file services.

I really like the operating system Ubuntu. I'm very sorry that I got this email today. Maybe Canonical have any financial problems.

From: Ubuntu One noreply@one.ubuntu.com
Subject: Ubuntu One file services

Hi,

We are writing to you to notify you that we will be shutting down the
Ubuntu One file services, effective 1 June 2014. This email gives
information about the closure and what you should expect during the
shutdown process.

As of today, it will no longer be possible to purchase storage or music
from the Ubuntu One store. The Ubuntu One file services apps in the Ubuntu,
Google, and Apple stores will be updated appropriately.

As always, your content belongs to you.  You can simply download your files
onto your PC or an external hard drive.  While the service will stop as of
1 June, you will have an additional two months (until 31 July 2014) to
collect all of your content. After that date, all remaining content will
be deleted.

If you have an active annual subscription, the unused portion of your fees
will be refunded. The refund amount will be calculated from today's
announcement.

We know you have come to rely on Ubuntu One, and we apologise for the
inconvenience this closure may cause.  We've always been inspired by the
support, feedback and enthusiasm of our users and want to thank you for
the support you've shown for Ubuntu One. We hope that you'll continue to
support us as together we bring a revolutionary experience to new devices.

The Ubuntu One team

събота, 15 февруари 2014 г.

Incorrect chess sold in the shop Jumbo.

I like to play chess. In my work I along with my colleagues wanted to buy a nice chess set package including the pieces and a board and play chess sometimes after working time. Today I went to a nearby shop Jumbo located at Sofia Drujba-2 11, Obikolna str. and find chess set that is sold at a good price. This shop is owned by Jumbo Group. Chess set is nice, but the board is wrong. I viewed the set, but did not buy it. Below can be seen a picture of the set.
As can be seen here, when you sit at your side of the board, on your right corner there is always a white square.
My conclusion from this case is that users need to be careful and check chess sets in the shop before buy them. It seems that the manufacturer of these chess sets never played chess.

AngularJS $http, CORS and http authentication

Some time ago I had a task for the company where I work. The task had to use CORS. I am writing this article to share lesson learned.
You want to send POST request to different domain with AngularJS $http service? There is several tricky thing into AngularJS and server setup.
First: In your application config you must to allow cross domain call

    /**
     *  Cors usage example. 
     *  @author Georgi Naumov
     *  gonaumov@gmail.com for contacts and 
     *  suggestions. 
     **/ 
    app.config(function($httpProvider) {
        //Enable cross domain calls
        $httpProvider.defaults.useXDomain = true;
    });

Second: You must specify withCredentials: true and username and password into request.


     /**
      *  Cors usage example. 
      *  @author Georgi Naumov
      *  gonaumov@gmail.com for contacts and 
      *  suggestions. 
      **/ 
       $http({
      url: 'url of remote service',
      method: "POST",
      data: JSON.stringify(requestData),
      withCredentials: true,
      headers: {
       'Authorization': 'Basic bashe64usename:password'
      }
     });

Тhird: Server setup. You must provide:

    /**
     *  Cors usage example. 
     *  @author Georgi Naumov
     *  gonaumov@gmail.com for contacts and 
     *  suggestions. 
     **/ 
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: http://url.com:8080");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

For every request. When you receive OPTION you must pass:


    /**
     *  Cors usage example. 
     *  @author Georgi Naumov
     *  gonaumov@gmail.com for contacts and 
     *  suggestions. 
     **/ 
    if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
       header( "HTTP/1.1 200 OK" );
       exit();
    }


HTTP authentication and everything else comes after that. Here is complete example of usage of server side with php.

   /**
     *  Cors usage example. 
     *  @author Georgi Naumov
     *  gonaumov@gmail.com for contacts and 
     *  suggestions. 
     **/ 
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: http://url:8080");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
    
    if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
       header( "HTTP/1.1 200 OK" );
       exit();
    }
    
    
    $realm = 'Restricted area';
    
    $password = 'somepassword';
    
    $users = array('someusername' => $password);
    
    
    if (isset($_SERVER['PHP_AUTH_USER']) == false ||  isset($_SERVER['PHP_AUTH_PW']) == false) {
        header('WWW-Authenticate: Basic realm="My Realm"');
    
        die('Not authorised');
    }
    
    if (isset($users[$_SERVER['PHP_AUTH_USER']]) && $users[$_SERVER['PHP_AUTH_USER']] == $password) 
    {
        header( "HTTP/1.1 200 OK" );
        echo 'You are logged in!' ;
        exit();
    }
    ?>

Here can be found me question in stackoverflow.

събота, 8 февруари 2014 г.

Arrows in GIMP.

I like GIMP. Gimp is very useful for people that don't like commercial software. When you get accustomed to it GIMP is very pleasant for using software. In my work I often have to annotate screen shots. For this I was slightly unpleasantly surprised when I learned that GIMP has  no arrows. I found this very good plugin that adds this feature in GIMP.  You must put the script under gimp/2.0/scripts directory. Under Ubuntu 12.04 (my current working box) you can install it using this one liner:

 sudo wget -O /usr/share/gimp/2.0/scripts/arrow.scm http://registry.gimp.org/files/arrow.scm

The above shell command works correctly also under Ubuntu 13.10.

How to use it: 
1.You must make a path with  Path tool. 

 2. From Tools select Arrows ..

 3. Settings dialog appears. 

4. After playing with settings and press OK you can see finished arrow.
Have fun.

петък, 3 януари 2014 г.

Disable notifications on skype only for particular contact under Linux.

Sometimes we need to switch off skype notifications but for particular contact only. In windows there is easy solution «Conversation» -> «Notification settings ...» -> «Do not notify me» unfortunately this option is missing under Linux version. I googled for solutions but there is no results. All articles shows that this is possible under Windows and Mac versions of skype. Once I thought I noticed that some of the commands for group chat is available for personal.
I did some experiments and came to a solution. When you want to disable notifications on skype only for particular contact under Linux you can use this command in chat window:
/alertsoff
. If you want to activate notifications you can use:
/alertson
. Hope this helps someone with a similar problem.

неделя, 10 ноември 2013 г.

«ТОР: Светът на мрака » - един мега тъп филм.

Вчера ходихме с жена ми да гледаме този филм. Нечие голямо въображение е създало някаква странна смес от междузвездни войни, митология и комикси. Локи е единственият, притежаващ нормална интелигентност и дори е до някъде симпатичен. Тор, богът на гръмотевиците е просто смешен и прилича на гей или метросексуален нищо, че има някакви мъжкарски залитания. Липсата на въображение в сценария е компенсирана с много специални ефекти. Хеймдал/Хеймдалур, който е известен в нордическите предания като буквално "най-белият от асите" и "белият бог" тук е негър. Като цяло филма е добър за да убиете един час, но да отидете на кино, заради него е грешка.

петък, 1 ноември 2013 г.

Детектване на операционнате система с JavaScript.

Тия дни получих един много забавен лог по скайп от един приятел. Прилагам го по-долу. Репликите са, както са ми били изпратени като само никовете на хората са сменени. Ето го да се посмеете малко:
[09:29:55] с какъв виндовс си?
[09:29:55] Иван: хр, 7 или 8?
[09:31:29] Music: как да разбера?
[09:31:43] Иван: бррррр
[09:32:27] Music: един ромб и свети
[09:32:31] Music: излиза сияние от него
[09:32:32] Иван: копче с байраче и надпис старт - значи си   със ХР или 7
  кръгче с байраче - 7
  нямаш старт бутон - 8
[09:32:45] Иван: ромба е байраче
[09:32:48] Music: кръгче с байряче и свети!
 
По този случай надрасках едно малко скрипте, с което може да се детектва версията на Windows. Детектва и линукс, но само, че е линукс не версията му. Кликнете върху бутона по-долу и ще се покаже каква операционна система ползвате. Забавлявайте се.