import requests
import sys
import re
import socket
'''
Module for getting geoData of a Ip
Adress.
'''
def rightIpPattern(ip):
'''
Checks for the right ipv4 pattern.
'''
return re.match("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$",ip)!=None
def hasInternetConnection(host="8.8.8.8", port=53, timeout=3):
'''
Checks if it's possible to connect with a google sever.
'''
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
return True
except Exception as ex:
print(ex)
return False
def getData(ip,what='country_name'):
'''
Returns the Location datas of the given Ip
what can be:
*region_code
*ip
*time_zone
*city
*country_code
*region_name
*country_name
*metro_code
*latitude
*longtitude
'''
if(hasInternetConnection() and rightIpPattern(ip)):
response = requests.get("http://freegeoip.net/json/"+ip)
json = response.json()
if(what!="everything"):
return json[what]
else:
return json
else:
print("Fail, check Ip adress and you internet connection")
if __name__== "__main__":
print(getData(sys.argv[1],sys.argv[2]))
#yogurt-corner
Snippets & Hacks for everyone [Software Dev NEWS]
Thursday, October 13, 2016
Thursday, July 28, 2016
Fastest sorting algorithm for integers - radixsort
A programmer has often the problem of fast sorting. Which algorithm he/she should take for that type of data. I will show you simply the fastest algorithm but only for sorting integers. I'm talking about the radixsort. But sth like the fastest algorithm doesn't exist for sorting. Because it's always a question of the data type and pattern wich you wan't to sort.
The code is written in python, because nearly every programmer understands it ^^
def radixsort( aList ):
RADIX = 10
maxLength = False
tmp , placement = -1, 1
while not maxLength:
maxLength = True
# declare and initialize buckets
buckets = [list() for _ in range( RADIX )]
# split aList between lists
for i in aList:
tmp = i / placement
buckets[tmp % RADIX].append( i )
if maxLength and tmp > 0:
maxLength = False
# empty lists into aList array
a = 0
for b in range( RADIX ):
buck = buckets[b]
for i in buck:
aList[a] = i
a += 1
# move to next digit
placement *= RADIX
Location:
Zürich, Schweiz
Tuesday, May 10, 2016
How to control the Mouse in Python
You mayby know some of the anoying pseudo viruses wich launches a ghost - mouse on your pc. So how we can do that under Windows with python.
First you need to install the pywin32 package. You can do this of course easely with pip
pip install pywin32
Import:
import win32api, win32con
Mouve mouse:
win32api.SetCursorPos((x,y))
Click Left:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
Click Right:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
Labels:
Control Hardware,
Control Mouse,
Python 3
Location:
Zürich, Schweiz
Monday, May 9, 2016
Why you should learn Python 10 - Reasons
- [1] I'ts easy to learn
Python is completely generic and you won't have much blue code because of the intuitive Syntax. You will also have the most needed libs in the standart package dir, like libs for parsing xml or for sending mail via smtp.
- [2] Python is powerfull
With the package ctypes you can do a lot of things that C also can do. The language itself has so much extended standart packages that python can also be a monster tool for programmers.
- [3] You can use it for webdevelopment
Ever heard about Django? No... this is the framework in which youtube whas written. And yes it's a python framework.
- [4] You can use it for any platform
Python is a interpreted language which works similar to java when you compile the scripts. It uses a just in time debugger. But yeah wherever the interpreter works, python works too. Windows, Linux Mac os x, Unix(BSD Like) and also android.
- [5] Python is needed in de economy
The amount of needed python jobs is now bigger than ever.
- [6] It also can understand java, c# and of course c
There are more than one interpreter. You can use Jython that also anderstand java or IronPython which is compatible with the .Net Framework.
- [7] It's a university language
Python is the most used language at universities. So when you learn it you will always find a snippet in python.
- [8] You will always find the right package
Because it's the most used language at universities, there are thousands of packages for python. Do to everything you wan't.
- [9] Blender
Also when you are a 3D Artist python will be usefull for you. As you mayby know, the python interpreter is a part of Blender.
- [10] Python is fast
It is the fastest interpreted language when you use Cython and write like you should.
Labels:
en,
First programming language,
Python 3
Location:
Zürich, Schweiz
Sunday, May 8, 2016
Debugger for Python
The simplest way to debug a python programm is to use the build in module pdb. It is simple to use:
for more informations : https://docs.python.org/3/library/pdb.html
import pdb import mymodule pdb.run('mymodule.test()')Or: python3 -m pdb myscript.py
for more informations : https://docs.python.org/3/library/pdb.html
Location:
Zürich, Schweiz
Saturday, May 7, 2016
Disassembler for Python bytecode
It's possible to disassemble easely python bytecode. With python onboard tools. In this case the module 'dis'.
>>> def marcin(n):
... print(n)
...
>>> import dis
>>> dis.dis(marcin)
2 0 LOAD_GLOBAL 0 (print)
3 LOAD_FAST 0 (n)
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
>>>
Friday, May 6, 2016
The Top 20 Hidden Features of Python
>Just A summary of the hidden possibilities.
>I will explain them in the following Posts
- Braces
from __future__ import braces
- List slicing
a = [1,2,3,4,5,6] a[2:4] [3,4] a[2:] [3,4,5,6] a[:2] [1,2] a[::] [1,2,3,4,5,6]
- For .. else Syntax
for i in sfoo: if bar(i): #do something break else: return -1
- Yield statement
def primes(numb): while True: if isprime(numb): yield numb numb+=1
- Multiple assignments
a, b = 1, 2 (a, b) = 1, 2 [a, b] = 1, 2
- Argument unpacking
def aMethod(arg1, arg2): # Do something foo = (3, 4) bar = {'y': 3, 'x': 2} aMethod(*point_foo) aMethod(**point_bar)
- Decorators
def print_arguments(function): def wrapper(*args, **kwargs): print 'Arguments:', args, kwargs return function(*args, **kwargs) return wrapper @print_args def write(text): print text
- 'this' Module
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
- Descriptors
class Property(object): def __init__(self, fget): self.fget = fget def __get__(self, obj, type): if obj is None: return self return self.fget(obj)
class MyClass(object): @Property def foo(self): return "Foo!"
- Docstring Tests
- Elipse slicing Syntax
>>> class C(object): ... def __getitem__(self, item): ... return item ... >>> C()[1:2, ..., 3] (slice(1, 2, None), Ellipsis, 3)
- Enumeration
>>> a = ['a', 'b', 'c', 'd', 'e'] >>> for index, item in enumerate(a): print index, item ... 0 a 1 b 2 c 3 d 4 e
- Generator Expressions
>>>x = [n for n in foo if bar(n)]
- In place value swaping
>>>a, b = b, a
- Multi-Line Regex
>>>> pattern = """ ... ^ # beginning of string ... M{0,4} # thousands - 0 to 4 M's ... (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's), ... # or 500-800 (D, followed by 0 to 3 C's) ... (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's), ... # or 50-80 (L, followed by 0 to 3 X's) ... (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's), ... # or 5-8 (V, followed by 0 to 3 I's) ... $ # end of string ... """ >>> re.search(pattern, 'M', re.VERBOSE)
- Named string formatting
print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42} The answer is 42.
- New Types at runtime
>>> NewType = type("NewType", (object,), {"x": "hello"}) >>> n = NewType() >>> n.x "hello"
- try exepet & else
try: #Something to Try Except(#Excetion): #Do something else: #Do sth other finally: #Do always
- .pth files
- with statement
from __future__ import with_statement with open('foo.txt', 'w') as f: f.write('hello!')
Labels:
Hidden features,
Python 3
Location:
Zürich, Schweiz
Subscribe to:
Posts (Atom)