Showing posts with label algorithms. Show all posts
Showing posts with label algorithms. Show all posts

Friday, 17 May 2013

Modulo adjustment

If you open MDN pages, describing Math.ceil, Math.floor, and Math.round, you will find the good example of the adjustment and rounding based on the decimal logarithm. For exdample, Math.ceil10(55, 2) returns 100 where 2 expresses an exponent for 10^2.

Besides of logarithmic adjustment we can use modulo based adjustment. It is almost the same as above but uses an arbitrary number for adjustment.

Monday, 25 June 2012

Merge and sort many logfiles having multiline entries

logmerge is the small and powerful script to merge two or more log files so that multiline entries appear in the correct chronological order without breaks of entries. Optional arguments control an adding of descriptive fields at the beginning of each line in the resulting combined logfile. Reading of .gz/.bz2 files is available.

Thursday, 5 January 2012

Artist/Album Info in Foobar2000

foobar2000 is perfect mediaplayer for Windows platforms. It is kind of those applications whose functionality is extendable simply adding plugins. One of these finest plugins is Run services that allows to run external applications and scrpts from within foobar2000.

I use Run services to view/edit information about albums or artists stored in plain text files. Let's consider how it is possible.

Tuesday, 12 July 2011

parseDate

Функция преобразует дату, заданную строкой, в количество миллисекунд относительно базового времени, и возвращает его. Строка должна содержать дату и время в определенном формате. Функция аналогична стандартному методу Date.parse. Отличие заключается в том, что корректно обрабатывает строки, содержащие миллисекунды.

Sunday, 1 May 2011

Обмен данными и объектами между скриптами

Однажды на Сером форуме шло обсуждение как можно осуществить обмен данными между скриптами. Идея основана на создании нового экземпляра, наследуемого от интерфейса IWebBrowser2 (ссылка: IWebBrowser2 Interface). Объект хранит в себе данные даже после завершения всех скриптов, практически как буфер обмена, и может служить как средство обмена данными и объектами между скриптами.

Sunday, 26 December 2010

JavaScript html entities

Несколько дней назад мой коллега попросил меня помочь реализовать код вставки специальных символов, выраженных их сущностями [1]:

var original = 'string with guillemets (standard quotation marks in Russia) « and »';

// do something to convert the original string to applicable characters
var entities = ...;

// insert the resulting string to the DOM
var textNode = document.createTextNode(entities);

Найденное решение [2] видимо очень известно во всем интернете. Однако это решение нам показалось не оптимально - довольно громоздкий код, который циклически перебирает и заменяет программно заданный набор сущностей. И этот код не использует внутренние возможности самого браузера - ведь браузер делает это автоматически. Но решение было найдено [3]. Этот код полностью нас удовлетворял - он очень мал, использует встроенные возможности и не содержит жестко заданного набора конвертируемых сущностей. Параллельно мы нашли решение для обратной задачи - перевод символов в их сущности [4].

В дальнейшем мы адаптировали оба решения в единый класс Entity. Мы обратили внимание на тот факт, что при переводе "двойных" и 'одинарных' кавычек они не преобразуются в свои сущности. Это не столь критично, но мы посчитали, что этот "недостаток" должен быть исправлен и добавили немного "ручной" работы.

Полное решение с комментариями можно найти по этой ссылке. Здесь можно посмотреть как это работает:


  1. Мнемоники в HTML (Википедия, англ.)
  2. html_entity_decode
  3. javascript equivalent of html_entity_decode
  4. PHP-функция: htmlentities

Tuesday, 27 April 2010

Wednesday, 17 March 2010

Y-combinators

Thursday, 28 January 2010

CMD/BAT: Repeat a string multiple times

If you want to get a string repeated multiple times -- you can use this routine. I have realised this as an attempt to implement this optimal algorithm using CMD/BAT only. It accepts three arguments: the name of a variable to store the resulting string, the multiplier (number of time the input string should be repeated), and the input string.

Wednesday, 11 November 2009

IEEE754 converter

Tuesday, 3 November 2009

Cross-platform date/time definition

Earlier here (in Russian) i have investigated ways how to obtain date and time parts using the CMD.EXE features. After that here (in Russian too) i have simplified this way until two lines of a code. But both ways are platform-dependent - the order of date parts depends on the locale settings.

Recently i found the excelent link (in Russian too) with the description how to obtain the subject platform-independently.

I slightly modified the established method and present it now.

Thursday, 29 October 2009

CMD/BAT Librarian

Introduction
Unfortunately CMD.EXE, the command line interpreter in Windows, does not allows to collect favorite scripts under appropriate folders and use them multiple times in the future. So we have to use the "copy-and-paste" technology to migrate some needed functionalities from one script to another.

The script below allows to store debugged scripts under the determined folder, use them mutiple times, compile and link automatically to the final script.

