analitics

Pages

Showing posts with label 2018. Show all posts
Showing posts with label 2018. Show all posts

Friday, November 9, 2018

Python Qt5 : default icons with QStyle.

This is a simple example of QStyle.
Using the QStyle can solve more issues above this example.
The QStyle can solve more problems than this example.
You can change everything in PyQt5 and Qt.
The QStyle class is an abstract base class that encapsulates the look and feel of a GUI, read here.
This is the result of a source code I used to show you how can use default icons from PyQt5.

See this source code:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Widget(QWidget):
  
    def __init__(self, parent= None):
        super(Widget, self).__init__()
        icons = [
'SP_TitleBarMinButton', 
'SP_TitleBarMenuButton', 
'SP_TitleBarMaxButton', 
'SP_TitleBarCloseButton', 
'SP_TitleBarNormalButton', 
'SP_TitleBarShadeButton', 
'SP_TitleBarUnshadeButton', 
'SP_TitleBarContextHelpButton', 
'SP_MessageBoxInformation', 
'SP_MessageBoxWarning', 
'SP_MessageBoxCritical', 
'SP_MessageBoxQuestion', 
'SP_DesktopIcon', 
'SP_TrashIcon', 
'SP_ComputerIcon', 
'SP_DriveFDIcon', 
'SP_DriveHDIcon', 
'SP_DriveCDIcon', 
'SP_DriveDVDIcon', 
'SP_DriveNetIcon', 
'SP_DirHomeIcon', 
'SP_DirOpenIcon', 
'SP_DirClosedIcon', 
'SP_DirIcon', 
'SP_DirLinkIcon', 
'SP_FileIcon', 
'SP_FileLinkIcon', 
'SP_FileDialogStart', 
'SP_FileDialogEnd', 
'SP_FileDialogToParent', 
'SP_FileDialogNewFolder', 
'SP_FileDialogDetailedView', 
'SP_FileDialogInfoView', 
'SP_FileDialogContentsView', 
'SP_FileDialogListView', 
'SP_FileDialogBack', 
'SP_DockWidgetCloseButton', 
'SP_ToolBarHorizontalExtensionButton', 
'SP_ToolBarVerticalExtensionButton', 
'SP_DialogOkButton', 
'SP_DialogCancelButton', 
'SP_DialogHelpButton', 
'SP_DialogOpenButton', 
'SP_DialogSaveButton', 
'SP_DialogCloseButton', 
'SP_DialogApplyButton', 
'SP_DialogResetButton', 
'SP_DialogDiscardButton', 
'SP_DialogYesButton', 
'SP_DialogNoButton', 
'SP_ArrowUp',  
'SP_ArrowDown', 
'SP_ArrowLeft', 
'SP_ArrowRight', 
'SP_ArrowBack', 
'SP_ArrowForward', 
'SP_CommandLink', 
'SP_VistaShield', 
'SP_BrowserReload', 
'SP_BrowserStop', 
'SP_MediaPlay', 
'SP_MediaStop', 
'SP_MediaPause', 
'SP_MediaSkipForward',
'SP_MediaSkipBackward', 
'SP_MediaSeekForward',
'SP_MediaSeekBackward', 
'SP_MediaVolume', 
'SP_MediaVolumeMuted', 
'SP_CustomBase'
            ]
        Col_size = 6
         
        layout = QGridLayout()
 
        count = 0
        for i in icons:
            select_button = QPushButton(i)
            select_button.setIcon(self.style().standardIcon(getattr(QStyle, i)))
 
            layout.addWidget(select_button, count / Col_size, count % Col_size)
            count += 1
             
        self.setLayout(layout)
         
if __name__ == '__main__':
    app = QApplication(sys.argv)
             
    dialog = Widget()
    dialog.show()
             
    app.exec_()

Thursday, November 8, 2018

Python Qt5 : QFileDialog and QTextEdit example.

This tutorial is about QFileDialog and how to use it.
First you need to create a default PyQ5 application and add your method is called by my_OpenDialog.
This will be connected to one button.
My application uses the QTextEdit to show HTML and text files.
If you try to see another file this will open badly.
I set the completeSuffix just for HTML and text.
As you know this returns the complete suffix (extension) of the file.
The content of this file is put into QTextEdit widget create and named editor_text.
This is result of using QFileDialog with python:

This is the source code with the QFileDialog example:
import sys, os
from PyQt5 import QtCore, QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setWindowTitle('Text document')
        self.editor_text = QtWidgets.QTextEdit(self)

        self.button_OpenDialog = QtWidgets.QPushButton('Open', self)
        self.button_OpenDialog.clicked.connect(self.my_OpenDialog)

        layout = QtWidgets.QGridLayout(self)
        layout.addWidget(self.editor_text, 0, 0, 1, 1)
        layout.addWidget(self.button_OpenDialog, 1, 0)
        #self.handleTextChanged()

    def my_OpenDialog(self):
        path = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Open file', '',
            'HTML files (*.html);;Text files (*.txt)')[0]
        if path:
            file = QtCore.QFile(path)
            if file.open(QtCore.QIODevice.ReadOnly):
                stream = QtCore.QTextStream(file)
                text = stream.readAll()
                info = QtCore.QFileInfo(path)
                if info.completeSuffix() == 'html':
                    self.editor_text.setHtml(text)
                else:
                    self.editor_text.setPlainText(text)
                file.close()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

