Python i przetwarzanie danych z www
Najpierw trzeba oczywiście stronę www pobrać
from urllib2 import urlopen
def get_www(url):
"Get web page html"
try:
content = urlopen(url).read()
return content
except:
return ""
a potem można już zrobić z nią co się chce, np. znaleźć wszystkie odnośniki. Można do tego wykorzystać klasę sgmllib.SGMLParser
from sgmllib import SGMLParser
class URLParser(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.urls = []
def start_a(self, attrs):
href = [v for k, v in attrs if k=='href']
if href:
self.urls.extend(href)
html = get_www("http://impact.arc.nasa.gov/")
parser = URLParser()
parser.feed(html)
print parser.urls
Jeśli potrzebujemy czegoś więcej to warto skorzystać z PyXML
MiKTeX + Uft8
Dzięki projektowi MiKTeX wykorzystanie LaTeX’a w Windows jest bardzo proste. Jeśli jednak ktoś [tak jak ja] pracuje nad tym samym projektem pod różnymi OS’ami może miec kłopoty. Wiekszośc poradników twierdzi bowiem, ze pod Linuxem należy korzystac z kodowania a Latin-2 (ISO 8859-2) a pod Windows cp1250 (Win Latin 2). Dlaczego nie użyc UTF-8? Poniżej przestawiam szablon dokumentu którego z powodzeniem używam
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[OT4]{polski}
\usepackage{bera}
\begin{document}
\end{document}
Trzeba tylko uważac, żeby plik źródłowy nie zawierał BOM (byte order mark).
[C++] Użycie freopen do przekierowania standardowych strumieni
Za pomocą funkcji
#include <cstdio> FILE *freopen(const char *filename, const char *mode, FILE *stream);
możemy dokonac przekierowania standardowych strumieni (stdin, stdout, stderr), co w pewnych sytuacjach może byc bardzo pomocne.
freopen("stdout.txt", "w", stdout);
freopen("stderr.txt", "w", stderr);
[Java] static import
Jedną z nowych rzeczy dodanych w Javie 1.5 jest statyczny import. Umożliwia on dostęp do statycznym metod i pól klasy bez odwoływania się do jej nazwy. Jest on szczególnie przydatny w przypadku klas użytkowych takich jak np java.lang.Math. Możemy wówczas napisać
import static java.lang.Math.*; // double r = cos(PI * theta);
zamiast
double r = Math.cos(Math.PI * theta);
Nie jest to może rewolucja, ale cecha w pewnych sytuacjach bardzo przydatna.
Właściwości w C++
No coż, w standardzie ich po prostu nie ma. Niektóre kompilatory, jak np mój ulubiony MSVC oferują je za pomocą rozszerzeń, inne nie oferują ich wcale. Wspomniany już kompilator MS wspiera je jednak znakomicie.
Składnia jest prosta
__declspec (property (get=nameOfGetFunction, put=nameOfSetFunction)) type propertyName;
np
class Renderer {
private:
ID3D10Device* m_pDevice;
ID3D10Device& GetDevice(){ return *m_pDevice;}
public:
__declspec (property (get=GetDevice)) ID3D10Device& Device;
}
Szablony? Oczywiście.
template<class T>
class vec3 {
public:
inline T get_x() const { return m_v[0]; }
inline T get_y() const { return m_v[1]; }
inline T get_z() const { return m_v[2]; }
inline void set_x(T value) { m_v[0] = value; }
inline void set_y(T value) { m_v[1] = value; }
inline void set_z(T value) { m_v[2] = value; }
__declspec(property(get=get_x,put=set_x)) T x ;
__declspec(property(get=get_y,put=set_y)) T y ;
__declspec(property(get=get_z,put=set_z)) T z ;
private:
T m_v[3];
}
Właściwości wirtualne?
struct Shape {
float computeArea()=0;
__declspec(property(get=computeArea)) float Area;
}
struct Rect : Shape {
Rect(float w, float h): m_w(w),m_h(h) {}
float computeArea() {
return m_w * m_h;
}
private:
float m_w, m_h;
}
struct Circle : Shape {
Circle(float r) : m_radius(r) {}
float computArea() {
return M_PI * m_radius * m_radius;
}
private:
float m_radius;
}
//...
Shape& s = *new Circle(1.0f);
float area = s.Area;
Oczywiście, świat nie jest idealny, więc i rozszerzenie kompilatora __declspec(property) nie jest, m.in
właściwości nie mogą być statyczne a i z szablonami nie zawsze wszystko działa.
Jeśli ktoś potrzebuje rozwiązań nie ograniczonych do jednego kompilatora, rozwiazanie stanowi biblioteka STLSoft Properties .
[Python] Poprawiona funkcja filter
Programowanie funkcyjne w Pythonie sprawia sporo radości
.Istnieje wbudowana funkcja filter
przyjmująca dwa parametry : predykat i listę która zwraca listę składającą się z tych elementów, dla których predykat jest prawdziwy. Za pomocą wyrażeń listowych (ang. list comprehension) jej działanie można opisać następująco
filter(f,seq) := [ x for x in seq if f(x) ]
Np.
>> l = filter ( lambda x: x < 10, xrange(100)) >> print l >> [0,1,2,3,4,5,6,7,8,9]
Trudno jednak używać tej funkcji z bardziej złożonymi warunkami wyboru elementów. Na szczęście rozwiązanie jest proste
import __builtin__
try:
all
except NameError:
def all(iterable):
for element in iterable:
if not element:
return False;
return True
__builtin__.all = all
all = all
def is_iterable(obj):
'''@return True if obj is iterable, False otherwise'''
return hasattr(obj,'__iter__')
def Filter(fncs,seq):
if not is_iterable(fncs):
fncs = (fncs,)
if not is_iterable(seq):
seq = (seq, )
return [ x for x in seq if all(f(x) for f in fncs)]
Mały przykład
def is_lt(n): return lambda x : x < n def is_gt(n): return lambda x : x > n def is_le(n): return lambda x : x <= n def is_ge(n): return lambda x : x >= n def is_odd(n): return n % 2 def is_even(n): return not is_odd(n) l = Filter( ( is_gt(10), is_le(20), is_even ) ,xrange(100 )) print l [12, 14, 16, 18, 20]
[Python] Abstrakcyjne właściwości w pythonie
property to jedna z wbudowanych funkcji pythona (od wersji 2.2.). Zwraca ona obiekt implementujący protokół deskryptorów
class Shape(object):
def __init__(self):
pass
def get_area(self):
pass
Area = property(fget = get_area)
class Rect(Shape):
def __init__(self,w,h):
self.width, self.height = w,h
def get_area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self):
self.radius = r
def get_area(self):
return math.pi * self.r**2;
s = Rect(20,10)
print r.Area
s = Circle(2);
print s.Area
Niestety, ten kod nie zadziała zgodnie z oczekiwaniami. Właściwości nie są abstrakcyjne. To, czego potrzebujemy ( przynajmniej ja ) znajduje się tutaj An Overrideable Alternative to the property Function in Python .
class OProperty(object):
"""Based on the emulation of PyProperty_Type() in Objects/descrobject.c"""
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError, "unreadable attribute"
if self.fget.__name__ == '<lambda>' or not self.fget.__name__:
return self.fget(obj)
else:
return getattr(obj, self.fget.__name__)()
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError, "can't set attribute"
if self.fset.__name__ == '<lambda>' or not self.fset.__name__:
self.fset(obj, value)
else:
getattr(obj, self.fset.__name__)(value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError, "can't delete attribute"
if self.fdel.__name__ == '<lambda>' or not self.fdel.__name__:
self.fdel(obj)
else:
getattr(obj, self.fdel.__name__)()
I wówczas
class Shape(object):
def __init__(self):pass
def get_area(self): pass
Area = OProperty(fget = get_area, doc='Calculate area of shape')
class Rect(Shape):
def __init__(self,w,h):
self.width, self.height = w,h
def get_area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self,r):
self.radius = r
def get_area(self):
return math.pi * self.radius**2
s = Rect(w=10,h=10);print s.Area;
s = Circle(r=1); print s.Area;
Voila!
[D] Struktury w D
W języku C++ różnica pomiędzy klasą i strukturą sprowadza się w zasadzie do domyślnego kwalifikatora dostępu do składowych. W języku D różnica jest jednak głębsza
W D
- struktury są typami wartości (value type) podczas gdy klasy są typami referencyjnymi (reference type).
- brak dziedziczenia i interfejsów
- pamięc domyślnie alokowana na stosie
struct ColorT( T ) {
T r;
T g;
T b;
T a;
};
alias ColorT!(int) Color;
struct Material {
Color ambient;
Color diffuse;
Color specular;
};
Inicjalizacja struktur
Statyczna
static Material material = {
ambient : {255,0,0,255} ,
diffuse : {0,255,0,255},
specular : {255,0,0,255}
};
Dynamiczna
Polega na użyciu istniejącego egzemplarza typu
Material material;
m.diffuse = { r:255, g:127, b:10, a:255};
m.specular = { r:127, g:127, b:0, a:255};
m.ambient = { r:255, g:255, b:0, a:255};
Material material2 = material;
Przeciążony operator opCall
struct Material {
...
static Material opCall(Color amb, Color diff, Color spec) {
Material m ;
m.ambient = amb;
m.specular= spec;
m.diffuse = diff;
return m;
}
...
}
Material material = Material(ambientColor, diffuseColor, specularColor);