Tuesday, 8 September 2009

CMD/BAT: GetOptions

This is flexible and useful library to manipulate with arguments in CMD/BAT scripts.

Monday, 27 July 2009

URL parsing in Javascript

There is very simple way to parse URL in Javascript. Just define new method in the prototype of the String. Of course, it has own shortcomings but in the most cases it covers the wide range of URLs and protocols (http(s), ftp, mailto, etc; the mandatory part of URL, host is considered as domain names, IPs, and localhost separately), and moreover it considers the more complex URLs like jdbc:oracle://localhost:1521.

Monday, 15 June 2009

Validate number arguments within CMD/BAT

@echo off

if "%~1" == "" (
    echo EMPTY
    goto :EOF
)

if "%~1" == "0" (
    echo ZERO
    goto :EOF
)

set /a number_var=%~1 2>nul

if errorlevel 2 (
    echo ILLEGAL
    goto :EOF
)

if %~1 neq %number_var% (
    echo ERROR
    goto :EOF
)

set number_var
goto :EOF

Saturday, 13 June 2009

Complex numbers with Javascript

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

Friday, 27 March 2009

JavaScript / JScript Benchmark (en)

Beginning

I will not lie - I do not like to estimate a performance of javascript code. This procedure provides for the main project a lot of "unnecessary" and "senseless" code:
var n = 1000; 
var start = (new Date()).getTime();/
for (var i = 0 ; i < n; i++) {
    // bla-bla-bla ...
}
var stop = (new Date()).getTime();
var duration = stop - start;
var average = duration / n; 
document.writeln(average);
I can presume that all the familiar lines such as these. I may be interested in the performance of a function or method, and possibly, some of program. But I do not want to pollute my working project by some kind of garbage, such as this. Also I do not want this for function that I am trying to estimate - what algorithm is better.
When I finally tired of it - I decided to develop a Benchmark. The objective was to estimate the performance of not only function, but any piece of code, beginning from the line n and ending by line m.

Motivation

Starting this work, I understood - it is possible that this code has been realized already and successfully. Nevertheless I started ab ovo. When finishing I decided to compare my solution with solutions of my predecessors (links are in the bottom of the article). I will not overmodest - despite of some similarities, my solution is better. The argumentation is following - despite of similarity my code is universal essentially.
Then I will show - that is, and how it can be very convenient and simple tool. Partially similarities and differences of the actual solution and it’s predecessors will be consider.

Features of OO-approach in JavaScript

