analitics

Pages

Monday, April 2, 2018

The jdoodle online tool for python 3.

This online tool from jdoodle website lets you to programming online with python 3 version.
To see all python modules used by this editor just add this python script and use Execute button.
import sys
import os 
print(help('modules'))

Tuesday, March 20, 2018

Python 3.6.4 : Testing PyQt5 with Spyder I.D.E.

Today I tested the PyQt5 python module with python version 3.6.4.
The script was created and tested with Spyder I.D.E. version 3.2.8.
The PyQt5 version is:
from PyQt5.Qt import PYQT_VERSION_STR
print("PyQt version:", PYQT_VERSION_STR)
PyQt version: 5.9.2
This is the python script:
import sys
from PyQt5.QtWidgets import (QWidget, QCalendarWidget,
    QLabel, QApplication)
from PyQt5.QtCore import QDate
 
class Calendar(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        calendar = QCalendarWidget(self)
        calendar.setGridVisible(True)
        calendar.move(0, 15)
        calendar.clicked[QDate].connect(self.showDate)
        calendar.currentPageChanged[int, int].connect(self.currentPageChanged)
 
        self.lbl = QLabel(self)
        date = calendar.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(0, 0)
 
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('Calendar')
        self.show()
 
    def showDate(self, date):
        self.lbl.setText(date.toString())
 
    def currentPageChanged(self, year, month):
        print(year, month)
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    calendar_test = Calendar()
    sys.exit(app.exec_())
The result of this script is:

Saturday, March 17, 2018

The Google Cloud SDK - part 003 .

The webapp2 is a lightweight Python web framework compatible with Google App Engine’s.
The webapp2 project, by Rodrigo Moraes, started as a fork of the App Engine web app framework.
The webapp2 includes a number of features such as improved support for URI routing, session management and localization.
You can see google documentation about this python module this link.
They say:
"webapp2 is compatible with the WSGI standard for Python web applications. You don't have to use webapp2 to write Python applications for App Engine. Other web application frameworks, such as Django, work with App Engine, and App Engine supports any Python code that uses the CGI standard. "
This is default start python example from Google Cloud SDK tested in the last tutorial.
import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, World!')

app = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)
Remember how to deploy your project to google:
C:\Python27>cd python-docs-samples\appengine\standard\hello_world

C:\Python27\python-docs-samples\appengine\standard\hello_world>gcloud app deploy app.yaml
Services to deploy:

descriptor:      [C:\Python27\python-docs-samples\appengine\standard\hello_world\app.yaml]
source:          [C:\Python27\python-docs-samples\appengine\standard\hello_world]
target project:  [xxxxxx]
target service:  [default]
target version:  [xxxxxxxxxxxxx]
target url:      [https://xxxxxx.appspot.com]


Do you want to continue (Y/n)?  y

Beginning deployment of service [default]...
Now I make some changes into main.py file to show you how easy is to use it.
This file: main.py is set into setting file app.yaml like the script: main.app.
Let's make some changes.

The default project is set with --promote true the result is: after a number of uploads you got this error:
ERROR: (gcloud.app.deploy) Error Response: [400] Your app may not have more than 15 versions.
Please delete one of the existing versions before trying to create a new version.
...
To fix go to App Engine - Versions with selected versions and press Delete button.
Then you can make the upload with the command :
gcloud app deploy app.yaml
Also, you can use this:
gcloud app deploy app.yaml --stop-previous-version
Some info about your project can be seen with this command:
gcloud config list
You can see the gcloud versions with:
gcloud version
I tested also with python version 3.6.4 :
C:\Python364\Scripts>pip install webapp2
Requirement already satisfied: webapp2 in c:\python364\lib\site-packages
      2 python-dateutil-2.7.0 setuptools-39.0.0 

Wednesday, March 14, 2018

The regex online tool for python and any programming languages.

Today I tested this online tool.
Is a tool for a regular expression (regex or regexp for short) for many programming languages.
These programming languages are php, javascript, golang and python.
The tool is easy to use it.
First, you need to select the programming language that is used for regular expression.
The next step is to put the regular expression into the edit box and add your text to be parsed by this regular expression.
For example, if you use this inputs for a regular expression:
([a-zA-Z]+) \d+
and this text example:
March 7 1976, June 1, August 9, Dec 25
the result output will be this:
March , June , August , Dec

Sunday, March 11, 2018

Python 3.6.4 : Testing OpenCV default GrabCut algorithm.

The main goal for me was to test the new install of python 3.6.4 and python modules with Windows operating system version 8.1.
For this tutorial, I chose these python modules: cv2, numpy and matplotlib .
I have tested the GrabCut algorithm article from here.
The article comes with a python script that includes the modules I tested in this programming language.
They tell us:
User inputs the rectangle. Everything outside this rectangle will be taken as sure background (That is the reason it is mentioned before that your rectangle should include all the objects). Everything inside rectangle is unknown. Similarly any user input specifying foreground and background are considered as hard-labelling which means they won't change in the process.
From my point of view, it is not a very successful algorithm to crop off the background but is working well.
import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('test_python_opencv.jpg')
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (57,58,476,741)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]

