...
Just my blog

Blog about everything, mostly about tech stuff I made. Here is the list of stuff I'm using at my blog. Feel free to ask me about implementations.

Soft I recommend
Py lib I recommend

I'm using these libraries so you can ask me about them.

Python 3 showing progressbar while subprocess.Popen

Have an interesting case I want to share and save for future. One small problem in this system: https://github.com/trianglesis/BMC_TPL_IDE is showing when some process is running and was not hanged up. Sometimes we need to run a huge amount of checks and tests and would be great to know if something hangs before killing it mannually. I used different scenarios and mostly a module pregressbar2, and this is what I finally can compose:

  1. Make worker which will execute job sorf of randomly:
    1. import time
      import random
      
      print("START SOMETHING")
      
      for i in range(5):
          sec = random.randint(1, 3)
          print("Sleeping for: %d" % sec)
          time.sleep(sec)
          print("Making job, line: %d" % i)
      
      print("END SOMETHING")
  2. Make process executor:
    1. import sys
      import subprocess
      import progressbar
      
      # Draw spinner:
      bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
      
      # Execute some job with multiple lines on stdout:
      p = subprocess.Popen("C:\Python34\python.exe worker.py", shell=True, stdout=subprocess.PIPE,
                                                                           stderr=subprocess.PIPE)
      # Lines will be collected in list:
      result = …

Read...

VK_execute

Для всех страждущих наконец выкладываю нормальные примеры использования VK Script: https://github.com/triaglesis/vk_execute Там все мои примеры и по работе и просто тестовые. Самый быстрый вот такого плана, без внутреннего парсинга. Как только добавляешь внутрь вк скрипта какой-то проверочный код - КПД резко падает. Мой совет - вк_скрипт только для сбора всего "сырого" - дальше обрабатывать уже на сереверной стороне.

var posts_cnt;
var posts;
var post_list = [];
var offset_posts = Args.global_offset_posts;
offset_posts = parseInt(offset_posts);
// var offset_posts = 0;
var run_count = 0;
var iter_count = 20;
while (iter_count > run_count )
    {posts = API.wall.get(
        {"owner_id":(Args.owner_id),
         "domain":(Args.domain),
         "offset":(offset_posts),
         "count":"100",
         "filter":"all",
         "extended":"0",
         "v":"5.42"}
        );
    post_list.push(posts.items);
    offset_posts = offset_posts + 100;
    run_count = run_count + 1;
    posts_cnt = posts.count;
    };
return {"posts_cnt": posts_cnt,
        "run_count":run_count,
        "iter_count":iter_count,
        "offset_posts": offset_posts,
        "posts": post_list};

 

Read...

Django, Apache2, Sublime Text 3 build system and developing process.

At first be sure that you are using this path to run pure apache: http://www.trianglesis.org.ua/django-python-3-4-wamp-apache-2-4-23-pycharm

This topic for those who wants to develop ON THE FLY with python and django and do not want to manually restart dev server each time when code changes AND you don't like built in python web-server and want to run your dev site as it should run on apache.

 

Sublime Text 3

I use it for fast code changing and writting because PyCharm can't work fine with multiline carrets, for example. Also PyCharm is too heavy when you want just copy&paste some features and see how it work on web. So my PyCharm will be used for debug purposes.

I hope you know what is the "Build system" in Sublime, if no - read this first: http://sublimetext.info/docs/en/reference/build_systems.html

  1. Should run Sublime text 3 "as Administrator"
    1. You can run it once with Shift + Left mouse …

Read...

Django + Python 3.4 + WAMP Apache 2.4.23 + Pycharm

Finally worked instance for hosting DEV site code on python and ability to resolve is as "on live" web server just on my laptop.

A lot of different configurations changed but this is one working for me, and maybe can help you also.

Better use EVERYTHING 32 bit for Window, you will suffer if you try to find some needed wheels for python 64bit on Windows 7 64bit.

 

WAMP Apache 2.4.23

Download: wampserver3.0.6_x86_apache2.4.23_mysql5.7.14_php5.6.25-7.0.10 Here

NOTE: Install all needed C++ Redistr. packages which are listed in WAMP install guide!

Download mod_wsgi.so Here or Here (for everythin 32 bit and python 3.4 on Win7 you need: mod_wsgi-py34-VC10.so)

NOTE: Use mod_wsgi version which corresponds your python version! (Above in links you can find more info, just read carefully)

After WAMP install - you don't need to run full programm (I just did not see any advantages of this and disable wampmysql service)

All you …

Read...

Gjango, Pycharm - static files Windows

This topic for those who broke his mind trying to understand how to make Pycharm run Django with static files I've made it, but be carefull it can break your mind too!

The settings

I use the most portable way to configure settings - so I can move it into centos web server without paths changes Win\Unix (I HOPE). There are common DIRs

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# BASE DIR: D:\Projects\CODE\WEB\sites\www\smm_tools\smm_site
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# PROJECT_ROOT:     D:\Projects\CODE\WEB\sites\www\smm_tools\smm_site\main_code
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
#Static root:      D:\Projects\CODE\WEB\sites\www\smm_tools\smm_site\static
STATIC_URL = '/static/'

