Skip to content

Instantly share code, notes, and snippets.

View bogsio's full-sized avatar

George-Bogdan Ivanov bogsio

View GitHub Profile
@bogsio
bogsio / snippet_1.py
Created October 28, 2013 19:29
Understanding Python descriptors #1
class Student(models.Model):
email = models.EmailField()
...
s = Student()
s.email = "[email protected]"
@bogsio
bogsio / snippet_2.py
Created October 28, 2013 19:30
Understanding Python descriptors #2
from validate_email import validate_email
class EmailField(object):
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
validate_email(value)
self.value = value
@bogsio
bogsio / snippet_3.py
Created October 28, 2013 19:31
Understanding Python descriptors #3
user1 = User()
user1.email = '123' # Throws exception
user1.email = '[email protected]'
print user1.email # [email protected]
user2 = User()
user2.email = '[email protected]'
print user2.email # [email protected]
print user1.email # [email protected] !!!
@bogsio
bogsio / snippet_4.py
Created October 28, 2013 19:32
Understanding Python descriptors #4
class EmailField(object):
__current_id = 0 # unique id of the instance
__email_dict = {} # dict containing all email values
__dict_key = "__email_field_key" # name of member attached to instances
def __get__(self, instance, owner):
if not hasattr(instance, self.__class__.__dict_key):
return None
# Retrieve the email value from the dict
@bogsio
bogsio / snippet_5.py
Created October 28, 2013 19:32
Understanding Python descriptors #5
class User(object):
email = EmailField()
...
class Company(object):
contact = EmailField()
...
user1 = User()
@bogsio
bogsio / asserts.py
Created October 28, 2013 19:36
test cases for majority
assert(majority([]) is None)
assert(majority(None) is None)
assert(majority([1, 2, 3]) is None)
assert(majority([3, 3, 3]) == 3)
assert(majority([1, 2, 3, 3, 3]) == 3)
assert(majority([1, 2, 3, 4, 5]) is None)
assert(majority([1, 3, 2, 3, 3, 6, 5, 8, 3, 3, 3, 6, 3]) == 3)
@bogsio
bogsio / majority.py
Created October 28, 2013 19:37
majority
def majority(collection):
if not collection:
return None
# initialize a candidate
candidate = collection[0]
chances = 1
# go through the rest of the elements
for c in collection[1:]:
CREATE TABLE posts (
post_id SERIAL PRIMARY KEY,
title text,
content text
);
INSERT INTO
posts(title, content)
VALUES('This is my first post',
'We are going to have so much fun!')
SELECT *
FROM posts
WHERE content @@ 'watch'
SELECT *
FROM posts
WHERE to_tsvector(content) @@ to_tsquery('english', 'watch');