Categories
Linux Programming Ruby Shell Script (BASH)

How to Install Ruby 2.7.1 and Rails 6.0.0 in Ubuntu 20.04 Focal Fossa with bash shell script

Ruby logo
Ruby
Ubuntu 20.04 LTS Focal Fossa
Ubuntu 20.04 LTS Focal Fossa

In this post, rbenv is used to install Rails6.0.0 and Ruby2.7.1

First, update your packages

sudo apt-get update

Then Install these prerequisites

sudo apt-get install git -y
sudo apt-get install gcc -y

sudo apt-get install autoconf -y
sudo apt-get install bison  -y
sudo apt-get install build-essential  -y
sudo apt-get install libssl-dev  -y
sudo apt-get install libyaml-dev  -y
sudo apt-get install libreadline6-dev  -y
sudo apt-get install zlib1g-dev  -y
sudo apt-get install libncurses5-dev  -y
sudo apt-get install libffi-dev  -y
sudo apt-get install libgdbm6  -y
sudo apt-get install libgdbm-dev  -y
sudo apt-get install libdb-dev  -y
PackageDescription
GitGit is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.
GccFor Compilation
autoconfAn automatic configure script builder
bisonA general-purpose parser generator that converts a grammar description for an LALR(1) context-free grammar into a C program to parse that grammar.
build-essential
libsslSecure Sockets Layer toolkit
libyamlA C library for parsing and emitting YAML
libreadline6GNU readline and history libraries, run-time libraries
zlib1gA runtime compression library
libncurses5This is shared libraries for terminal handling
libffiA module to check availability of a library for FFI
libgdbm6GNU dbm database routines
libgdbmGNU dbm database routines
libdbBerkeley Database Libraries for C++
These Prerequisites are now installed your System

Next, we install rbenv itself

git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git "$(rbenv root)"/plugins/ruby-build

Install your desired version if ruby

rbenv install 2.7.1

Make the installed version of ruby Global so it can be used everywhere

rbenv global 2.7.1

Finally install Rails 6.0.0 or any supported version you desire and then check its version

gem install bundler -v 2.1.4

ruby -v

gem install rails -v 6.0.0
rails -v

Here is the complete shell script.

#!/bin/bash
sudo apt-get update
echo "--------------"
echo "Prerequisites"
echo "Get updated  Rails prerequisites from https://github.com/rbenv/ruby-build/wiki#suggested-build-environment"
echo "--------------"
sudo apt-get install git -y
sudo apt-get install gcc -y

sudo apt-get install autoconf -y
sudo apt-get install bison  -y
sudo apt-get install build-essential  -y
sudo apt-get install libssl-dev  -y
sudo apt-get install libyaml-dev  -y
sudo apt-get install libreadline6-dev  -y
sudo apt-get install zlib1g-dev  -y
sudo apt-get install libncurses5-dev  -y
sudo apt-get install libffi-dev  -y
sudo apt-get install libgdbm6  -y
sudo apt-get install libgdbm-dev  -y
sudo apt-get install libdb-dev  -y

echo "--------------"
echo "Installing Ruby using rbenv along with its setup"
echo "--------------"

git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git "$(rbenv root)"/plugins/ruby-build


rbenv install 2.7.1
rbenv global 2.7.1

gem install bundler -v 2.1.4

ruby -v

gem install rails -v 6.0.0
rails -v

Furthermore, to uninstall a specific version of Ruby, you can do this

rbenv uninstall 2.7.1
Categories
Programming Shell Script (BASH) SQL

Install SQL Server 2019 in Ubuntu 20.04 LTS

Learn how to Install SQL Server 2019 in Ubuntu 20.04 LTS. Lets just start straightaway. While it is a straightforward process in Microsoft Windows operating system, it is different in Ubuntu (or Debian based supported distributions).

If you are in a rush and/or are too pro to skip this, I have also provided a Shell script. The shell script can be found HERE! but I recommend reading this post to make sure nothing is skipped and the installation of Microsoft SQL Server 2019 goes smoothly.

codeonion:~$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04 LTS
Release:	20.04
Codename:	focal

Lets Begin Installation of Microsoft SQL Server 2019 in Ubuntu 20.04

Install software-properties-common

sudo apt install software-properties-common
sudo apt-get update

Import the public repository GPG keys:

wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

Register the Microsoft SQL Server Ubuntu repository for SQL Server 2017:
https://packages.microsoft.com/config/ubuntu/20.04/

sudo add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/18.04/mssql-server-2019.list)"

Install Microsoft SQL Server 2019 in Ubuntu

sudo apt update
sudo apt install mssql-server

We are recommended to run a command

So lets run it
sudo /opt/mssql/bin/mssql-conf setup

Pick your Microsoft SQL Server 2019 Edition

When prompted, accept the license and then set up a PASSWORD


Confirm Microsoft SQL Server 2019 Active Status

systemctl status mssql-server.service 

Should show active running database server



Install Microsoft SQL TOOLS mssql-tools

Lets now install mssql-tools. But first!! Acquire the power of Sudo Su!