Looks like ot works, but in really weird way:

  • static files are working fine
  • web page as template is loading
  • some scc and js are loading and some are not

Working css:

In works in different ways - this is one of them which I think correct.

In HTML code:

<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet" type="text/css">
<link href="{% static …

Read...

Windows mirrored volume and hard reset

When you doing a hardware reset for Windows Server 2012 Hyper-V with RAID1 you may catch "Volume Sync" For me to remember: http://serverfault.com/questions/107636/how-to-view-status-of-software-raid-1-resynching Screenshot_250

Read...

Пост с именинниками Вконтакте

Публикация поста с именинниками Вконтакте:

py_vk Старый скриптец, который я использовал около года назад для выборки именинников и публикации поста с ними на стену сообществ Вконтакте. Выкладываю в публичный доступ, так как морально он устарел и код в нем выглядит ужасно, но подходит чисто для образовательных целей и "авось кому пригодится" мне бы он помог на первых порах изучения, может быть … [su_quote]"На тобі боже, що мені негоже."[/su_quote] Сам код можете смотреть здесь: В ближайшие дни, недели, месяцы я буду выкладывать все эти прошлые поделки, по мере того, как полностью перепишу их на новый манер, сейчас у меня основная задача - полностью унифицировать эти отрывки кода и сделать из них полноценную систему управления и автоматизации, поэтому, эти вот отрывки сами по себе уже никакой ценности не несут для меня, но могут кому-то помочь. По себе знаю, что даже кривой но рабочий пример какой-то вещи - может помочь продвинуться в понимании каких-то …

Read...

vk execute wall get comments automation

Как использовать vk execute для получения всех комментариев со всех постов?

py_vk Как и обещал, пришло время выложить исходники (исподники) скриптов, которые я использую для собирания комментов с постов в группе. [su_note]Почему "исподники"? Потому что этот самый код на самом деле такая глючная тварь и такой "грязный" что его стыдно показывать на людях![/su_note] [su_quote]Эту конструкцию я использую в двух модулях, один собирает статистику, другой удаляет комментарии, если они оставлены не участником группы\сообщества. Обновляться и рассматриваться эта конструкция будет в ключе использования её именно как парсилки комментариев, для последующего удаления оных. Главная проблема заключалась в том, что возвращался крайне запутанный список, в котором могли возникать пробелы, из-за которых удалялись не те комментарии, которые следовало бы удалять.[/su_quote] Суть в следующем, у вас есть группа, в которой есть посты, в которых есть комментарии. Вначале вы отбираете ТОЛЬКО те посты, в которых комментов больше нуля и формируете их них список, разделенный запятыми, это …

Read...

Python schedule how to

Задачка на вечер: Дано: задание, которое нужно выполнять в заданные промежутки времени, модуль Python schedule. Задача: запускать одну и ту же задачу с разными значениями offset раз в 10 сек, так, чтобы 0ffset=119 запускался в 10 сек от начала каждой минуты, offset=219 на 20й секунде каждой минуты и так далее. Все что пока смог сделать - заставить выполняться задачу каждую 10ю секунду, НО! это грозит тем, что каждые 10 сек в очередь добавляется каждая след. задача, так что может выполняться все куда чаще, чем раз в 10 сек. Есть идея - сделать задержку в 10 сек после каждого добавления задачи в очередь, тогда может получиться задержка в 20 сек, потом выполнение подряд нескольких задач, и снова 20 сек задержки. Сломал голову себе, сломаю и вам.

from time import strftime, sleep
import schedule


def del_comments_offset(offset):
    print("Func start")
    try:
        delete_comments_older(logFile, token, tk_owner_id, tk_group_id, tk_domain, offset)
    except:
        log_block("ERROR!!! : Connection error!")

offsets = …

Read...

Oh my gosh BACULA config

Recently finished bacula config and run first one successfully! I'm really do not understand now, why does this tool have a complicated system with batch of daemons and modules. For my opinion, backup tool just should know from where to wherever make a backup and how often. But for further usage and remember this config, I'll add it here. [caption id="" align="alignnone" width="428"]Bacula config Bacula config[/caption]   Is is just a reminder, not a how-to, just want to not forget this. Job configs is not so complicate, intuitively understandable.

Director

bacula-dir.conf

[su_spoiler title="Code" icon="chevron"]

Director {                            # define myself
  Name = tet-redmine-dir
  DIRport = 9101
  QueryFile = "/etc/bacula/scripts/query.sql"
  WorkingDirectory = /var/lib/bacula
  PidDirectory = "/var/run/bacula"
  Maximum Concurrent Jobs = 1
  Password = "tet-redmine-director"         # Console password
  Messages = Daemon
  DirAddress = 127.0.0.1
}
Storage {
  Name = File
# Do not use "localhost" here
  Address = 127.0.0.1
  SDPort = 9103
  Password = tet-redmine-storage
  Device …

Read...