Wednesday, November 7, 2018

Python Qt5 : QLCDNumber and QDial example.

This tutorial uses a simple example of QLCDNumber and QDial.
The steps start with create the QWidget with the QLCDNumber and QDial.
You need to set geometry for both and connect the dial with valueChanged.
Finally you need to use show to see the QWidget.
The result is show into the next screenshot:

Let see the source code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QWidget, QLCDNumber, QDial, QApplication)

class QLCDNumber_QDial(QWidget):
    def __init__(self):
        super().__init__()
        self.initUi()

    def initUi(self):
        the_lcd = QLCDNumber(self)
        the_dial = QDial(self)

        self.setGeometry(150, 100, 220, 100)
        self.setWindowTitle('QLCDNumber')

        the_lcd.setGeometry(10,10,70,70)
        the_dial.setGeometry(140,10,70,70)

        the_dial.valueChanged.connect(the_lcd.display)

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    run = QLCDNumber_QDial() 
    sys.exit(app.exec_())

Tuesday, November 6, 2018

Python Qt5 : QColorDialog example.

Today I will show you how to use the QColorDialog and clipboard with PyQt5.
You can read documentation from the official website.
This example used a tray icon with actions for each type of code color.
The code of color is put into clipboard area and print on the shell.
I use two ways to get the code of color:
  • parse the result of currentColor depends by type of color codel;
  • get the code of color by a special function from QColorDialog;
To select the color I want to use is need to use the QColorDialog:

Let's see the source code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# create the application
app = QApplication([])
app.setQuitOnLastWindowClosed(False)

# get the icon file
icon = QIcon("icon.png")

# create clipboard
clipboard = QApplication.clipboard()
# create dialog color
dialog = QColorDialog()

# create functions to get parsing color
def get_color_hex():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText(color.name())
        print(clipboard.text())

def get_color_rgb():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText("rgb(%d, %d, %d)" % (
            color.red(), color.green(), color.blue()
        ))
        print(clipboard.text())

def get_color_hsv():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText("hsv(%d, %d, %d)" % (
            color.hue(), color.saturation(), color.value()
        ))
        print(clipboard.text())
# create function to use getCmyk 
def get_color_getCmyk():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText("Cmyk(%d, %d, %d, %d, %d)" % (
            color.getCmyk()
        ))
        print(clipboard.text())


# create the tray icon application
tray = QSystemTrayIcon()
tray.setIcon(icon)
tray.setVisible(True)

# create the menu and add actions
menu = QMenu()
action1 = QAction("Hex")
action1.triggered.connect(get_color_hex)
menu.addAction(action1)

action2 = QAction("RGB")
action2.triggered.connect(get_color_rgb)
menu.addAction(action2)

action3 = QAction("HSV")
action3.triggered.connect(get_color_hsv)
menu.addAction(action3)

action4 = QAction("Cmyk")
action4.triggered.connect(get_color_getCmyk)
menu.addAction(action4)

action5 =QAction("Exit")
action5.triggered.connect(exit)
menu.addAction(action5)

# add the menu to the tray icon application
tray.setContextMenu(menu)

app.exec_()

Monday, November 5, 2018

Python Qt5 : tray icon example.

This tutorial is about another tray icon application type.
The base application is the same like any application with some changes with this steps:
- QSystemTrayIcon this will start to create the application like an tray icon application;
- create one menu to show if you use the right click of mouse;
- add a menu with action items;
- add the exit action to close the tray icon application;
- you can use the action item from menu to print a message
Let's see the source code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# create the application
app = QApplication([])
app.setQuitOnLastWindowClosed(False)

# create the icon
icon = QIcon("icon.png")

# create the tray icon 
tray = QSystemTrayIcon()
tray.setIcon(icon)
tray.setVisible(True)

# this will print a message 
def print_msg():
 print("This action is triggered connect!")

# create the menu for tray icon
menu = QMenu()

# add one item to menu 
action = QAction("This is menu item")
menu.addAction(action)
action.triggered.connect(print_msg)

# add exit item to menu 
exitAction = QAction("&Exit")
menu.addAction(exitAction)
exitAction.triggered.connect(exit)

# add the menu to the tray
tray.setContextMenu(menu)

# start application execution 
app.exec_()
This is result of the running source code:

Sunday, November 4, 2018

Python Qt5 : QtSql with QtOpenGL example.