sudo su

This breaks all the walls and lets you do whatever the crap you want. So be careful :). Now do the following.

curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/19.10/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt update 
sudo ACCEPT_EULA=Y apt install mssql-tools unixodbc-dev

Configure PATH for MS SQL binaries

curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/19.10/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt update 
sudo ACCEPT_EULA=Y apt install mssql-tools unixodbc-dev

Now connect to your server using

sqlcmd -S 127.0.0.1 -U sa -P <yourpassword>

Shell Script to Install Microsoft SQL Server 2019 in Ubuntu 20.04

Finally, I will be an ass if I didn’t make a shell script of this process so:

First

sudo su

Then run the following shell script (replace your password at the bottom of the script)

!/bin/bash
lsb_release -a
sudo apt install software-properties-common -y
sudo apt install curl -y
sudo apt-get update
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
sudo add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/18.04/mssql-server-2019.list)"
sudo apt-get update
sudo apt-get install -y mssql-server
sudo /opt/mssql/bin/mssql-conf setup
systemctl status mssql-server --no-pager
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list | sudo tee /etc/apt/sources.list.d/msprod.list
sudo apt-get update
sudo apt-get install mssql-tools unixodbc-dev -y
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
sqlcmd -S 127.0.0.1 -U sa -P <YOUR PASSWORD HERE>

Then test the following query

SELECT Name from sys.Databases;
GO

And you will see:

That may be the end of it. Let me know if it helped. Please comment and share if it helped. Lets us know.

Thanks.

Categories
Laravel Programming

Laravel 5.8 Creating a MVC project with CRUD in 5 steps

This Laravel tutorial deals with the Installation, Setup and Basic Laravel MVC usage to open a page with intro to the CRUD operations.

Don’t know how to setup a new Laravel project or you are a 20 year old pro who is too pro to touch the basics? This is the right place to be.  I’ll keep referencing this tutorial whenever Installation is needed in my other Laravel posts.

It is expected that you are familiar with the basics of windows and linux server administration. If you need more help then please use Google. But I will try to avoid the basics to make sure that the goals are achieved without any fuss.

Now I don’t joke around. As per the tradition of this blog, I will make sure that you achieve this goal with the least effort wasted on figuring out wtf is this blog talking about. Let me know in the comments if you find it helpful. So let’s get started!

The 12345 Steps 🙂 :

  1. Setup of new project and running the server to make sure it bites.
  2. Creating a Database (mysql)
  3. Performing Migration to create schema
  4. Controller to repeatedly insert and render a View
  5. Test! and Conclusion

1. Setup and running new project

Lets learn how to install a new Laravel project with running a server on default port 8000.

Before we start, it is important that you should simply follow the official documentation for the latest Laravel Version installation guideline. I don’t want you to look backward when mentioning my blog. 

Source: https://laravel.com/docs/5.8/installation

So create a folder in your drive and open the console in it like so:

Opening the Laravel root project folder in windows command prompt or terminal
Opening the Laravel root project folder in windows command prompt or terminal

Now, lets create a project by running the following command in console:

laravel new codeonion_tutorial 

This creates a “codeonion_tutorial” folder and will start downloading the assets we need.

Creating a new Laravel project
Creating a new Laravel project

After a decade of waiting, the project will be ready. Now let’s make sure that it is running.

  • I go into the codeonion_tutorial project by  cd codeonion_tutorial
  • Start the Server:

php artisan serve

  • Visit the IP address as provided by the console output. Mine by default shows http://localhost:8000
  • So it works. You can now create a database.

2. Creating a Database (mysql)

Lets learn how to create a database in phpmyadmin for a Laravel project. But first, lets enjoy this breathtaking performance by the star of this blog.

Dancing Banana
Dancing Banana

You might be using XAMPP, LAMPP or plain old terminal based mysql server. I don’t care. AS a professional, you must have to know how to create a database. Heck! You must be able to follow this tutorial with using other database engines as well. So help yourself and learn that part as well. Let me know if you want me to make a tutorial about that. Otherwise, just keep following.

I am using Windows and Xampp. Run the Mysql server and open phpmyadmin

Running a Xampp Server for phpmyadmin
Running a Xampp Server for phpmyadmin

Then visit http://localhost/phpmyadmin/

phpmyadmin interface
phpmyadmin interface

Now, let’s create a database. Press New as shown below:

Create a new Database in phpmyadmin
Create a new Database in phpmyadmin

A Create database page will open which is explained below:

Write name of database and press create
Write name of database and press create
  1. Write name of your database to be.
  2. Press Create
  3. Done! (but also note these sub points)
    1. It could
      1. Fail if it violates any rules of database server
      2. It could also fail if your database is not allowed
      3. It could also fail if your Hosting service limits you by number of databases you can make
    2. Now how many bloggers would tell you about these things !! ;D

3. Performing Migration to create schema

Here, lets learn how to perform migrations and database configuration in Laravel.