plt.imshow(img),plt.colorbar(),plt.show()
The intersection areas are eliminated exactly as in the documentation.
See my first test on an image taken from the internet.

Saturday, March 3, 2018

News: The Spyder IDE - new release .

Many python users use the Spyder IDE.
This IDE comes with many features and is easy to use, see Wikipedia page:
Spyder (formerly Pydee[3]) is an open-source cross-platform integrated development environment (IDE) for scientific programming in the Python language. Spyder integrates NumPy, SciPy, Matplotlib and IPython, as well as other open source software.[4][5] It is released under the MIT license.[6]
Six days ago, a release of this IDE with version 3.2.7 was announced.
This IDE can be download from GitHub page.

Friday, February 23, 2018

Use IMDB website with IMDbPY python module .

This python package is written in pure Python 3 to access the IMDb's database and used it.

You can read about this python module from GitHub docs webpage
The development team comes with this DISCLAIMER:
# DISCLAIMER

IMDbPY and the authors are not affiliated with Internet Movie Database Inc.

IMDb is a trademark of Internet Movie Database Inc. and all contents
and data included on the IMDb's site is the property of IMDb or its
content suppliers and protected by United States and international
copyright laws.

Please, read the IMDb's conditions of use in their website:
- http://www.imdb.com/conditions
- http://www.imdb.com/licensing
- any other notice in the http://www.imdb.com/ site.

First I start the install process with the pip tool:
C:\Python364\Scripts>pip install IMDbPY
Requirement already satisfied: IMDbPY in c:\python364\lib\site-packages
Requirement already satisfied: lxml in c:\python364\lib\site-packages (from IMDbPY)
Requirement already satisfied: sqlalchemy-migrate in c:\python364\lib\site-packages (from IMDbPY)
Requirement already satisfied: SQLAlchemy in c:\python364\lib\site-packages (from IMDbPY)
Requirement already satisfied: pbr>=1.8 in c:\python364\lib\site-packages (from sqlalchemy-migrate->IMDbPY)
Requirement already satisfied: decorator in c:\python364\lib\site-packages (from sqlalchemy-migrate->IMDbPY)
Requirement already satisfied: six>=1.7.0 in c:\python364\lib\site-packages (from sqlalchemy-migrate->IMDbPY)
Requirement already satisfied: sqlparse in c:\python364\lib\site-packages (from sqlalchemy-migrate->IMDbPY)
Requirement already satisfied: Tempita>=0.4 in c:\python364\lib\site-packages (from sqlalchemy-migrate->IMDbPY)
This is my source code to test it and working well.
# start with IMDb python class
from imdb import IMDb
imd = IMDb('http')
print("-===-")
# search movies by title
# and show the long imdb canonical title and movieID of the results.
title = imd.search_movie("Under the Dome")
for item in title:
   print(item['long imdb canonical title'], item.movieID)
print("-===-")
# search for a person
for person in imd.search_person("Ana de Armas"):
    print(person.personID, person['name'])
print("-===-")
# get 5 movies tagged with a keyword
movies_keyword = imd.get_keyword('novel', results=5)
for item in movies_keyword:
   print(item['long imdb canonical title'], item.movieID)
print("-===-")
# get top 250  from top movies
top250 = imd.get_top250_movies()
for item in top250:
   print(item['long imdb canonical title'], item.movieID)
print("-===-")
print("top 250 -=> ")
# get bottom 100 from top movies
bottom100 = imd.get_bottom100_movies()
print("bottom 100 -=> ")
for item in top250:
   print(item['long imdb canonical title'], item.movieID)

Thursday, February 8, 2018

Python 2.7 : Testing the pefile python module.