Today I will show you how to deal with QtOpenGL.
Let's make a test to see what is this:
>>> import PyQt5
>>> from PyQt5.QtOpenGL import *
>>> dir(PyQt5.QtOpenGL)
['QGL', 'QGLContext', 'QGLFormat', 'QGLWidget', '__doc__', '__file__', '__loader
__', '__name__', '__package__', '__spec__']
The QtOpenGL is used to take an OpenGL content and show into the PyQt5 application.
You need to kknow how to use OpenGL API.
You can see the result of this example:

This is the source code for my example:
import sys
import math

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtOpenGL import QGL, QGLFormat, QGLWidget

try:
    from OpenGL import GL
except ImportError:
    app = QApplication(sys.argv)
    QMessageBox.critical(None, "OpenGL samplebuffers",
            "PyOpenGL must be installed to run this example.")
    sys.exit(1)

# use to create OpenGL content 
class GLWidget(QGLWidget):
    GL_MULTISAMPLE = 0x809D
    # rotation to 0
    rot = 0.0

    def __init__(self, parent):
        super(GLWidget, self).__init__(QGLFormat(QGL.SampleBuffers), parent)
        self.list_ = []
        self.startTimer(40)
        self.setWindowTitle("OpenGL with sample buffers")

    def initializeGL(self):
        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glLoadIdentity()
        GL.glOrtho( -.5, .5, .5, -.5, -1000, 1000)
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glLoadIdentity()
        GL.glClearColor(1.0, 1.0, 1.0, 1.0)

        self.makeObject()

    def resizeGL(self, w, h):
        GL.glViewport(0, 0, w, h)

    def paintGL(self):
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glPushMatrix()
        GL.glEnable(GLWidget.GL_MULTISAMPLE)
        GL.glTranslatef( -0.25, -0.10, 0.0)
        GL.glScalef(0.75, 1.15, 0.0)
        GL.glRotatef(GLWidget.rot, 0.0, 0.0, 1.0)
        GL.glCallList(self.list_)
        GL.glPopMatrix()

        GL.glPushMatrix()
        GL.glDisable(GLWidget.GL_MULTISAMPLE)
        GL.glTranslatef(0.25, -0.10, 0.0)
        GL.glScalef(0.75, 1.15, 0.0)
        GL.glRotatef(GLWidget.rot, 0.0, 0.0, 1.0)
        GL.glCallList(self.list_)
        GL.glPopMatrix()

        GLWidget.rot += 0.2

        self.qglColor(Qt.black)
        self.renderText(-0.35, 0.4, 0.0, "Multisampling enabled")
        self.renderText(0.15, 0.4, 0.0, "Multisampling disabled")

    def timerEvent(self, event):
        self.update()
    # create one object 
    def makeObject(self):
        x1 = +0.05
        y1 = +0.25
        x2 = +0.15
        y2 = +0.21
        x3 = -0.25
        y3 = +0.2
        x4 = -0.1  
        y4 = +0.2
        x5 = +0.25 
        y5 = -0.05

        self.list_ = GL.glGenLists(1)
        GL.glNewList(self.list_, GL.GL_COMPILE)
        
        self.qglColor(Qt.blue)
        self.geometry(GL.GL_POLYGON, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5)
        
        GL.glEndList()
    # create geometry of object depend of render - GL_POLYGON
    # used five points 
    def geometry(self, primitive, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5):
        GL.glBegin(primitive)

        GL.glVertex2d(x1, y1)
        GL.glVertex2d(x2, y2)
        GL.glVertex2d(x3, y3)
        GL.glVertex2d(x4, y4)
        GL.glVertex2d(x5, y5)

        GL.glEnd()
# start the application 
if __name__ == '__main__':

    app = QApplication(sys.argv)

    my_format = QGLFormat.defaultFormat()
    my_format.setSampleBuffers(True)
    QGLFormat.setDefaultFormat(my_format)

    if not QGLFormat.hasOpenGL():
        QMessageBox.information(None, "OpenGL using samplebuffers",
                "This system does not support OpenGL.")
        sys.exit(0)

    widget = GLWidget(None)

    if not widget.format().sampleBuffers():
        QMessageBox.information(None, "OpenGL using samplebuffers",
                "This system does not have sample buffer support.")
        sys.exit(0)

    widget.resize(640, 480)
    widget.show()

    sys.exit(app.exec_())

Saturday, November 3, 2018

Python Qt5 : QtSql with QSQLITE example.

Today I will show you how to deal with QtSql and QSQLITE and show a table into an MDI (Multiple Document Interface) application.
First I create tree scripts named:
  • PyQt5_connection.py - create a memory database and add value into table;
  • PyQt5_view.py - create a model for the table;
  • PyQt5_show.py - show the MDI application with the model table database;
The source code is commented and is simple to understand.
Let's see this python scripts:
First is PyQt5_connection.py:
from PyQt5 import QtWidgets, QtSql
from PyQt5.QtSql import *

def createConnection():
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(":memory:")
    if not db.open():
        QtWidgets.QMessageBox.critical(None, "Cannot open memory database",
                             "Unable to establish a database connection.\n\n"
                             "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel)
        return False
    query = QtSql.QSqlQuery()
    #print (os.listdir("."))
    query.exec("DROP TABLE IF EXISTS Websites")
    query.exec("CREATE TABLE Websites (ID INTEGER PRIMARY KEY NOT NULL, " +     "website VARCHAR(20))")
    query.exec("INSERT INTO Websites (website) VALUES('python-catalin.blogspot.com')")
    query.exec("INSERT INTO Websites (website) VALUES('catalin-festila.blogspot.com')")
    query.exec("INSERT INTO Websites (website) VALUES('free-tutorials.org')")
    query.exec("INSERT INTO Websites (website) VALUES('graphic-3d.blogspot.com')")
    query.exec("INSERT INTO Websites (website) VALUES('pygame-catalin.blogspot.com')")
    return True
The next is the PyQt5_view.py python script with the model of the table from database:
from PyQt5 import QtWidgets, QtSql

from PyQt5 import QtWidgets, QtSql

class WebsitesWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(WebsitesWidget, self).__init__(parent)
 # this layout_box can be used if you need more widgets 
 # I used just one named WebsitesWidget
        layout_box = QtWidgets.QVBoxLayout(self)
 #
        my_view = QtWidgets.QTableView()
 # put viwe in layout_box area
        layout_box.addWidget(my_view)
 # create a table model
        my_model = QtSql.QSqlTableModel(self)
        my_model.setTable("Websites")
        my_model.select()
 #show the view with model  
        my_view.setModel(my_model)
        my_view.setItemDelegate(QtSql.QSqlRelationalDelegate(my_view))
The last python script named PyQt5_show.py will create the MDI application and will show databese table:
from PyQt5 import QtWidgets, QtSql
from PyQt5_connection import createConnection
# this will import any classes from PyQt5_view script
from PyQt5_view import WebsitesWidget

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.MDI = QtWidgets.QMdiArea()
        self.setCentralWidget(self.MDI)

        SubWindow1 = QtWidgets.QMdiSubWindow()
        SubWindow1.setWidget(WebsitesWidget())
        self.MDI.addSubWindow(SubWindow1)
        SubWindow1.show()
 # you can add more widgest 
        #SubWindow2 = QtWidgets.QMdiSubWindow()

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)

    if not createConnection():
        print("not connect")
        sys.exit(-1)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
This is the result of the running PyQt5_show.py python script:

Thursday, November 1, 2018

Python Qt5 : QtWebEngine example.

The QtWebEngine is the new web rendering engine that is planned to replace QtWebKit in Qt.
The official website tells us:
QtWebEngineWidgets or QtWebEngine libraries, depending on application type
Let's test this web rendering engine with a simple source code:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication
# use the QtWebEngineWidgets
from PyQt5.QtWebEngineWidgets import *
# start my_app
my_app = QApplication(sys.argv)
# open webpage
my_web = QWebEngineView()
my_web.load(QUrl("http://free-tutorials.org"))
my_web.show()
# sys exit function
sys.exit(my_app.exec_())
The output of this running source code.

Friday, October 26, 2018

Python Qt5 : MP3 player example.

This tutorial with PyQt5 will allow us to play an MP3 file using QtMultimedia.
I used a test.mp3 file in the same folder with my python script.
This is the source script:
import sys

from PyQt5 import QtCore, QtWidgets, QtMultimedia

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    filename = 'test.mp3'
    fullpath = QtCore.QDir.current().absoluteFilePath(filename) 
    media = QtCore.QUrl.fromLocalFile(fullpath)
    content = QtMultimedia.QMediaContent(media)
    player = QtMultimedia.QMediaPlayer()
    player.setMedia(content)
    player.play()
    sys.exit(app.exec_())

Wednesday, October 24, 2018

Python Qt5 : Webcam example.

Today I come with another source code.
This example uses QtMultimedia to create use of the webcam.
The source code follows the steps from finding, set and use a webcam.
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *

import os
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.online_webcams = QCameraInfo.availableCameras()
        if not self.online_webcams:
            pass #quit
        self.exist = QCameraViewfinder()
        self.exist.show()
        self.setCentralWidget(self.exist)

        # set the default webcam.
        self.get_webcam(0)
        self.setWindowTitle("WebCam")
        self.show()

    def get_webcam(self, i):
        self.my_webcam = QCamera(self.online_webcams[i])
        self.my_webcam.setViewfinder(self.exist)
        self.my_webcam.setCaptureMode(QCamera.CaptureStillImage)
        self.my_webcam.error.connect(lambda: self.alert(self.my_webcam.errorString()))
        self.my_webcam.start()

    def alert(self, s):
        """
        This handle errors and displaying alerts.
        """
        err = QErrorMessage(self)
        err.showMessage(s)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setApplicationName("WebCam")

    window = MainWindow()
    app.exec_()

Tuesday, October 23, 2018

Python Qt5 : toolbar example.

This is a simple example with PyQt5 python module and python 3.6.4 version.
The example is about how to create a toolbar with PyQt5.
The base of this source code is the create a default window application.
I create a toolbar and I add an action to this toolbar.
The name of the toolbar is my_toolbar.
The action is named one_action.
This action is linked to a python function named action_one.
I add to my source code another function named alert.
This is good for debugging part to handle with errors and displaying alerts.
Let's see the source code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.status = QStatusBar()
        self.setStatusBar(self.status)
        my_toolbar = QToolBar("toolbar")
        my_toolbar.setIconSize(QSize(48, 48))
        self.addToolBar(my_toolbar)
        
        one_action = QAction(QIcon(), "Action one", self)        
        one_action.setStatusTip("Action one on toolbar")
        one_action.triggered.connect(self.action_one)
        my_toolbar.addAction(one_action)
        
        self.setWindowTitle("Window PyQt5 - 001")
        self.show()

    def action_one(self):
        print("Action one")

    def alert(self, s):
        """
        This handle errors and displaying alerts.
        """
        err = QErrorMessage(self)
        err.showMessage(s)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setApplicationName("Window PyQt5 - 001")

    window = MainWindow()
    app.exec_()

Sunday, October 21, 2018

Programmer's Notepad - free editor with PyPN python module.

Programmer's Notepad is a free, open source, text editor with special features for coders.
This editor comes with a variety of text clips representing common programming languages.
I saw 43 of text clips to start your programming.
Featuring
Syntax highlighting
Text Clips for simple text insertion
Code folding / outlining
Flexible Regular Expression support
Code navigation using Ctags
Projects for navigating large code bases
Extend using Python or C++
For example, if you start with the HTML then every tag will autocomplete with the end tag.
You can install the PyPN python module and used with this editor:
C:\Python364\Scripts>pip install PyPN
Collecting PyPN
...
Installing collected packages: PyPN
Successfully installed PyPN-0.9
More about PyPN module can be found here.
You can donate to support the project.

Friday, September 28, 2018

Python 2.7 : Python geocoding without key.

Today I will come with a simple example about geocoding.
I used JSON and requests python modules and python version 2.7.
About geocoding I use this service provide by datasciencetoolkit.
You can use this service free and you don't need to register to get a key.
Let's see the python script:
import requests
import json

url = u'http://www.datasciencetoolkit.org/maps/api/geocode/json'
par = {
    u'sensor': False,
    u'address': u'London'
}

my = requests.get(
    url,
    par
)
json_out = json.loads(my.text)

if json_out['status'] == 'OK':
    print([r['geometry']['location'] for r in json_out['results']])
I run this script and I test with google map to see if this works well.
This is output and working well with the geocoding service:

Friday, September 7, 2018

Python 3.6.4 : Test Django version 2.1.1 on Windows O.S.

I used the python version 3.6.4 to test the last Django framework version.
Add your python to the path environment variable under Windows O.S.
Create your working folder:
C:\Python364>mkdir mywebsite
Go to the folder to install all you need:
C:\Python364>cd mywebsite
Use a virtual environment using the virtualenv command:
C:\Python364\mywebsite>python -m venv myvenv
C:\Python364\mywebsite>myvenv\Scripts\activate
(myvenv) C:\Python364\mywebsite>python -m pip install --upgrade pip
(myvenv) C:\Python364\mywebsite>pip3.6 install django
Collecting django
...
If you try to run again this command you will see the version of Django:
(myvenv) C:\Python364\mywebsite>pip3.6 install django
Requirement already satisfied: django in c:\python364\mywebsite\myvenv\lib\
site-packages (2.1.1)
Requirement already satisfied: pytz in c:\python364\mywebsite\myvenv\lib\
site-packages (from django) (2018.5)
You need to run the django-admin command:
(myvenv) C:\Python364\mywebsite>cd myvenv
(myvenv) C:\Python364\mywebsite\myvenv>cd Scripts
(myvenv) C:\Python364\mywebsite\myvenv\Scripts>django-admin.exe startproject mysite
(myvenv) C:\Python364\mywebsite\myvenv\Scripts>dir my*
(myvenv) C:\Python364\mywebsite\myvenv\Scripts>cd mysite
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite&
Make a change to settings file:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>cd mysite
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\mysite>notepad settings.py
Change UTC timezone:
TIME_ZONE = 'Europe/Paris'
Change host:
ALLOWED_HOSTS = ['192.168.0.185','mysite.com']
The next step is to use these commands:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\mysite>cd ..
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK
Let's try these steps with the browser:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py runserver
 192.168.0.185:8080
Performing system checks...

System check identified no issues (0 silenced).
September 07, 2018 - 16:30:13
Django version 2.1.1, using settings 'mysite.settings'
Starting development server at http://192.168.0.185:8080/
Quit the server with CTRL-BREAK.
[07/Sep/2018 16:30:16] "GET / HTTP/1.1" 200 16348
[07/Sep/2018 16:30:21] "GET / HTTP/1.1" 200 16348
This is the result:

Let's start Django application named myblog and add to settings.py :
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py startapp
myblog

(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>dir
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>cd mysite
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\mysite>notepad settings.py
Search into settings.py this line and add 'myblog' and comma after, see:
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myblog',
]
Let's change models.py from myblog folder:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\mysite>cd ..
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>cd myblog
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\myblog>notepad models.py
Add this source code:
from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
 author = models.ForeignKey(User,on_delete=models.PROTECT)
 title = models.CharField(max_length=200)
 text = models.TextField()
 create_date = models.DateTimeField(default=timezone.now)
 published_date = models.DateTimeField(blank=True, null=True)
 
 def publish(self):
  self.publish_date = timezone.now()
  self.save()
 def __str__(self):
  return self.title
Go and run this command manage.py for model Post with makemigrations myblog and migrate myblog :
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\myblog>cd ..
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py 
makemigrations myblog
Migrations for 'myblog':
  myblog\migrations\0001_initial.py
    - Create model Post
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py migrate 
myblog
Operations to perform:
  Apply all migrations: myblog
Running migrations:
  Applying myblog.0001_initial... OK
Add this source code to admin.py from myblog folder:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>cd myblog
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\myblog>notepad admin.py
Let's test again:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite\myblog>cd ..
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py runserver
 192.168.0.185:8080
Performing system checks...

System check identified no issues (0 silenced).
September 07, 2018 - 17:19:00
Django version 2.1.1, using settings 'mysite.settings'
Starting development server at http://192.168.0.185:8080/
Quit the server with CTRL-BREAK.
Check the admin interface with add admin word to link, see: http://192.168.0.185:8080/admin

If you see some errors this will be fixed later.
Let's make a superuser with this command:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py 
createsuperuser
Username (leave blank to use 'catafest'): catafest
Email address: catafest@yahoo.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
Run again this command and log in with your user and password:
(myvenv) C:\Python364\mywebsite\myvenv\Scripts\mysite>python manage.py runserver
 192.168.0.185:8080
This is the result of users and posts.

Click on the Add button from Posts to add your post.
The result is this:

I don't make settings for URL and view.
This will be changed by users.

Wednesday, August 29, 2018

PyOpenGL: Fix Attempt to call an undefined function glutInit .

This tutorial is about how to fix this error using Python version 3.6.4 :
OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit,
check for bool(glutInit) before calling
First I start with a common pip3.6 install.
Scripts>pip3.6.exe install PyOpenGL
Collecting PyOpenGL
  Downloading https://files.pythonhosted.org/packages/9c/1d/4544708aaa89f26c97cc
09450bb333a23724a320923e74d73e028b3560f9/PyOpenGL-3.1.0.tar.gz (1.2MB)
    100% |████████████████████████████████| 1.2MB 1.2MB/s
Building wheels for collected packages: PyOpenGL
  Running setup.py bdist_wheel for PyOpenGL ... done
  Stored in directory: C:\Users\catafest\AppData\Local\pip\Cache\wheels\6c\00\7f
\1dd736f380848720ad79a1a1de5272e0d3f79c15a42968fb58
Successfully built PyOpenGL
Installing collected packages: PyOpenGL
Successfully installed PyOpenGL-3.1.0
When I run my python script code I got this error:
c:\Python364\Scripts>cd ..
c:\Python364>python.exe opengl_001.py
Traceback (most recent call last):
  File "opengl_001.py", line 182, in 
    StereoDepth().main()
  File "opengl_001.py", line 173, in main
    glutInit()
  File "c:\Python364\lib\site-packages\OpenGL\GLUT\special.py", line 333, in glu
tInit
    _base_glutInit( ctypes.byref(count), holder )
  File "c:\Python364\lib\site-packages\OpenGL\platform\baseplatform.py", line 40
7, in __call__
    self.__name__, self.__name__,
OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit,
check for bool(glutInit) before calling
I use the whl files from here.
c:\Python364>cd Scripts

c:\Python364\Scripts>pip3.6.exe install PyOpenGL-3.1.2-cp36-cp36m-win_amd64.whl
Processing c:\python364\scripts\pyopengl-3.1.2-cp36-cp36m-win_amd64.whl
Installing collected packages: PyOpenGL
  Found existing installation: PyOpenGL 3.1.0
    Uninstalling PyOpenGL-3.1.0:
      Successfully uninstalled PyOpenGL-3.1.0
Successfully installed PyOpenGL-3.1.2

c:\Python364\Scripts>pip3.6.exe install PyOpenGL_accelerate-3.1.2-cp36-cp36m-win
_amd64.whl
Processing c:\python364\scripts\pyopengl_accelerate-3.1.2-cp36-cp36m-win_amd64.w
hl
Installing collected packages: PyOpenGL-accelerate
Successfully installed PyOpenGL-accelerate-3.1.2
This allow me to run well the python script with PyOpenGL python module.
This is result of shader stereo depth image:

Sunday, July 15, 2018

Python 3.6.4 : Microsoft Azure - bad answer .

The Azure from Microsoft comes with the free account and $200 credit to explore services for 30 days.
I only have 7 days left from this free account.
During this time I tried to use it from scratch.
In this short tutorial, I will talk about this period,
First I used the python version 3.6.4 and the Azure development tools.
These are the links I follow:
I install the azure for python with :
C:\Python364\Scripts>pip install azure
You can use a preview version of this package, which you can access using the --pre flag:
C:\Python364\Scripts>pip install --pre azure
I used the example from azure:
git clone https://github.com/Azure-Samples/storage-blobs-python-quickstart.git
Into azure account, I create a storage account named pythonazure.

You can configure the Access control (IAM) to use with your account.
This storage account needs to use keys, see Access keys area.
They tell us about this feature:
Use access keys to authenticate your applications when making requests to this Azure storage account. Store your access keys securely - for example, using Azure Key Vault - and don't share them. We recommend regenerating your access keys regularly. You are provided two access keys so that you can maintain connections using one key while regenerating the other.
I change the account name with pythonazure and account_key with my account key.
The result is this:

In view of my previous experiences with Google, Firebase and Azure on the ease of assimilation and understanding of the content and the time allocated to making a simple task according to the Azure documentation, then azure get the last place.
In azure services, we can see the errors that occur and which are non-existent on google or firebase.

I was interested in ease and fast access to python cloud services. However, you can read this point of view written by google here.

Tuesday, June 26, 2018

Python 3.6.4 : Trying to use the python azurure on the windows.

In this tutorial, I used the python version 3.6.4 and Windows 8.1 OS.
You can start with pip install tool for some azure modules:
Install the latest Batch runtime library
C:\Python364\Scripts>pip install azure-batch 
This will install the latest Storage management library
C:\Python364\Scripts>pip install azure-mgmt-scheduler 
Will install only the latest compute installed using the --pre flag:
C:\Python364\Scripts>pip install --pre azure-mgmt-compute 
Finally the storage I used into this tutorial:
C:\Python364\Scripts>pip install azure-storage --upgrade
You can install all of the azure python modules:
C:\Python364\Scripts>pip install --pre azure
...
Installing collected packages: azure-storage-nspkg, azure-storage-common, azure-
storage-queue, azure-servicebus, azure-servicefabric, azure-storage-file, azure-
servicemanagement-legacy, azure-mgmt-consumption, azure-mgmt-media, azure-mgmt-d
ns, azure-mgmt-search, azure-mgmt-cdn, azure-mgmt-compute, azure-mgmt-eventhub,
azure-mgmt-containerinstance, azure-mgmt-datalake-nspkg, azure-mgmt-datalake-ana
lytics, azure-mgmt-recoveryservices, azure-mgmt-authorization, azure-mgmt-adviso
r, azure-mgmt-recoveryservicesbackup, azure-mgmt-billing, azure-mgmt-devtestlabs
, azure-mgmt-network, azure-mgmt-web, azure-mgmt-applicationinsights, azure-mgmt
-cognitiveservices, azure-mgmt-rdbms, azure-mgmt-monitor, azure-mgmt-reservation
s, azure-mgmt-notificationhubs, azure-mgmt-loganalytics, azure-mgmt-logic, azure
-mgmt-iothubprovisioningservices, azure-mgmt-marketplaceordering, azure-mgmt-res
ource, azure-mgmt-scheduler, azure-mgmt-powerbiembedded, azure-mgmt-servicefabri
c, azure-mgmt-commerce, azure-mgmt-sql, azure-mgmt-cosmosdb, azure-mgmt-relay, a
zure-mgmt-storage, azure-mgmt-redis, azure-mgmt-managementpartner, azure-mgmt-tr
afficmanager, azure-mgmt-machinelearningcompute, azure-mgmt-datafactory, azure-m
gmt-hanaonazure, azure-mgmt-iothub, azure-mgmt-servermanager, azure-mgmt-batch,
azure-mgmt-keyvault, azure-mgmt-subscription, azure-mgmt-eventgrid, azure-mgmt-s
ervicebus, azure-mgmt-batchai, azure-mgmt-containerservice, azure-mgmt-container
registry, azure-mgmt-msi, azure-mgmt-datalake-store, azure-mgmt, azure-datalake-
store, azure-eventgrid, azure-keyvault, azure-cosmosdb-nspkg, futures, azure-cos
mosdb-table, azure-graphrbac, azure-storage-blob, azure
I tested with all azure python modules, but you can use just you need.
The next step is to open the Azure account - I have a trial free account.
I create a Resource Group named python-azure and a Storage account named pythonazure.
Into pythonazure I add the Files service and I upload an HTML file named default.html .
See the next images with the steps I make:
Let's make one simple test:
C:\Python364\Scripts>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from azure.common.credentials import UserPassCredentials
>>> from azure.mgmt.resource import ResourceManagementClient
>>> from azure.mgmt.storage import StorageManagementClient
>>> from azure.storage import CloudStorageAccount
>>> from azure.storage.blob.models import ContentSettings, PublicAccess
>>> 
I have not been able to authenticate myself with a python script in Azure.
I found some inconsistencies and issues on GitHub so I still have to document.

Any help in this regard is welcome.

Sunday, June 24, 2018

Python 3.6.4 : Using python client with blogger API .

I used a new project into console cloud google.
I used the google-api-python-client from here with OAuth service.
You need to create a project and add the blogger API to use it.
For credentials, I used OAuth with the JSON file from google.
This is the source code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function

__author__ = 'Catalin George Festila ( catafest , mythcat )'

import sys

from oauth2client import client
from googleapiclient import sample_tools


def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv, 'blogger', 'v3', __doc__, __file__,
      scope='https://www.googleapis.com/auth/blogger')

  try:

      users = service.users()

      # Retrieve this user's profile information
      thisuser = users.get(userId='self').execute()
      print('This user\'s display name is: %s' % thisuser['displayName'])

      blogs = service.blogs()

      # Retrieve the list of Blogs this user has write privileges on
      thisusersblogs = blogs.listByUser(userId='self').execute()
      for blog in thisusersblogs['items']:
        print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))

      posts = service.posts()

      # List the posts for each blog this user has
      for blog in thisusersblogs['items']:
        print('The posts for %s:' % blog['name'])
        request = posts.list(blogId=blog['id'])
        while request != None:
          posts_doc = request.execute()
          if 'items' in posts_doc and not (posts_doc['items'] is None):
            for post in posts_doc['items']:
              print('  %s (%s)' % (post['title'], post['url']))
          request = posts.list_next(request, posts_doc)

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run'
      'the application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)