Nothing is easy nowadays. You have publishers destroying true game developers and companies and then you have web frameworks made confusing by ignorant bloggers. I am all of them combined. So let’s configure our project database for migrations.

  • Our composer installation of the Laravel has already set the .env configuration file in place. But let’s do that manually to exercise the process.
Pointing out the .env configuration file of the Laravel Project
Pointing out the .env configuration file of the Laravel Project
  • Go to the terminal/command line and execute the following command

The .env file will be created and we will now configure it for our database. Open the .env file in the root folder of your newly created project and find the following highlighted database configuration

Editing the .env configuration file in Laravel
Editing the .env configuration file in Laravel

Lets set it to match our database

Laravel default phpmyadmin mysql configuration
Laravel default phpmyadmin mysql configuration

Migrations

First we have to clean the migration files created by composer. Go to the database/migrations/ folder and delete all files.

Now let’s create a migration file. Execute the following command from the root folder of the project.

php artisan make:migration create_messages_table
Creating migration files in Laravel
Creating migration files in Laravel

Now from the root folder, go to database/migrations/ folder and open the latest file which was created. Migration file that was created for me was:

2019_07_14_162743_create_messages_table.php

It has a timestamp along with the name I designated in the filename.

Open the file and lets add commands to create our “messages” table..

Initially, it will contain up and down functions (which handle what happens when we want the executions to be at up or down state in our database server).

Basic Laravel migration file usage
Basic Laravel migration file usage

Lets add the following line after the “id” column line in the up() function

$table->string(‘message’);

Editing the laravel migration file to refer to the table column
Editing the laravel migration file to refer to the table column

Lets run the migration using 

php artisan migrate

Laravel migration process
Laravel migration process

Note that if you screwed up, then you can “undo” the migration using php artisan migrate:rollback but it is not necessary to do now.

At this time, go to phpmyadmin and you will see that our table has been created.

Table updated in phpmyadmin after migration was performed in Laravel
Table updated in phpmyadmin after migration was performed in Laravel

Now, lets make a web page which repeatedly inserts into that table and fetches all and displays into a page. Sweet!

4. Controller to repeatedly insert and render a View

Lets learn how to create a Model, controller, view and route for our Laravel project.

Our database is connected, migrations are up. Now we need to populate the table and then we need to display it on the screen. So lets start without any regular fuss that I am used to deliberately provide to you include this once.

MODEL CREATION

Lets learn how to create a Model for the messages table. This model will be used by the controller.

First, lets create a model by executing this command

php artisan make:model Message

Open the model file at root/app/Message.php and change its content to make sure that it points to the correct table. Add the highlighted line and save it.

Model referring to the database table
Model referring to the database table

Now we can use the model in our controller.

CONTROLLER CREATION

Lets learn how to make a controller for our view. This controller will call out modal to add a random message and fetch all messages.

We need to create a controller. From the root folder, execute this command
php artisan make:controller MessageHandler

Creating a controller in Laravel using command line
Creating a controller in Laravel using command line

This will create a controller file in rootfolder/app/Http/Controllers

Open the root/app/Http/Controllers/MessageHandler.php and change the contents of the controller file as follows:

Laravel controller to insert into table  and get all the records to display in a web page
Laravel controller to insert into table and get all the records to display in a web page

This controller code:

  1. Creates a random message
  2. Saves it to the database in messages table.
  3. Retrieves all the messages
  4. Displays them in separate lines

Now, let’s make a route

ROUTE

Lets learn how to make a route for our controller.’s process_and_display action

Open root/routes/web.php and add this to the bottom of it:

Route::get(‘show_message’, ‘MessageHandler@process_and_display’);

We are now done with the MVC!

5. Test! and Conclusion

So we have done it all. Lets go to the http://localhost:8000/show_message and see what happens after we refresh the page several times.

Successfully showing the tutorial output
Successfully showing the tutorial output
[jetpack_subscription_form show_only_email_and_button=”true” custom_background_button_color=”undefined” custom_text_button_color=”undefined” submit_button_text=”Dancing BananaSubscribe For More” submit_button_classes=”undefined” show_subscribers_total=”true” ]

You should now review the above steps. Go over the project you created and learn what was done in each step.Read documentation and learn more.

Please let me know in the comments about this post and tell me if there is more I can do. We have now learnt about Installation, Setup and Basic Laravel MVC usage to open a page with intro to the CRUD operations .

android autocomplete camera code codeiginter 3 Codeigniter codeigniter 3 computer vision CSS database files focal fossa help helpful how how to HTML HybridIgniter install installation java knoppix laravel learn libraries linux mvc open opencv OpenCV4Android PHP plugin project Review – Web Design WYSIWYG SDK solution sudo terminal touchpad tutorial ubuntu ubuntu 20.04 update upload wordpress

Categories
Linux Review

Review: Don’t Use Microsoft Teams Preview in Ubuntu 20.04 as of May 2020 until bugs are fixed.

So I have been using teams regularly on Ubuntu 20.04. Things that I noticed were:

  • Mid-call crashes
  • Worst call quality (I could hear the electrons around the atoms)
  • Not being able to find the buttons to control screen (expecting in future)
  • Caused a Mergelist corruption when running apt-get update