The pefile is a python module to read and work with PE (Portable Executable) files.
The install of this python module is very easy with the pip tool.
I tested the default example create with FASM to see if this is working well:
This is the source code:
; Example of 64-bit PE program
format PE64 GUI
entry start

section '.text' code readable executable

  start:
        sub     rsp,8*5         ; reserve stack for API use and make stack dqword aligned

        mov     r9d,0
        lea     r8,[_caption]
        lea     rdx,[_message]
        mov     rcx,0
        call    [MessageBoxA]

        mov     ecx,eax
        call    [ExitProcess]

section '.data' data readable writeable

  _caption db 'Win64 assembly program',0
  _message db 'Hello World!',0

section '.idata' import data readable writeable

  dd 0,0,0,RVA kernel_name,RVA kernel_table
  dd 0,0,0,RVA user_name,RVA user_table
  dd 0,0,0,0,0

  kernel_table:
    ExitProcess dq RVA _ExitProcess
    dq 0
  user_table:
    MessageBoxA dq RVA _MessageBoxA
    dq 0

  kernel_name db 'KERNEL32.DLL',0
  user_name db 'USER32.DLL',0

  _ExitProcess dw 0
    db 'ExitProcess',0
  _MessageBoxA dw 0
    db 'MessageBoxA',0  
The python script I used to test this python module is this:
import sys
from sys import argv
import mmap
import pefile

fp = open(argv[1],"r")
map = mmap.mmap(fp.fileno(),0,access=mmap.ACCESS_READ)
pe = pefile.PE(data=map[:])
print pe
The output is this:
C:\Python27>python.exe pe.py PE64DEMO.EXE
----------Parsing Warnings----------

Byte 0x00 makes up 87.5488% of the file's contents. This may indicate truncation / malformation.

----------DOS_HEADER----------

[IMAGE_DOS_HEADER]
0x0 0x0 e_magic: 0x5A4D
0x2 0x2 e_cblp: 0x80
0x4 0x4 e_cp: 0x1
0x6 0x6 e_crlc: 0x0
0x8 0x8 e_cparhdr: 0x4
0xA 0xA e_minalloc: 0x10
0xC 0xC e_maxalloc: 0xFFFF
0xE 0xE e_ss: 0x0
0x10 0x10 e_sp: 0x140
0x12 0x12 e_csum: 0x0
0x14 0x14 e_ip: 0x0
0x16 0x16 e_cs: 0x0
0x18 0x18 e_lfarlc: 0x40
0x1A 0x1A e_ovno: 0x0
0x1C 0x1C e_res:
0x24 0x24 e_oemid: 0x0
0x26 0x26 e_oeminfo: 0x0
0x28 0x28 e_res2:
0x3C 0x3C e_lfanew: 0x80

----------NT_HEADERS----------

[IMAGE_NT_HEADERS]
0x80 0x0 Signature: 0x4550

----------FILE_HEADER----------

[IMAGE_FILE_HEADER]
0x84 0x0 Machine: 0x8664
0x86 0x2 NumberOfSections: 0x3
0x88 0x4 TimeDateStamp: 0x5A1954AF [Sat Nov 25 11:31:59 2017 UTC]
0x8C 0x8 PointerToSymbolTable: 0x0
0x90 0xC NumberOfSymbols: 0x0
0x94 0x10 SizeOfOptionalHeader: 0xF0
0x96 0x12 Characteristics: 0x2F
Flags: IMAGE_FILE_EXECUTABLE_IMAGE, IMAGE_FILE_LARGE_ADDRESS_AWARE, IMAGE_FILE_LINE_NUMS_STRIPPED, IMAGE_FILE_LOCAL_SYMS_STRIPPED, IMAGE_FILE_RELOCS_STRIPPED

----------OPTIONAL_HEADER----------