The content of the folder project named google_api_python.
c:\Python364\google_api_python>dir
06/24/2018  08:27 PM             1,096 blogger.dat
06/24/2018  07:49 PM             2,599 blogger.py
06/24/2018  08:24 PM               309 client_secrets.json
06/24/2018  08:26 PM                76 debug.log
               4 File(s)          4,080 bytes
               2 Dir(s)  201,382,006,784 bytes free
You need to add the client_id and client_secret from google project into file client_secrets.json.
Run the python script:
c:\Python364\google_api_python>python.exe blogger.py
The google will ask you about the authentification and will run the script:

Google show us all the infos about this project into dashboard:

Wednesday, June 6, 2018

Python 3.6.4 : The qrcode python module .

This python module named qrcode is a suite of tools to Generate QR codes.
Let's start the tutorial with the install steep :
c:\Python364\Scripts>pip install qrcode[pil]
Collecting qrcode[pil]
... 
Successfully installed qrcode-6.0 
Let's see the output for dir:
>>> import qrcode
>>> from qrcode import *
>>> dir(qrcode)
['ERROR_CORRECT_H', 'ERROR_CORRECT_L', 'ERROR_CORRECT_M', 'ERROR_CORRECT_Q', 'LU
T', 'QRCode', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
 '__name__', '__package__', '__path__', '__spec__', 'base', 'constants', 'except
ions', 'image', 'main', 'make', 'run_example', 'util']
>>> dir(qrcode.util)
['ALPHA_NUM', 'BCH_digit', 'BCH_type_info', 'BCH_type_number', 'BIT_LIMIT_TABLE'
, 'BitBuffer', 'G15', 'G15_MASK', 'G18', 'LUT', 'MODE_8BIT_BYTE', 'MODE_ALPHA_NU
M', 'MODE_KANJI', 'MODE_NUMBER', 'MODE_SIZE_LARGE', 'MODE_SIZE_MEDIUM', 'MODE_SI
ZE_SMALL', 'NUMBER_LENGTH', 'PAD0', 'PAD1', 'PATTERN_POSITION_TABLE', 'QRData',
'RE_ALPHA_NUM', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__
', '__name__', '__package__', '__spec__', '_data_count', '_lost_point_level1', '
_lost_point_level2', '_lost_point_level3', '_lost_point_level4', '_optimal_split
', 'base', 'create_bytes', 'create_data', 'exceptions', 'length_in_bits', 'lost_
point', 'mask_func', 'math', 'mode_sizes_for_version', 'optimal_data_chunks', 'o
ptimal_mode', 'pattern_position', 're', 'six', 'to_bytestring', 'xrange']
>>> dir(qrcode.image)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__path__', '__spec__', 'base']
>>> dir(qrcode.run_example)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defau
lts__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__',
 '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '
__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module_
_', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex_
_', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> 
This is the test python script I used to test this python module:
import qrcode
from  qrcode import *
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('https://python-catalin.blogspot.com/')
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")
with open('my_qr_test.png', 'wb') as qrfile:
    img.save(qrfile)
This is the output of QR file:

Saturday, May 26, 2018

Blender 3D and Roblox with Python .

I spend my free time with my son playing Roblox and in the meantime, I try to introduce him to the world of computers.
However, you can download the player as a 3D object and use it as an avatar.
Here's an issue: The 3D object is hard to set with origins for animation but python and Blender 3D can easily solve this.
You can use BMesh.
As you know:
BMesh is the new Blender mesh system in 2.63, with full support for N-sided polygons instead of only triangles and quads.
The result of this download 3D object has a bad origin:

Let's see the source code:
import bpy
import bmesh
import mathutils 
from mathutils import Vector

context = bpy.context

def origin_to_bottom(obj):
    matrix_world = obj.matrix_world
    local_verts = [Vector(v[:]) for v in obj.bound_box]
    blender_mesh = blender_meshesh.new()
    blender_mesh.from_mesh(obj.data)
    x, y, z = 0, 0, 0
    l = len(local_verts)
    z = min([v.z for v in local_verts])
    local_origin = Vector((0, 0, 0))
    global_origin = matrix_world * local_origin
    for v in blender_mesh.verts:
        v.coord = v.coord - local_origin
    blender_mesh.to_mesh(obj.data)
    matrix_world.translation = global_origin

mesh_objs = [mesh_object for mesh_object in context.selected_objects if mesh_object.type == 'MESH']
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')

for my_objects in mesh_objs:
    origin_to_bottom(my_objects)
The result is this: