Very good one place compilation of most significant Programming Principles - https://java-design-patterns.com/principles/
My notes about CG-art, 3D design, digital photo and programming. If you find these notes useful fill free to contact me or leave comments.
Thursday, 22 July 2021
Java Design Patterns
Monday, 29 July 2013
Алгоритмы и структуры данных, сложность - шпаргалка. (Algorithms and data structures complexity cheatsheet)
Labels:
algorithms complexity,
big-o notation,
cheatsheet
Thursday, 23 May 2013
Простые тесты в Java. Белый ящик. Статический внутренний класс.
Искал как бы по-быстрому написать простые тесты в Java, в итоге осмыслил и скомпоновал найденное в виде этой заметки.
Итак, у нас есть некий класс с функциональностью, которую мы хотим протестировать.
Более того, мы хотим использовать тестирование методом "белого ящика" (white-box). В чём отличие белого ящика от чёрного, можете спросить вы. Отличие в том, что мы знаем что внутри белого ящика и можем использовать эти знания для проверки внутренних состояний объекта. Для этого нам понадобиться добавить в наш класс статический вложенный класс (static nested class).
Вся прелесть как раз в том, что создавая объекты внешнего класса в методах внутреннего класса, мы можем получить доступ к приватным членам этого внешнего класса.
Также создаём статический метод main внутри статического класса для запуска самих тестов.
При этом скомпилированный байт код будет разнесён по двум разным файлам Foo.class и Foo$Test.class и мы можем не включать файлы с тестами в боевую сборку.
Запустить тест можно следующим образом:
Итак, у нас есть некий класс с функциональностью, которую мы хотим протестировать.
Более того, мы хотим использовать тестирование методом "белого ящика" (white-box). В чём отличие белого ящика от чёрного, можете спросить вы. Отличие в том, что мы знаем что внутри белого ящика и можем использовать эти знания для проверки внутренних состояний объекта. Для этого нам понадобиться добавить в наш класс статический вложенный класс (static nested class).
Вся прелесть как раз в том, что создавая объекты внешнего класса в методах внутреннего класса, мы можем получить доступ к приватным членам этого внешнего класса.
public class Foo {
private int value;
private Foo link;
public Foo() {
value = 10;
link = null;
}
public Foo bar(int value) {
this.value = value;
return this;
}
private static class Test {
public static void testConstructor() {
Foo foo = new Foo();
assert (foo.value == 10): "value != 10";
assert (foo.link == null): "link is not null";
}
public static void testBar() {
Foo foo = new Foo();
assert (foo.bar(20) == foo): "returned reference is not itself";
assert (foo.value == 20): "value haven't changed after calling method";
}
public static void main(String[] args) {
Test.testConstructor();
Test.testBar();
System.out.println("OK");
}
}
}
Также создаём статический метод main внутри статического класса для запуска самих тестов.
При этом скомпилированный байт код будет разнесён по двум разным файлам Foo.class и Foo$Test.class и мы можем не включать файлы с тестами в боевую сборку.
Запустить тест можно следующим образом:
> java -ea Foo\$Testгде -ea (enable assertion) для выдачи исключений о невыполнении теста.
Labels:
Java,
static nested class,
tests,
white-box
Sunday, 27 January 2013
Как измерить время выполнения секции кода в python
Пришлось реализовать замер времени выполнения кода и вспомнил один вариант на который когда-то натолкнулся. (К сожалению ссылку на оригинал потерял, но принцип очень простой).
Создаём класс с двумя переопределёнными методами:
И далее в коде используем следующим образом:
Очень хорошая статья поясняющая детали.
Если есть ещё какие-нибудь красивые методы был бы рад о них услышать.
Создаём класс с двумя переопределёнными методами:
import time
class Profiler(object):
def __enter__(self):
self._startTime = time.time()
def __exit__(self, type, value, traceback):
print "Elapsed time: {:.3f} sec".format(time.time() - self._startTime)
И далее в коде используем следующим образом:
with Profiler() as p: // your code to be profiled hereСоответсвенно всё понятно из приведённого примера. При входе в конструкцию with объект создаётся, а при выходе гарантированно завершается. Даже при возникновении исключения.
Очень хорошая статья поясняющая детали.
Если есть ещё какие-нибудь красивые методы был бы рад о них услышать.
Friday, 26 October 2012
Устанговка плагина Blender UV island copy paste.
Windows.
Для работы плагина требуется python-igraph модуль.
На данный момент python-igraph существует собранный только под win32 архитектуру.
Поэтому пока пробуем плагин только с версией Blender под win32.
(Позже я попытаюсь его собрать и под win64.)
Скачиваем архив ICP-win-x32.zip.
Распаковываем его в C:\Users\Username\AppData\Roaming\Blender Foundation\Blender\2.64\scripts\addons\.
Linux.
Для пользователей linux всё немного сложнее, если в вашем дистрибутиве нет готового пакета для python-igraph (нужен под python 3.2). Но это не проблема.
В этом случае потребуется сама библиотека igraph и модуль python-igraph.
Скачиваем архив ICP.zip.
Распаковываем в ~/.config/blender/2.64/scripts/addons/.
Скачиваем архив igraph с исходниками отсюда.
Распаковываем архив, компилируем и устанавливаем.
Скачиваем архив python-igraph с исходниками отсюда.
Распаковываем, собираем и устанавливаем.
После этого копируем сам модуль igraph (директорию с именем igraph со всем её содержимым)
из директории /usr/local/lib64/python3.2/site-packages/python_igraph-0.6-py3.2-linux-x86_64.egg/
в ~/.config/blender/2.64/scripts/addons/modules/.
Загружаем Blender и в разделе User Preferences/Addons находим в разделе Mesh плагин UV island copy paste. Ставим галочку и пробуем как описано в видео.
Для работы плагина требуется python-igraph модуль.
На данный момент python-igraph существует собранный только под win32 архитектуру.
Поэтому пока пробуем плагин только с версией Blender под win32.
(Позже я попытаюсь его собрать и под win64.)
Скачиваем архив ICP-win-x32.zip.
Распаковываем его в C:\Users\Username\AppData\Roaming\Blender Foundation\Blender\2.64\scripts\addons\.
Linux.
Для пользователей linux всё немного сложнее, если в вашем дистрибутиве нет готового пакета для python-igraph (нужен под python 3.2). Но это не проблема.
В этом случае потребуется сама библиотека igraph и модуль python-igraph.
Скачиваем архив ICP.zip.
Распаковываем в ~/.config/blender/2.64/scripts/addons/.
Скачиваем архив igraph с исходниками отсюда.
Распаковываем архив, компилируем и устанавливаем.
tar zxvf igraph-0.6.tar.gz cd igraph-0.6/ ./configure make sudo make install
Скачиваем архив python-igraph с исходниками отсюда.
Распаковываем, собираем и устанавливаем.
tar zxvf python-igraph-0.6.tar.gz cd python-igraph-0.6/ python3 setup.py build sudo python3 setup.py install
После этого копируем сам модуль igraph (директорию с именем igraph со всем её содержимым)
из директории /usr/local/lib64/python3.2/site-packages/python_igraph-0.6-py3.2-linux-x86_64.egg/
в ~/.config/blender/2.64/scripts/addons/modules/.
Загружаем Blender и в разделе User Preferences/Addons находим в разделе Mesh плагин UV island copy paste. Ставим галочку и пробуем как описано в видео.
Если возникают какие-то вопросы или ошибки не стеснясь пишем тут или на мне на почту.
P.S. В виду особенностей представления внутренних данных в Blender этот плагин хорошо работает только на островах с замкнутым швом. Т.е. все вершины в острове должны быть уникальны и не должно быть раздвоенных вершин. В UV редакторе при выбранном режиме sticky selection mode - shared vertex у каждой вершины не должно быть пары. С этими ограничениями плагин можно использовать. (Если после выполнения плагина образовалась каша и какие-то вершины с копировались неправильно, то скорее всего шов не замкнут.) Таким образом плагин требует доработки в архитектуре. Работа продолжается...
Monday, 22 October 2012
Taa-daa! :) I`m proudly present my UV-islands copy-paste plug-in for Blender.
Demo video.
Link for add-on itself will be added soon.
Also I`ve opened bug report about strange behaviour of island select here.
From Blender community site.
Stacking of symmetrical geometry - often times geometry that is exactly the same we will want to use the same image/texture data to save memory however, aligning the uv islands so they exactly overlap can be tedious. This would allow automatic alignment of UV islands for mirrored/symmetrical geometry.
P.S. (Update) Due to some internal data organization in Blender this add-on works well on closed seams only. It means that UV island must have all vertex unique and no vertex split up. In UV editor with sticky selection mode set to shared vertex no vertex should have pair. Add-on can be used in real work but with previous restrictions. So it needs additional design changes for open seams. And work in progress...
P.S.S. For those who would like to use and test it in it's current state, installation instructions (in English) can be found here. Also installation instructions in Russian.
Demo video.
Link for add-on itself will be added soon.
Also I`ve opened bug report about strange behaviour of island select here.
From Blender community site.
Stacking of symmetrical geometry - often times geometry that is exactly the same we will want to use the same image/texture data to save memory however, aligning the uv islands so they exactly overlap can be tedious. This would allow automatic alignment of UV islands for mirrored/symmetrical geometry.
P.S. (Update) Due to some internal data organization in Blender this add-on works well on closed seams only. It means that UV island must have all vertex unique and no vertex split up. In UV editor with sticky selection mode set to shared vertex no vertex should have pair. Add-on can be used in real work but with previous restrictions. So it needs additional design changes for open seams. And work in progress...
P.S.S. For those who would like to use and test it in it's current state, installation instructions (in English) can be found here. Also installation instructions in Russian.
Friday, 31 August 2012
Saturday, 11 August 2012
How to add support for svg icons in PySyde application
First and very important note - svg icons requires xml support
so we need to add next line in our code:
or add QtSvg4.dll and QtXml4.dll in your bin distribution folder. This will include needed libraries in your distribution if you use something like pyinstaller to make executables.
Copy "plugins/imageformats/qsvg4.dll" from your PySide installation folder to your distribution folder.
Add qt.conf file in your bin distribution folder.
so we need to add next line in our code:
from PySide import QtSvg, QtXml
or add QtSvg4.dll and QtXml4.dll in your bin distribution folder. This will include needed libraries in your distribution if you use something like pyinstaller to make executables.
Copy "plugins/imageformats/qsvg4.dll" from your PySide installation folder to your distribution folder.
Add qt.conf file in your bin distribution folder.
[Paths] Prefix = . Binaries = . Plugins = ../plugins Translations = ../translations
Friday, 20 July 2012
WIP. Dreadnought.
Saturday, 14 July 2012
WebGL services to show your 3D models on.
Do you want to share you models with friends? Show your WIP and let spectators to view your model with different angles and in close details? You need only WebGL compatible browser*. I think you like it.
p3d.in
- 3D models in Wavefront (.obj) format
- diffuse, specular and normal (doesn't like bump maps) textures in jpg format not more than 1024x1024px
Sketchfab
- 3D models in Blender (.blend), Collada (.dae), Wavefront (.obj), OpenSceneGraph (.osg, osgt, osgb, ive), 3DS (.3ds), Lightwave (.lwo | .lws), Polygon File Format (.ply), Virtual Reality Modeling Language (.wrl), Open Inventor (.iv), Shape (.shp), Standard Tessellation Language (.stl), Biovision Hierarchy (.bvh), Open Flight (.flt), ac3d (.ac), DirectX (.x), Designer Workbench (.dw), 3DC point cloud (.3dc), carbon graphics Inc (.geo), Generic Tagged Arrays (.gta)
The quick summary - you can post your models in 3D, share it with friends and others. But all models should be prepared and engines renders models with sometimes seen artifacts. Do you know any other free WebGL services like those two? Please let me know in comments.
* Best results I met with Mozilla Firefox and Google Chrome browsers. Opera 12 isn't quite stable with WebGL.
p3d.in
- 3D models in Wavefront (.obj) format
- diffuse, specular and normal (doesn't like bump maps) textures in jpg format not more than 1024x1024px
Sketchfab
- 3D models in Blender (.blend), Collada (.dae), Wavefront (.obj), OpenSceneGraph (.osg, osgt, osgb, ive), 3DS (.3ds), Lightwave (.lwo | .lws), Polygon File Format (.ply), Virtual Reality Modeling Language (.wrl), Open Inventor (.iv), Shape (.shp), Standard Tessellation Language (.stl), Biovision Hierarchy (.bvh), Open Flight (.flt), ac3d (.ac), DirectX (.x), Designer Workbench (.dw), 3DC point cloud (.3dc), carbon graphics Inc (.geo), Generic Tagged Arrays (.gta)
The quick summary - you can post your models in 3D, share it with friends and others. But all models should be prepared and engines renders models with sometimes seen artifacts. Do you know any other free WebGL services like those two? Please let me know in comments.
* Best results I met with Mozilla Firefox and Google Chrome browsers. Opera 12 isn't quite stable with WebGL.
Wednesday, 11 July 2012
WIP. Blender add-on - copy/paste UV islands. Some theory behind.
Here it is example of simple mesh unwrap. As you can see we have 3 pairs of identical UV islands. In most of the cases we can pack each pair in the same UV space thus increasing texture space used for other details.
In 3d-Coat process look like selecting one UV island, pressing Ctrl-C (copy), then selecting similar island and pressing Ctrl-V (paste). Both islands at this moment using the same texture space. If we have more then two islands we can pack them one by one.
The main problem is that we need to find "symmetrical" vertexes for both islands and copy UV coordinates from one vertex to "paired" one.
So how can we do it. After some meditation I found that we need to iteratively compare border loops for both islands vertex by vertex and find shortest path between them - pair with shortest path should be "symmetrical". This concept needs poof code - so I return to this theme as soon as I write simple prototype for future add-on.
In 3d-Coat process look like selecting one UV island, pressing Ctrl-C (copy), then selecting similar island and pressing Ctrl-V (paste). Both islands at this moment using the same texture space. If we have more then two islands we can pack them one by one.
The main problem is that we need to find "symmetrical" vertexes for both islands and copy UV coordinates from one vertex to "paired" one.
So how can we do it. After some meditation I found that we need to iteratively compare border loops for both islands vertex by vertex and find shortest path between them - pair with shortest path should be "symmetrical". This concept needs poof code - so I return to this theme as soon as I write simple prototype for future add-on.
WIP. Blender add-on - copy/paste UV islands. Stacking of symmetrical geometry.
There is nice piece of software called 3D-Coat. Studying tutorials I found nice feature it used - namely copy/paste of UV islands. I found lack of this feature in Blender. Following link you can find more details about this, here I quote only essentials.
P.S. for Russian speaking friends I also placed post here.
Stacking of symmetrical geometry - often times geometry that is exactly the same we will want to use the same image/texture data to save memory however, aligning the uv islands so they exactly overlap can be tedious. This would allow automatic alignment of UV islands for mirrored/symmetrical geometry.I think it can be realized by add-on, and here I will post my WIP on this project.
P.S. for Russian speaking friends I also placed post here.
Subscribe to:
Posts (Atom)