TL;DR; I had to UNINSTALL MICROSOFT TEAMS. And I’ll suggest not using teams until it is no longer in Preview

BUT!

This is not why I am posting this. The reason I am posting this is because it messed with my Ubuntu 20.04 system.

I saw a red warning symbol in my notification that said that I was not able to update my system.

apt-get update could not work. Upon inspection, I found this:

codeonion@codeonion-ThinkPad-P50:~$ sudo apt-get update
[sudo] password for codeonion: 
Hit:1 http://ppa.launchpad.net/lutris-team/lutris/ubuntu focal InRelease
Hit:2 http://dl.google.com/linux/chrome/deb stable InRelease                                                                                                                            
Hit:3 http://security.ubuntu.com/ubuntu focal-security InRelease                                                                                                                        
Hit:4 http://ppa.launchpad.net/stebbins/handbrake-releases/ubuntu focal InRelease                                                                                                       
Hit:5 http://pk.archive.ubuntu.com/ubuntu focal InRelease                                                                                                                               
Hit:6 http://packages.microsoft.com/repos/vscode stable InRelease                                                                                                                       
Hit:7 http://pk.archive.ubuntu.com/ubuntu focal-updates InRelease                                                                                                                       
Hit:8 https://dl.winehq.org/wine-builds/ubuntu focal InRelease                                                                                                                          
Hit:9 https://download.sublimetext.com apt/stable/ InRelease                                                                                                         
Hit:10 http://pk.archive.ubuntu.com/ubuntu focal-backports InRelease                                           
Hit:11 https://packages.microsoft.com/ubuntu/18.04/mssql-server-2019 bionic InRelease    
Hit:12 https://packages.microsoft.com/ubuntu/18.04/prod bionic InRelease
Hit:13 https://packages.microsoft.com/ubuntu/19.10/prod eoan InRelease
Hit:14 https://packages.microsoft.com/repos/ms-teams stable InRelease
Hit:15 https://dbeaver.io/debs/dbeaver-ce  InRelease
Reading package lists... Error!
E: Malformed Description-md5 line; doesn't have the required length (32 != 33) '"129fb0c:f9aeae8e8d848457773b5c4e'
E: Malformed Description-md5 line; doesn't have the required length (32 != 33) '"129fb0c:f9aeae8e8d848457773b5c4e'
E: Encountered a section with no Package: header
E: Problem with MergeList /var/lib/apt/lists/pk.archive.ubuntu.com_ubuntu_dists_focal_universe_i18n_Translation-en
E: The package lists or status file could not be parsed or opened.

Mergelist problem

E: Malformed Description-md5 line; doesn't have the required length (32 != 33) '"129fb0c:f9aeae8e8d848457773b5c4e'
E: Malformed Description-md5 line; doesn't have the required length (32 != 33) '"129fb0c:f9aeae8e8d848457773b5c4e'
E: Encountered a section with no Package: header
E: Problem with MergeList /var/lib/apt/lists/pk.archive.ubuntu.com_ubuntu_dists_focal_universe_i18n_Translation-en

The following had to be done to fix this