Any piece of code can be a body of nameless function (this is truth for JavaScript especially taking in account it’s special OO realization). E.g.:
var arr = [100, 200, 300, 400]; 
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
can be transformed to the next
var arr = [100, 200, 300, 400]; 
((function() 
{
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
})(); 

Realization

This means that for any function you can apply a method which can perform additional actions:
Function.prototype.eval = function()
This method is defined for internal object Function, it is a certain amount of times, while retaining the length function and prints some statistics about the performance.
Let's to examine an example of usage:
var arr = [1, 2, 3, 4];

function sum(arr)
{
   var result = 0;
   for (var i = 0; i < arr.length; i++) {
      result += arr[i];
   }
   return result;
}

// original code
var s = sum(arr);

// modified code
var s = sum.eval(arr);
When comparing the original and modified codes, it can be seen that a difference is minimal. The code is pure until now and the result allows analyzing of information.

Features

This solution does not use timers and can be performed in different environment such as the browser window and standalone applications. Also it consists of the additional code solving problem of platform independency.
What has been implemented additionally? In the difference of analogues this code works in the most of cases - JavaScript/JScript. To reach this feature some additional useful properties has been defined:
- Function.prototype.evalCount - integer parameter keeps the number of iterations, by default is1000.
- Function.prototype.evalDuration - integer parameter keeps duration of the code execution. It is evaluated during a benchmarking process and does not have default value.
- Function.prototype.evalPrint = function() - auxiliary function for output of statistics of the performance. It takes in account differences of environments and launches appropriate output method. By default, it outputs the number of iterations and duration.
Of course, these parameters can be redefined, e.g., change the number of iterations or change the method of the statistics output. And this can be performed both globally via the function’s prototype and locally for the actual function. E.g.:
sum.evalCount = 10240; // 10K iterations
var result = sum.eval(1, 2, 3, 4);

Benefits

In the contrast of analogues the suggested method:
1. allows a light embedding the performance code with minimal modifications of the main code;
2. has extended features of control;
3. independent of the environment and allows to use this extension without modification both JavaScript and JScript (Windows Scripting Host).

The full solution

The solution is environment independent. It has been tested for IE6, IE7, FF2.0.0.15, FF3.0.7 and Windows Scripting Host. It is distributed under the GPL. The source code is available by this link. Ibid - the download link.

References

1. John Resig's blog
2. webtoolkit site

Saturday, 21 March 2009

JavaScript / JScript Benchmark

Начало

Не буду лгать - я не люблю оценивать производительность javascript кода. Эта процедура содержит для основного проекта массу "ненужного" и "бессмысленного" кода:
var n = 1000; 
var start = (new Date()).getTime();/
for (var i = 0 ; i < n; i++) {
    // bla-bla-bla ...
}
var stop = (new Date()).getTime();
var duration = stop - start;
var average = duration / n; 
document.writeln(average);
Думаю, всем знакомы строчки, подобные этим. Меня может интересовать производительность функции или метода, а возможно и некоторого участка программы. Но я не хочу засорять свой еще сырой код всяким мусором, подобным этому. Я также не хочу это делать для функций, когда пытаюсь оценить - какой же алгоритм лучше.
Когда мне это окончательно надоело - я решил написать свой Benchmark. Задача заключалась в том, чтобы можно было оценить производительность не только функции, но и любого участка кода, начиная со строки n и заканчивая строкой m.

Мотивация

Начиная работу, я понимал - вполне вероятно, что такой код уже кем-то и весьма успешно реализован. Тем не менее, я начал с нуля. После завершения я решил сравнить свое решение с работами своих предшественников (ссылки в конце). Не буду скромничать - не смотря на некоторое сходство, мое решение лучше. Аргументация следующая - при существенном сходстве реализации мой код в значительной мере более универсален.
Далее я покажу - что есть, и как из него можно получить весьма удобный и простой инструмент. Частично будут рассмотрены сходства и различия настоящего решения и его предшественников.

Особенности ОО-подхода в JavaScript

Любой фрагмент кода (особенно это справедливо для JavaScript с его особым ОО-подходом) может быть телом безымянной функции. Например, код
var arr = [100, 200, 300, 400]; 
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
может быть преобразован в следующий
var arr = [100, 200, 300, 400]; 
((function() 
{
    var result = 0; 
    for (var i = 0; i < arr.length; i++) {
        result += arr[i];
    }
})(); 

Реализация

Это значит, что для любой функции можно применить некий метод, который может выполнить дополнительные действия, а именно:
Function.prototype.eval = function()
Данный метод определен для встроенного объекта Function, вызывает его определенное количество раз, при этом запоминает длительность выполнения функции и печатает некоторую статистическую информацию о ходе выполнения.
Посмотрим на примере как эго можно использовать:
var arr = [1, 2, 3, 4];

function sum(arr)
{
   var result = 0;
   for (var i = 0; i < arr.length; i++) {
      result += arr[i];
   }
   return result;
}

// исходный код
var s = sum(arr);

// модифицированный код
var s = sum.eval(arr);
То есть, сравнивая исходный и модифицированный код, можно увидеть, что отличия минимальны. Код по прежнему чист, а результат позволяет проанализировать полученную информацию.

Особенности

Данное решение не использует таймеры отчета времени и может выполняться в разных средах, как в окне браузера, так и в самостоятельном приложении. Также содержит некоторый дополнительный код, который решает проблему кроссплатформенности.
Что же было применено дополнительно? В отличия от аналогов, данный пример работает для большинства случаев - JavaScript/JScript. Для этого дополнительно определено несколько полезных свойств:
- Function.prototype.evalCount - целочисленный параметр хранит количество итераций, или количество раз исполнения кода, значение по умолчанию 1000.
- Function.prototype.evalDuration - целочисленный параметр хранит продолжительность выполнения кода.
- Function.prototype.evalPrint = function() - вспомогательная функция для вывода статистики о производительности, учитывает различия сред исполнения и вызывает соответствующий метод для вывода количества итераций и продолжительности исполнения кода.
По умолчанию, производится оценка и выводится время исполнения кода для 1000 итераций. Параметр Function.prototype.evalDuration вычисляется в процессе и не имеет значения по умолчанию.
Естественно, эти параметры можно переопределить, например, изменить количество итераций, или переопределить свой метод отображения статистики. При чем, это можно сделать как глобально через прототип, так и конкретно для определенной функции. Например:
sum.evalCount = 10240; // 10K iterations
var result = sum.eval(1, 2, 3, 4);

Преимущества

Предложенная методика в отличие от аналогов
1. позволяет легко внедрить в свой код возможности оценки производительности с минимальными изменениями основного кода;
2. имеет расширенные возможности контроля;
3. она независима от текущей платформы и позволяет использовать данное расширение без изменений как в среде JavaScript, так и в JScript (Windows Scripting Host).

Полное решение

Решение платформно-независимо. Тестировалось для IE6, IE7, FF2.0.0.15, FF3.0.7 и Windows Scripting Host. Распространяется по лицензии GPL. Листинг исходного кода доступен по этой ссылке. Там же - ссылка на скачивание.

Ссылки по теме

1. John Resig's blog
2. webtoolkit site