[IMAGE_OPTIONAL_HEADER64]
0x98 0x0 Magic: 0x20B
0x9A 0x2 MajorLinkerVersion: 0x1
0x9B 0x3 MinorLinkerVersion: 0x49
0x9C 0x4 SizeOfCode: 0x200
0xA0 0x8 SizeOfInitializedData: 0x400
0xA4 0xC SizeOfUninitializedData: 0x0
0xA8 0x10 AddressOfEntryPoint: 0x1000
0xAC 0x14 BaseOfCode: 0x1000
0xB0 0x18 ImageBase: 0x400000
0xB8 0x20 SectionAlignment: 0x1000
0xBC 0x24 FileAlignment: 0x200
0xC0 0x28 MajorOperatingSystemVersion: 0x1
0xC2 0x2A MinorOperatingSystemVersion: 0x0
0xC4 0x2C MajorImageVersion: 0x0
0xC6 0x2E MinorImageVersion: 0x0
0xC8 0x30 MajorSubsystemVersion: 0x5
0xCA 0x32 MinorSubsystemVersion: 0x0
0xCC 0x34 Reserved1: 0x0
0xD0 0x38 SizeOfImage: 0x4000
0xD4 0x3C SizeOfHeaders: 0x200
0xD8 0x40 CheckSum: 0xECAF
0xDC 0x44 Subsystem: 0x2
0xDE 0x46 DllCharacteristics: 0x0
0xE0 0x48 SizeOfStackReserve: 0x1000
0xE8 0x50 SizeOfStackCommit: 0x1000
0xF0 0x58 SizeOfHeapReserve: 0x10000
0xF8 0x60 SizeOfHeapCommit: 0x0
0x100 0x68 LoaderFlags: 0x0
0x104 0x6C NumberOfRvaAndSizes: 0x10
DllCharacteristics:

----------PE Sections----------

[IMAGE_SECTION_HEADER]
0x188 0x0 Name: .text
0x190 0x8 Misc: 0x2D
0x190 0x8 Misc_PhysicalAddress: 0x2D
0x190 0x8 Misc_VirtualSize: 0x2D
0x194 0xC VirtualAddress: 0x1000
0x198 0x10 SizeOfRawData: 0x200
0x19C 0x14 PointerToRawData: 0x200
0x1A0 0x18 PointerToRelocations: 0x0
0x1A4 0x1C PointerToLinenumbers: 0x0
0x1A8 0x20 NumberOfRelocations: 0x0
0x1AA 0x22 NumberOfLinenumbers: 0x0
0x1AC 0x24 Characteristics: 0x60000020
Flags: IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ
Entropy: 0.540255 (Min=0.0, Max=8.0)
MD5 hash: 54edeb1437149ccc09183b623e3be7b8
SHA-1 hash: c473f3db5ca81084db3489ab3519832ded9cc28c
SHA-256 hash: 74e9ff7d6902292d9a8ad93174aef46596f8f1fe9eb5dd72b9ebc99f8bd2ecfb
SHA-512 hash: 070610baa66d6efcbb2cc7e935c2afd2686068818c00b772b3e62de103389cecbc6c309976e10860a974532a1018fba9da50effb64c60f533433dbb808ba088c

[IMAGE_SECTION_HEADER]
0x1B0 0x0 Name: .data
0x1B8 0x8 Misc: 0x24
0x1B8 0x8 Misc_PhysicalAddress: 0x24
0x1B8 0x8 Misc_VirtualSize: 0x24
0x1BC 0xC VirtualAddress: 0x2000
0x1C0 0x10 SizeOfRawData: 0x200
0x1C4 0x14 PointerToRawData: 0x400
0x1C8 0x18 PointerToRelocations: 0x0
0x1CC 0x1C PointerToLinenumbers: 0x0
0x1D0 0x20 NumberOfRelocations: 0x0
0x1D2 0x22 NumberOfLinenumbers: 0x0
0x1D4 0x24 Characteristics: 0xC0000040
Flags: IMAGE_SCN_CNT_INITIALIZED_DATA, IMAGE_SCN_MEM_READ, IMAGE_SCN_MEM_WRITE
Entropy: 0.627189 (Min=0.0, Max=8.0)
MD5 hash: 6684d4efed7dc864e5bbb0280faa841b
SHA-1 hash: 0214a59237a9020d3fa41419107a59f276a95e5f
SHA-256 hash: 23ae47e7bfb842935b35775428fe9c5df5c3f46fa46c2da2e93a27ba031ae091
SHA-512 hash: 60eeefcb47e1e63584342049a66d4539ab4b580190faf9d2629e0db1336933835c207e419060cce08cfec430e2f1e13a90cac7abfb05679ed5d84dac8997f12f