sudo rm -r /var/lib/apt/lists/*
sudo mkdir /var/lib/apt/lists/partial
sudo apt-get update

It worked partially but apt-get update still gave me a Mergelist problem.

So I had to UNINSTALL MICROSOFT TEAMS

Then, when I ran

sudo rm -r /var/lib/apt/lists/*
sudo mkdir /var/lib/apt/lists/partial
sudo apt-get update

The system got back on its feet, the warning notification disappeared. Looks like until it is in preview, I’ll stick to using Teams on the web only.

Special Thanks to this Gist. @d2s, you are a lifesaver.

Categories
Programming Python

Run Python Scripts using AutoHotkey and Pass Arguments

So you have a python script that has some code like:

import argparse

# GET ORDER ID
parser = argparse.ArgumentParser(description='For blog.codeonion.com my visitors!')
parser.add_argument("--argument_to_be_passed", required=True, type=str, help="Please pass a value into --argument_to_be_passed")
args = parser.parse_args()

value = args.argument_to_be_passed
print(value)

Now, if we run this script, this is the output:

Execution without passing arguments

But if we pass arguments manually:

Arguments are getting passed manually and then printed on command line.

So you see, it is working. But this is slow and boring.

What if you wanted to automate running a python script in order to QUICKLY test something and development purpose!

I know from experience the process of ALT+TAB into a CMD and then pressing UP arrow and press enter is a repetitive labour. Lets reward ourselves with Autohotkey’s automation and buy some extra minutes into the already tightened day.

ENTER THE AUTOHOTKEY!

Once you have installed AutoHotkey, it is time write this script:

; Autoexecute
    #NoEnv
    #SingleInstance force
return
#^space::
    run cmd.exe
    WinWait, ahk_exe cmd.exe ; Wait for CMD to start
    Send c:{enter} ; Go to C drive
    Send cd C:\python\blog\{enter} ; go to script's folder
    Send python arguments.py --argument_to_be_passed CODEONION{enter}
return

Make sure the path to python script is correct. Run this AutoHotkey script file and then, use CTRL+WINDOWSKEY+SPACE to run the macro. And enjoy the spam show!

See it in action!

https://gist.github.com/codeonion/a348f3cc3e580347266fec8f1de6c0d4

Get code from my Github Gist

I really hope this made your day! Please commend and share if oyu are feeling generous. Thanks! and have a nice day!

Categories
Godot Engine Programming

Learn Godot 3 GDScript, Calling an API and parsing JSON

So you think that Godot can’t handle general purpose utility and non-game applications? I am trying to answer this question and this post is part of my attempt to use Godot for apps which are not games at all.

As a web application developer, I have decided that this post should deal with using Godot to call an API on a server and then fetch some JSON data. Afterwards, I will parse the data and maybe print it in the console.

It is expected that:

  • You know what is Godot
  • You have Godot Installed already
  • You have some basic knowledge of Game development and Godot usage. Not like my codeigniter and Android series (RIP maybe?)

So what is Godot Engine? Godot engine is…. well fk it. My last post was in 2016 so I’ll skip the bs.

We are going to use the APIs available at the following links but you can use any JSON dataset of your own choice and your own API end poitns

https://jsonplaceholder.typicode.com/todos

Get All Todo list items https://jsonplaceholder.typicode.com/todos
Get Single Todo list item by user idhttps://jsonplaceholder.typicode.com/todos/{id}
E.g.
https://jsonplaceholder.typicode.com/todos/8

Data looks like
{
“userId”: 1,
“id”: 8,
“title”: “quo adipisci enim quam ut ab”,
“completed”: true
}

With Godot installed, and my API url ready, lets get into action.

So I have a new project with a scene containing nodes like

Nodes in the scene

And the scene itself is organized like this with some poor design choices made to make sure I don’t get lost in the midst of working on this

Just setting up the stage for ladies and gentlemen

Due to lack of talent, I first chose to create a visual script on the button shown above. But then I realized that it was lacking in some HTTPRequest departments so I instead went with GDScript. Otherwise, Visual Scripting is pretty good!

Ich bin ein mann, Der Mann

Attach a GDScript to the Canvas Layer

Save it

Now, we need to connect the following two signals to the CanvasLayer script node. To do this:

  1. Button’s pressed() signal
  2. HTTPrequest’s request_completed( int result, int response_code, PoolStringArray headers, PoolByteArray body ) signal
Steps to connect the signal of Button

Do the same for HTTPRequest’s request_completed( int result, int response_code, PoolStringArray headers, PoolByteArray body ) signal as well.


Now lets edit the code. Click on the Script icon next to the CanvasLayer

Click to start scripting
The auto-generated functions will be used to call API

Lets replace this code with this

extends CanvasLayer

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

func _on_Button_pressed():
	print("Requesting")
	$HTTPRequest.request("https://jsonplaceholder.typicode.com/todos/8")

func _on_HTTPRequest_request_completed( result, response_code, headers, body ):
	print("Processing the Response")
	var json = JSON.parse(body.get_string_from_utf8())
	print(json.result)

Lets run the program

We are successfully calling the API

But lets up the anti and show this response in RichTextLabel. To do that, we will

  1. Get the values from the JSON response
  2. Show it in the RichTextLabel

So lets update our script and use the following code and run the program.

extends CanvasLayer

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

func _on_Button_pressed():
	print("Requesting")
	$HTTPRequest.request("https://jsonplaceholder.typicode.com/todos/8")

func _on_HTTPRequest_request_completed( result, response_code, headers, body ):
	print("Processing the Response")
	var json = JSON.parse(body.get_string_from_utf8())
	var api_result = (json.result)
	
	# Get the handle of RichTextLabel
	var rtl = get_node("RichTextLabel")
	
	# Clear the RichTextLabel to  avoit clutter
	rtl.clear()
	
	# Concatenate the text of the RichTextLabel on separate lines
	rtl.text += var2str(api_result["userId"]) + "\n"
	rtl.text += var2str(api_result["id"]) + "\n"
	rtl.text += api_result["title"] + "\n"
	rtl.text += var2str(api_result["completed"]) + "\n"
The JSON output is now called, processed (a bit) and shown in the RichTextLabel

So, we did it! In the next post, I will continue this quest and we will look into using headers and secure authentication. Thanks for taking interest. Lets spread the world and learn together.

Join the Godot Engine’s Discord server https://discordapp.com/invite/zH7NUgz

Please do share this post and let me know what more I can do to improve this post and what I can do in the next posts.

Thanks
Codeonion

Categories
Programming

LibGDX Android Studio: Download and set up a new LibGDX Project

Hey fellow developers!

Welcome to the beginning of LibGDX for Android tutorials. In this tutorial, you will learn how to download, setup and create a new LibGDX project in Android Studio.

At the end of this tutorial, you will:

  1. Download LibGDX
  2. Setup LibGDX
  3. Create a new LibGDX project in Android Studio

So lets get Started!


Download LibGDX

First of all, lets download LibGDX. (I am assuming that you already have Android Studio.)

  1. Go to official LibGDX website.
  2. Go to Download
  3. Download (Duh!)
  4. And open the folder

This process is given here

 LibGDX Android Studio - Download

Now, we will setup LibGDX for our project.


Setup LibGDX

Now, we will setup the LibGDX project using the downloaded gdx-setup.java file.

  1. First of all, fill in the basic project information
    1. Run gdx-setup.java
    2. Provide your Project name.
    3. Provide package information according to your settings
    4. Game Class is the java class file name that you will eventually be working with.
    5. Destination is where you will work on your project.
    6. Android SDK is where your Android SDK is installed. Give its path.
  2. Sub-Projects is where you provide the platforms that you wish to support.
    1. Chose Android
      (Only because this is an android based tutorial. But you are not limited to that.)
  3. Extensions is where you tell the setup what extensions to load.
    1. For simplicity, just chose Box2d
      (you can learn more later)
  4. Press Generate
    1. Wait until the download completes.

Here is the screen shot of my completed setup.

This entire process is given below.

 LibGDX Android Studio - Setup

Now, we will open this project in Android Studio


Open in Android Studio

Follow these steps to load the LibGDX project in Android Studio

  1. Open Android Studio
  2. Click Import Project
    • Here is how
  3. Give path to the LibGDX download location (which you provided in setup) and press OK
    • Here is how
  4. Wait till the project is loaded in Android Studio

This entire process is given below:

LibGDX Android Studio - Load project in Android Studio

This is it. You have just loaded LibGDX in Android Studio. Now lets run it in Android Virtual Device 😀


Run LibGDX in Android Virtual Device

Follow these steps to run your new LibGDX project in AVD

  1. Launch your Android Virtual Device (AVD)
  2. Press the Run button in Android Studio
  3. Now, the app will run on your AVD. Done!

This process is given below:

LibGDX Android Studio -Launch app in AVD

This is it. You have just created and run a new LibGDX project in Android Studio.

Lets draw some shapes in the next tutorial.

Return to the LibGDX Tutorials

Categories
Android OpenCV Programming

Use OpenCV to show camera on android App with correct orientation

Return to OpenCV 4 Android Tutorials List

In this series of tutorials, you are learning OpenCV for Android using Android Studio. So far, you have made a working OpenCV Android Studio Project containing OpenCV module.

In Here is the overview of what we are going to achieve:

  • Create an OpenCV for Android Project (As in previous tutorial in this series) (Here)
  • Show Camera on the Screen
    1. Edit Manifest
      1. Add permission to allow camera.
      2. Support various screen sizes and adaptability of camera.
      3. Use specific features of the camera.
    2. Add a custom Layout show_camera.xml to display camera in it.
    3. Edit MainActivity_show_camera.java 
      1. Import required android classes
      2.  Import OpenCV classes
      3. Connect to OpenCV manager
      4. Initiate LogCat to log events of out app
      5. SHOW CAMERA ON LAYOUT
      6. Corrected Orientation (portrait)

Trust me, it is very simple to do. Lets do it!


 

Manifest.xml

We need to edit the AndroidManifest.xml file like following:

  1. Allow permission to use camera
    <uses-permission android:name="android.permission.CAMERA"/>
  2. Allow camera to optimize to the dimensions of the device in use
    <supports-screens android:resizeable="true"
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:anyDensity="true" />
  3. Use Front camera and autofocus of camera :S
     <uses-feature android:name="android.hardware.camera" android:required="false"/>
        <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
        <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
        <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

The Manifest.xml file in its entirety is given here

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="opencv.codeonion.com.opencv_test">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >
        <activity
            android:name=".MainActivity_show_camera"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <supports-screens   android:resizeable="true"
                        android:smallScreens="true"
                        android:normalScreens="true"
                        android:largeScreens="true"
                        android:anyDensity="true" />

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

</manifest>

 

This entire process is given here:

Show camera on android App using OpenCV for Android - Edit Manifest

This is all you need to do in AndroidManifest.xml


Create a new layout (show_camera.xml )

Now in your project, do the following:

  1. Create a new layout called show_camera.xml
  2. Add the following code it to:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        xmlns:opencv="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent">
    
        <org.opencv.android.JavaCameraView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:visibility="gone"
            android:id="@+id/show_camera_activity_java_surface_view"
            opencv:show_fps="true"
            opencv:camera_id="any" />
    
    </LinearLayout>

    Note that the JavaCameraView has the id of show_camera_activity_java_surface_view

This is given below:

 


MainActivity_show_camera.java

Import the following Android Classes in your MainActivity_show_camera:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

Import the following OpenCV classes in your MainActivity_show_camera:

import org.opencv.android.JavaCameraView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

Now, lets work with the MainActivity_show_camera Class 🙂 (Code in the end). I will explain every line of OpenCV code in detail.

  • Implement the OpenCV class CvCameraViewListener2 to allow OpenCV to communicate with android camera functionalities.
public class MainActivity extends AppCompatActivity implements CvCameraViewListener2 {
  • Declare the following items in the class
    // Used for logging success or failure messages
        private static final String TAG = "OCVSample::Activity";
    
        // Loads camera view of OpenCV for us to use. This lets us see using OpenCV
        private CameraBridgeViewBase mOpenCvCameraView;
    
        // Used in Camera selection from menu (when implemented)
        private boolean              mIsJavaCamera = true;
        private MenuItem             mItemSwitchCamera = null;
    
        // These variables are used (at the moment) to fix camera orientation from 270degree to 0degree
        Mat mRgba;
        Mat mRgbaF;
        Mat mRgbaT;
  • Now, lets call OpenCV manager to help our app communicate with android phone to make OpenCV work
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
            @Override
            public void onManagerConnected(int status) {
                switch (status) {
                    case LoaderCallbackInterface.SUCCESS:
                    {
                        Log.i(TAG, "OpenCV loaded successfully");
                        mOpenCvCameraView.enableView();
                    } break;
                    default:
                    {
                        super.onManagerConnected(status);
                    } break;
                }
            }
        };
    • CameraBridgeViewBase mOpenCvCameraView
      This variable acts as a bridge between camera and OpenCV library.
    • BaseLoaderCallback mLoaderCallback = …..
      Well, once OpenCV library is loaded, you may want to perform some actions. For example, displaying a success or failure message.
  • Initiate the LogCat
    public MainActivity_show_camera() {
            Log.i(TAG, "Instantiated new " + this.getClass());
        }
  • Now, when the activity is created, display the OpenCV camera in the layout. show_camera.xml.
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            Log.i(TAG, "called onCreate");
            super.onCreate(savedInstanceState);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    
            setContentView(R.layout.show_camera);
    
            mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);
    
            mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    
            mOpenCvCameraView.setCvCameraViewListener(this);
        }
  •  The following three functions handle the events when the app is Paused, Resumed and Closed/Destroyed
    @Override
        public void onPause()
        {
            super.onPause();
            if (mOpenCvCameraView != null)
                mOpenCvCameraView.disableView();
        }
    
        @Override
        public void onResume()
        {
            super.onResume();
            if (!OpenCVLoader.initDebug()) {
                Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
                OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
            } else {
                Log.d(TAG, "OpenCV library found inside package. Using it!");
                mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
            }
        }
    
        public void onDestroy() {
            super.onDestroy();
            if (mOpenCvCameraView != null)
                mOpenCvCameraView.disableView();
        }
  • Now, we will do two main things:
    • Receive Image Data when the camera preview starts on your screen 😀
      public void onCameraViewStarted(int width, int height) {
      
              mRgba = new Mat(height, width, CvType.CV_8UC4);
              mRgbaF = new Mat(height, width, CvType.CV_8UC4);
              mRgbaT = new Mat(width, width, CvType.CV_8UC4);
          }
    • Destroy image data when you stop camera preview on your phone screen
      public void onCameraViewStopped() {
              mRgba.release();
          }
    • Now, this one is interesting! OpenCV orients the camera to left by 90 degrees. So if the app is in portrait more, camera will be in -90 or 270 degrees orientation. We fix that in the next and the most important function. There you go!
          public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
      
              // TODO Auto-generated method stub
              mRgba = inputFrame.rgba();
              // Rotate mRgba 90 degrees
              Core.transpose(mRgba, mRgbaT);
              Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
              Core.flip(mRgbaF, mRgba, 1 );
      
              return mRgba; // This function must return
          }

The entire code is given below:

package opencv.codeonion.com.opencv_test;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

import org.opencv.android.JavaCameraView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

// OpenCV Classes

public class MainActivity_show_camera extends AppCompatActivity implements CvCameraViewListener2 {

    // Used for logging success or failure messages
    private static final String TAG = "OCVSample::Activity";

    // Loads camera view of OpenCV for us to use. This lets us see using OpenCV
    private CameraBridgeViewBase mOpenCvCameraView;

    // Used in Camera selection from menu (when implemented)
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    // These variables are used (at the moment) to fix camera orientation from 270degree to 0degree
    Mat mRgba;
    Mat mRgbaF;
    Mat mRgbaT;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

    public MainActivity_show_camera() {
        Log.i(TAG, "Instantiated new " + this.getClass());
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "called onCreate");
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.show_camera);

        mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);

        mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);

        mOpenCvCameraView.setCvCameraViewListener(this);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    public void onCameraViewStarted(int width, int height) {

        mRgba = new Mat(height, width, CvType.CV_8UC4);
        mRgbaF = new Mat(height, width, CvType.CV_8UC4);
        mRgbaT = new Mat(width, width, CvType.CV_8UC4);
    }

    public void onCameraViewStopped() {
        mRgba.release();
    }

    public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

        // TODO Auto-generated method stub
        mRgba = inputFrame.rgba();
        // Rotate mRgba 90 degrees
        Core.transpose(mRgba, mRgbaT);
        Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
        Core.flip(mRgbaF, mRgba, 1 );

        return mRgba; // This function must return
    }
}

The entire process of editing MainActivity_show_camera.java is shown here:

Show camera on android App using OpenCV for Android - MainActivity_show_camera


Note: The camera disorientation problem is a bitch an issue not to be takien lightheartedly. Thanks for noting.

This concludes this tutorial, now that you have created a camera app, it is now time to continue this and perform more Computer Vision! In the next tutorial, I will draw a simple object on the screen. Be sure to check out the list of OpenCV for Android tutorials for latest tutorials.

Thanks for reading, and please share and comment if this helped and to share your ideas and opinions.

Return to OpenCV 4 Android Tutorials List

Categories
Programming

Update Knoppix 7.6 from Terminal

So you downloaded Knoppix and realized that it is a little bit rusty. There is a way to make it fresh and update all the packages with two simple commands.

First you need to Refresh the packages database. Go to terminal and type the following command and press enter.

sudo apt-get update

 

This will initiate an activity on the terminal that will download the latest packages information. This will take a few minutes. After the activity finishes, you will have the latest packages information. This is time to Upgrade the packages that are already installed in your Knoppix system to the latest versions that are available in online repositories.

Simply, type in the following command in terminal:

sudo apt-get upgrade

 

This will initiate a download activity on your terminal that will download all the upgradable packages from online repositories. This will take longer than the “update” activity.

At the end, you will have the latest packages installed and you will be running smooth!

 

Categories
Android OpenCV Programming

Creating a new OpenCV project in Android Studio

Return to OpenCV for Android Tutorials List

In this tutorial, we will create a new OpenCV project in Android Studio. Since you have everything downloaded already, we are ready to move on. By the end of this tutorial, you will have a new project set up, which you can use to build your projects upon. So lets do some CV!

Note: This tutorial has been tested on Android Studio 1.5 and 2.0

In short, the steps are, (2) Create simple project. (3) Import OpenCV SDK as a Module in Android Studio. (4) Set OpenCV Version. in Project (5) Fix Library association in project. (6) Done! Now actual OpenCV code can be written in future. The longer and detailed guided tutorial is given below.

  1. I beg you to open Android studio.
  2. Create a new project
    • I named it “OpenCV_Test”. (It could be different in the following GIF)
    • Minimum SDK is “API 19: Android 4.4 (KitKat).
    • Default Activity is “Basic Activity” (easily changeable later on)
    • Activity name is “MainActivity” (i.e. default settings)
    • I have shown the entire process in this GIF.
      Android-Studio-Create-New-Project
    • After pressing Finish, Gradle will perform some processes and eventually, you will be presented with your Android project.
    • Now, we can start importing OpenCV into the project.
  3. Import the OpenCV for Android SDK module in Android Studio.
    • To import the OpenCV SDK as a module in your project, go to File>New>Import Module.
    • Then Give path to your OpenCV as ..\OpenCV-android-sdk\sdk\java
    • You can chose to modify your module’s name.
    • Press Next and Finish the Dialogue.
    • The entire process is given here:
      OpenCV-Android-Import-Module-Android-Studio
    • Note that in the end, there are some errors in the code as well as the console. This is because you need to fix the Version number and link the libraries with your own project. This is shown in the next two steps.
  4. In this step, we will fix the Android Project SDK information in the OpenCV build.gradle file.
    • In project explorer, switch to Project view.
    • Go to OpenCVLibrary300 > build.gradle file and open it.
      • I have updated the contents of the file with the following code
        apply plugin: 'com.android.library'
        
        android {
            compileSdkVersion 23
            buildToolsVersion "23.0.2"
        
            defaultConfig {
                minSdkVersion 19
                targetSdkVersion 23
            }
        
            buildTypes {
                release {
                    minifyEnabled false
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
                }
            }
        }
      • Note that the android project’s SDK information can be obtained from the project’s own build.gradle file.
    • Once the Android SDK settings are updated, press “Try Again” button.
    • This entire process is given below:
      OpenCV-Android-Update-DefaultProject-SDK-Information
    • Now. we need to fix library association.
  5. Looking good so far! We now need to make sure that the OpenCV for Android libraries are associated with our Android Studio project. Currently, Android Studio will not recognize the OpenCV code that we type in our files. We fix this as follows.
    • Go to File>Project Structure.
    • When window opens, under Modules, select app.
    • Click Dependencies.
    • Click +.
    • Select Module Dependencies.
    • (In my case) Select :openCVLibrary300.
    • Press Ok and Ok.
    • After a few seconds, the libraries will be associated with your Android project.
    • This entire process is shown here:
      OpenCV-SDK-library-association
    • You can now write more OpenCV code in future in the same project.
  6. We did it! Project is ready for future OpenCV development.

This concludes this tutorial. You are now ready to start making your own Android Studio Project that consists of OpenCV SDK features limited only by your imagination. In the next tutorial, I will SHOW CAMERA on android app screen using OpenCV. Make sure that you read it. Do not forget to SHARE this post and write your opinions, ideas and views  in the  COMMENT  section below.

Thanks for reading :). Please like my Facebook page and follow my Twitter for more tutorials.

Return to OpenCV for Android Tutorials List