12/12/2017

Removing duplicates in lists using set, python

Simple example using set


>>> t = [1, 2, 3, 5, 6, 7, 8]
>>> t = t + [1]
>>> t = t + [2]

>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1, 2, 3]
>>> list(set(t) - set(s))
[8, 5, 6, 7]

reference : https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists

12/10/2017

Python: Split string with multiple delimiters [duplicate]


String split using delimiter

let's see how to split string using delimiter
There are 2 issues those are single delimiter and multi delimiters.

import re
#single delimiter
inputStr = 'This\nis\nmy\ndesk.'
split_inpuStr = inputStr.split('\n')
print('single',split_inpuStr)

#double delimiters
inputStr2 = 'This\r\nis\nmy\ndesk.'
split_inpuStr2 = re.split('\r\n|\n', inputStr2)
print('double',split_inpuStr2)

#multi delimiters
a = 'Beautiful,is; better*than\nugly'
b = re.split('; |, |\*|\n',a)
print('multi',b)


reference

https://stackoverflow.com/questions/4998629/python-split-string-with-multiple-delimiters
https://stackoverflow.com/questions/10393157/splitting-a-string-with-multiple-delimiters-in-python

python regular auto generator
http://ss2r.marearts.com

Django queryset simple tutorial


I have 4 objects in my table. The table name is 'Post'.



In models.py, the db class is like that:
class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title


So, let's train how to access the db and handle this.
Above all, you have to makemigrations, migrate after adding the db class code.

>python manage.py makemigrations
>python manage.py migrate


----
OK, train to the QuerySet (we call the dango query as QuerySet),
input this command in the console.
>python manage.py shell


OK, so now let's see the some commands
I will introduce very simple and useful commands.


1. show all objects

>from webapp.models import Post
: db import
>Post.objects.all()




2. access specific object

- first object
>Post.objects.all().first()
- last object
>Post.objects.all().last()
- 3rd object
>Post.objects.all()[2]




very easy right? 😴


3. element value change in object and save

> obj = Post.objects.all()[2]
>obj.title = 'a_title_3'
>obj.save()






4. object add and save

>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()


5. Checking for empty queryset in Django

if table_name.objects.all().count() == 0:
     print('none')


6. auto increase primary field

id = models.AutoField(primary_key=True)


7. Query datetime by today, yesterday's date 

visitor table class is like that:
class visitor_ss2r(models.Model):
    id = models.AutoField(primary_key=True)
    count = models.PositiveIntegerField(default=0)
    day_visiting = models.DateField(auto_now=True)

today search
(notice!) import datetime 
visitor.objects.get(day_visiting=datetime.date.today())
or
visitor.objects.filter(day_visiting=datetime.date.today()).count()
yesterday search
today = datetime.date.today()
yesterday = today - datetime.timedelta(days = 1)
visitor.objects.get(day_visiting=today)
or
visitor.objects.filter(day_visiting=yesterday).count()

8. object delete

outdated_day = today - datetime.timedelta(days = 30)
obs = visitor_ss2r.objects.filter(day_visiting=outdated_day)
if len(obs) > 0:
    obs.delete()


9. admin page DB field view

Add def __str__(self): .....  show below code!

class visitor_ss2r(models.Model):
    id = models.AutoField(primary_key=True)
    count = models.PositiveIntegerField(default=0)
    day_visiting = models.DateField(auto_now=True)

    def __str__(self):
        return 'Date: ' + str(self.day_visiting)

then you can see like that in admin page


more detail
in admin.py, we can make column list like that:

class visitor_ss2r_Admin(admin.ModelAdmin):
    list_display = ('id', 'count', 'day_visiting')
admin.site.register(visitor_ss2r, visitor_ss2r_Admin)



R. reference

Fastest way to get the first object from a queryset in django?https://stackoverflow.com/questions/5123839/fastest-way-to-get-the-first-object-from-a-queryset-in-django

Making queries (Django officials page)
https://docs.djangoproject.com/en/2.0/topics/db/queries/




10/19/2017

WebCam Histogram Test, OpenCV

Histogram Test on webcam stream
Refer to below source code..😀

test video


< gist >

< /gitst >



tags : normalize, calcHist, MatND




9/29/2017

openCV Tip, Calculate overlap percent between two rectangle.

Calculate overlap percent between two rectangle




It is not difficult, we just use bit operator : &, |
for more detail information, refer to below source code.

< gist >

< /gist>



9/27/2017

Tip, Add 'Vector (b)' to end of 'Vector (a)'

If you have 2 Vector and you want to add Vector b to end of Vector a, refer to below code. (very simple!)

vector< int > a;
a.push_back(1);
a.push_back(2);
a.push_back(3);

vector< int > b;
b.push_back(4);
b.push_back(5);
b.push_back(6);

a.insert(a.end(), b.begin(), b.end());

int count = 0;
for (auto it : a)
{
printf("a[%d] = %d \n", count++, it);
}



9/24/2017

Tip, How to count number of '0' in element of Matrix(Mat)?

As same with Matlab, we can use inequality ">,<,==,>=,<=".

Firstly, we check equal to '0' or '>0', the result is output to '255' if satisfied.
Divide by 255 then elements have left '0' or '1'
And sum all of the element, then we can get the number of zero.



Source code is here..

Mat a = Mat(5, 5, CV_8UC1);
randn(a, 0, 1);

Mat b = (a == 0) / 255;
Mat c = (a > 0) / 255;

cout << "Input matrix matrix a = " << endl;
cout << a << endl;

cout << "number of 0 = " << sum(b)[0];
cout << ", number of over 0 = " << sum(c)[0] << endl << endl;


cout << "matrix b = " << endl;
cout << b << endl;
cout << "matrix c = " << endl;
cout << c << endl;