[IMAGE_SECTION_HEADER]
0x1D8 0x0 Name: .idata
0x1E0 0x8 Misc: 0x90
0x1E0 0x8 Misc_PhysicalAddress: 0x90
0x1E0 0x8 Misc_VirtualSize: 0x90
0x1E4 0xC VirtualAddress: 0x3000
0x1E8 0x10 SizeOfRawData: 0x200
0x1EC 0x14 PointerToRawData: 0x600
0x1F0 0x18 PointerToRelocations: 0x0
0x1F4 0x1C PointerToLinenumbers: 0x0
0x1F8 0x20 NumberOfRelocations: 0x0
0x1FA 0x22 NumberOfLinenumbers: 0x0
0x1FC 0x24 Characteristics: 0xC0000040
Flags: IMAGE_SCN_CNT_INITIALIZED_DATA, IMAGE_SCN_MEM_READ, IMAGE_SCN_MEM_WRITE
Entropy: 0.996929 (Min=0.0, Max=8.0)
MD5 hash: 073b9b0656f7ca77d968f183a1ceb909
SHA-1 hash: acefe438c7bfef7362b87519349c5a7b251aa43d
SHA-256 hash: 016761b2d3b31ed8eeddccc9f56e6338978171a0082c066cbf2b28cecd77566a
SHA-512 hash: a5fb7ace9108f63c96c9da239fc5077106cf3ffe8e31a1ab0a11b589a8e6af9e66d23c38060c157a3e34125bc5af495c770e48bc00172a5c8ec78b34794628b3

----------Directories----------

[IMAGE_DIRECTORY_ENTRY_EXPORT]
0x108 0x0 VirtualAddress: 0x0
0x10C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_IMPORT]
0x110 0x0 VirtualAddress: 0x3000
0x114 0x4 Size: 0x90
[IMAGE_DIRECTORY_ENTRY_RESOURCE]
0x118 0x0 VirtualAddress: 0x0
0x11C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_EXCEPTION]
0x120 0x0 VirtualAddress: 0x0
0x124 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_SECURITY]
0x128 0x0 VirtualAddress: 0x0
0x12C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_BASERELOC]
0x130 0x0 VirtualAddress: 0x0
0x134 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_DEBUG]
0x138 0x0 VirtualAddress: 0x0
0x13C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_COPYRIGHT]
0x140 0x0 VirtualAddress: 0x0
0x144 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_GLOBALPTR]
0x148 0x0 VirtualAddress: 0x0
0x14C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_TLS]
0x150 0x0 VirtualAddress: 0x0
0x154 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG]
0x158 0x0 VirtualAddress: 0x0
0x15C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT]
0x160 0x0 VirtualAddress: 0x0
0x164 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_IAT]
0x168 0x0 VirtualAddress: 0x0
0x16C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]
0x170 0x0 VirtualAddress: 0x0
0x174 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR]
0x178 0x0 VirtualAddress: 0x0
0x17C 0x4 Size: 0x0
[IMAGE_DIRECTORY_ENTRY_RESERVED]
0x180 0x0 VirtualAddress: 0x0
0x184 0x4 Size: 0x0

----------Imported symbols----------

[IMAGE_IMPORT_DESCRIPTOR]
0x600 0x0 OriginalFirstThunk: 0x0
0x600 0x0 Characteristics: 0x0
0x604 0x4 TimeDateStamp: 0x0 [Thu Jan 01 00:00:00 1970 UTC]
0x608 0x8 ForwarderChain: 0x0
0x60C 0xC Name: 0x305C
0x610 0x10 FirstThunk: 0x303C

KERNEL32.DLL.ExitProcess Hint[0]

[IMAGE_IMPORT_DESCRIPTOR]
0x614 0x0 OriginalFirstThunk: 0x0
0x614 0x0 Characteristics: 0x0
0x618 0x4 TimeDateStamp: 0x0 [Thu Jan 01 00:00:00 1970 UTC]
0x61C 0x8 ForwarderChain: 0x0
0x620 0xC Name: 0x3069
0x624 0x10 FirstThunk: 0x304C

USER32.DLL.MessageBoxA Hint[0]

Sunday, February 4, 2018

The collections python module .

This module named collections implements some nice data structures which will help you to solve various real-life problems.
Let's start to see the content of this python module:
C:\Users\catafest>python

C:\Users\catafest>cd C:\Python27\

C:\Python27>python
Python 2.7 (r27:82525, Jul  4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> from collections import *
>>> dir(collections)
['Callable', 'Container', 'Counter', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView',
 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'OrderedDict', 'Sequence',
 'Set', 'Sized', 'ValuesView', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__'
, '_abcoll', '_chain', '_eq', '_heapq', '_ifilter', '_imap', '_iskeyword', '_itemgetter', '_repeat', 
'_starmap', '_sys', 'defaultdict', 'deque', 'namedtuple']
Now I will tell you about some
First is Counter and is a direct subclass which helps to count hashable objects.
The elements are stored as dictionary keys and counts are stored as values which can be zero or negative.
Next is defaultdict and is a dictionary object which provides all methods provided by the dictionary.
This takes the first argument (default_factory) as default data type for the dictionary.
The namedtuple helps to have the meaning of each position in a tuple.
This allows us to code with better readability and self-documenting code.
Let's try some examples:
>>> from collections import Counter
>>> from collections import defaultdict
>>> from collections import namedtuple
>>> import re
>>> path = 'C:/yara_reg_rundll32.txt'
>>> output = re.findall('\w+', open(path).read().lower())
>>> Counter(output).most_common(5)
[('a', 2), ('nocase', 2), ('javascript', 2), ('b', 2), ('rundll32', 2)]
>>> 
>>> d = defaultdict(list)
>>> colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> for k, v in colors:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> 
>>> Vertex = namedtuple('vertex', ['x', 'y'])
>>> v = Vertex(5,y = 9)
>>> v
vertex(x=5, y=9)
>>> v.x*v.y
45
>>> v[0]
5
>>> v[0]+v[1]
14
>>> x,y = v
>>> v
vertex(x=5, y=9)
>>> x
5
>>> y
9
>>>
The content of the yara_reg_rundll32.txt file is:
rule poweliks_rundll32_exe_javascript
{
meta:
description = "detect Poweliks' autorun rundll32.exe javascript:..."
string:
$a = "rundll32.exe" nocase
$b = "javascript" nocase
condition:
$a and $b
}

I used vertex variables into my example because can be used with Blender 3D.
You can see many examples at official documentation website.





Sunday, January 14, 2018

The trinket website for learning.

This website comes with this feature:
Trinket lets you run and write code in any browser, on any device.
Trinkets work instantly, with no need to log in, download plugins, or install software.
Easily share or embed the code with your changes when you're done.

  • Just create Your Free Account then use the web interface to play with turtle python module:
  • Trinket lets you run and write code in any browser, on any device.
  • Trinkets work instantly, with no need to log in, download plugins, or install software.
  • Easily share or embed the code with your changes when you're done.

Friday, January 12, 2018

Python 2.7 : Python and BigQuery service object.

Here's another tutorial about python and google. I thought it would be useful for the beginning of 2018.
The Google team tell us:

What is BigQuery?

Storing and querying massive datasets can be time consuming and expensive without the right hardware and infrastructure. Google BigQuery is an enterprise data warehouse that solves this problem by enabling super-fast SQL queries using the processing power of Google's infrastructure. Simply move your data into BigQuery and let us handle the hard work. You can control access to both the project and your data based on your business needs, such as giving others the ability to view or query your data.


This tutorial it follows more precisely the steps from here.
First of all, you must create an authentication file by using the Create service account from your Google project.
Go to Google Console, navigate to the Create service account key page.
From the Service account drop-down, select the New service account.
Input a name into the form field.
From the Role drop-down, select Project and Owner.
The result is a JSON file type (this is for authenticating with google) download it renames and put into your project folder.
Like into the next image:

Now, select from the left area the Library does add the BigQuery API, try this link.
Search for BigQuery API and then use the button ENABLE to use it.
The next step is to install these python modules: pyopenssl and google-cloud-bigquery.
C:\Python27\Scripts>pip install -U pyopenssl
C:\Python27\Scripts>pip install --upgrade google-cloud-bigquery
Add this JSON file to windows path from my test folder:
set GOOGLE_APPLICATION_CREDENTIALS=C:\test\python_doc.json
Because my JSON file is named python_doc.json then this is the name I will use with my python script.
Let's see the script:
import google
from google.cloud import bigquery

def query_shakespeare():
    client = bigquery.Client()
    client = client.from_service_account_json('python_doc.json')
    query_job = client.query("""
        #standardSQL
        SELECT corpus AS title, COUNT(*) AS unique_words
        FROM `bigquery-public-data.samples.shakespeare`
        GROUP BY title
        ORDER BY unique_words DESC
        LIMIT 10""")

    results = query_job.result()  # Waits for job to complete.

    for row in results:
        print("{}: {}".format(row.title, row.unique_words))

if __name__ == '__main__':
    query_shakespeare()
The result is:
C:\Python27>python.exe goo_test_bquerry.py
hamlet: 5318
kinghenryv: 5104
cymbeline: 4875
troilusandcressida: 4795
kinglear: 4784
kingrichardiii: 4713
2kinghenryvi: 4683
coriolanus: 4653
2kinghenryiv: 4605
antonyandcleopatra: 4582
NOTE: Take care of the JSON file because it gives access to your google account and tries to use the restrictions according to the application's requirements.

Thursday, January 4, 2018

Python 2.7 : InsecurePlatformWarning error.

This is not a common error and can be solve it easy like any python issue.
The result of this error can be shown like into the next example:
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:318: 
SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension 
to TLS is not available on this platform. This may cause the server to present an incorrect TLS 
certificate, which can cause validation failures. You can upgrade to a newer version of Python to
 solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html
#snimissingwarning.
  SNIMissingWarning
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: 
InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from
 configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade 
to a newer version of Python to solve this. For more information, see https://urllib3.readthe
docs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
The simple way to test this python error is to install these python modules:
pip install urllib3 
pip install requests
This last python module named requests to come with:
Successfully installed certifi-2017.11.5 chardet-3.0.4 idna-2.6 requests-2.18.4
What is this python module named requests?
Is a security the requests python module inject pyopenssl into urllib3
.
C:\Python27>python
Python 2.7 (r27:82525, Jul  4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> help()

Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> modules requests

Here is a list of matching modules.  Enter any module name to get more help.

pip._vendor.cachecontrol.controller - The httplib2 algorithms ported for use with requests.
pip._vendor.requests - Requests HTTP library
pip._vendor.requests.adapters - requests.adapters
pip._vendor.requests.api - requests.api
pip._vendor.requests.auth - requests.auth
pip._vendor.requests.certs - requests.certs
pip._vendor.requests.compat - requests.compat
pip._vendor.requests.cookies - requests.cookies
pip._vendor.requests.exceptions - requests.exceptions
pip._vendor.requests.hooks - requests.hooks
pip._vendor.requests.models - requests.models
pip._vendor.requests.packages
pip._vendor.requests.packages.chardet
pip._vendor.requests.packages.chardet.big5freq
pip._vendor.requests.packages.chardet.big5prober
pip._vendor.requests.packages.chardet.chardetect - Script which takes one or more file paths 
and reports on their detected
pip._vendor.requests.packages.chardet.chardistribution
pip._vendor.requests.packages.chardet.charsetgroupprober
pip._vendor.requests.packages.chardet.charsetprober
pip._vendor.requests.packages.chardet.codingstatemachine
pip._vendor.requests.packages.chardet.compat
pip._vendor.requests.packages.chardet.constants
pip._vendor.requests.packages.chardet.cp949prober
pip._vendor.requests.packages.chardet.escprober
pip._vendor.requests.packages.chardet.escsm
pip._vendor.requests.packages.chardet.eucjpprober
pip._vendor.requests.packages.chardet.euckrfreq
pip._vendor.requests.packages.chardet.euckrprober
pip._vendor.requests.packages.chardet.euctwfreq
pip._vendor.requests.packages.chardet.euctwprober
pip._vendor.requests.packages.chardet.gb2312freq
pip._vendor.requests.packages.chardet.gb2312prober
pip._vendor.requests.packages.chardet.hebrewprober
pip._vendor.requests.packages.chardet.jisfreq
pip._vendor.requests.packages.chardet.jpcntx
pip._vendor.requests.packages.chardet.langbulgarianmodel
pip._vendor.requests.packages.chardet.langcyrillicmodel
pip._vendor.requests.packages.chardet.langgreekmodel
pip._vendor.requests.packages.chardet.langhebrewmodel
pip._vendor.requests.packages.chardet.langhungarianmodel
pip._vendor.requests.packages.chardet.langthaimodel
pip._vendor.requests.packages.chardet.latin1prober
pip._vendor.requests.packages.chardet.mbcharsetprober
pip._vendor.requests.packages.chardet.mbcsgroupprober
pip._vendor.requests.packages.chardet.mbcssm
pip._vendor.requests.packages.chardet.sbcharsetprober
pip._vendor.requests.packages.chardet.sbcsgroupprober
pip._vendor.requests.packages.chardet.sjisprober
pip._vendor.requests.packages.chardet.universaldetector
pip._vendor.requests.packages.chardet.utf8prober
pip._vendor.requests.packages.urllib3 - urllib3 - Thread-safe connection pooling and re-using.
pip._vendor.requests.packages.urllib3._collections
pip._vendor.requests.packages.urllib3.connection
pip._vendor.requests.packages.urllib3.connectionpool
pip._vendor.requests.packages.urllib3.contrib
pip._vendor.requests.packages.urllib3.contrib.appengine
pip._vendor.requests.packages.urllib3.contrib.ntlmpool - NTLM authenticating pool, 
contributed by erikcederstran
pip._vendor.requests.packages.urllib3.contrib.pyopenssl
pip._vendor.requests.packages.urllib3.contrib.socks - SOCKS support for urllib3
pip._vendor.requests.packages.urllib3.exceptions
pip._vendor.requests.packages.urllib3.fields
pip._vendor.requests.packages.urllib3.filepost
pip._vendor.requests.packages.urllib3.packages
pip._vendor.requests.packages.urllib3.packages.ordered_dict
pip._vendor.requests.packages.urllib3.packages.six - Utilities for writing code that runs on 
Python 2 and 3
pip._vendor.requests.packages.urllib3.packages.ssl_match_hostname
pip._vendor.requests.packages.urllib3.packages.ssl_match_hostname._implementation - The match_hostname() 
function from Python 3.3.3, essential when using SSL.
pip._vendor.requests.packages.urllib3.poolmanager
pip._vendor.requests.packages.urllib3.request
pip._vendor.requests.packages.urllib3.response
pip._vendor.requests.packages.urllib3.util
pip._vendor.requests.packages.urllib3.util.connection
pip._vendor.requests.packages.urllib3.util.request
pip._vendor.requests.packages.urllib3.util.response
pip._vendor.requests.packages.urllib3.util.retry
pip._vendor.requests.packages.urllib3.util.ssl_
pip._vendor.requests.packages.urllib3.util.timeout
pip._vendor.requests.packages.urllib3.util.url
pip._vendor.requests.sessions - requests.session
pip._vendor.requests.status_codes
pip._vendor.requests.structures - requests.structures
pip._vendor.requests.utils - requests.utils
requests - Requests HTTP Library
requests.__version__
requests._internal_utils - requests._internal_utils
requests.adapters - requests.adapters
requests.api - requests.api
requests.auth - requests.auth
requests.certs - requests.certs
requests.compat - requests.compat
requests.cookies - requests.cookies
requests.exceptions - requests.exceptions
requests.help - Module containing bug report helper(s).
requests.hooks - requests.hooks
requests.models - requests.models
requests.packages
requests.sessions - requests.session
requests.status_codes
requests.structures - requests.structures
requests.utils - requests.utils
help>
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>
...

Wednesday, January 3, 2018

The ebooklib python module .

Happy new year 2018!
The official webpage of this python module comes with this intro:
EbookLib is a Python library for managing EPUB2/EPUB3 and Kindle files. It's capable of reading and writing EPUB files programmatically (Kindle support is under development).
First the installation of this python module named ebooklib.
C:\>cd Python27

C:\Python27>cd Script
The system cannot find the path specified.

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install ebooklib
Collecting ebooklib
  Downloading EbookLib-0.16.tar.gz
Requirement already satisfied: lxml in c:\python27\lib\site-packages (from ebooklib)
Requirement already satisfied: six in c:\python27\lib\site-packages (from ebooklib)
Installing collected packages: ebooklib
  Running setup.py install for ebooklib ... done
Successfully installed ebooklib-0.16
If you don't see the Scripts folder into your Python27 folder you need to install pip tool.
Just download the get-pip.py script into your Python27 folder and run it with python.
Let's test some default example:
C:\Python27>python.exe get-pip.py
The next step is to test a simple example:
from ebooklib import epub

book = epub.EpubBook()

# set metadata
book.set_identifier('id123456')
book.set_title('Sample book')
book.set_language('en')

book.add_author('Author Python')
book.add_author('catafest', file_as='', role='writer', uid='author')

# create chapter
c1 = epub.EpubHtml(title='Intro', file_name='chap_01.xhtml', lang='hr')
c1.content=u'Intro heading.Python is a interpreted high-level programming language ...'

# add chapter
book.add_item(c1)

# define Table Of Contents
book.toc = (epub.Link('chap_01.xhtml', 'Introduction', 'intro'),
(epub.Section('Simple book'),
(c1, ))
)

# add default NCX and Nav file
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())

# define CSS style
style = 'BODY {color: white;}'
nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)

# add CSS file
book.add_item(nav_css)

# basic spine
book.spine = ['nav', c1]

# write to the file
epub.write_epub('test.epub', book, {})
You can update and make more good your epub book with HTML5 tags.
I used this example with headings and paragraph to change the text, see the result: