runtimeerror: attempting to deserialize object on a cuda device

runtimeerror: attempting to deserialize object on a cuda device but torch.cuda.is_available() is false. if you are running on a cpu-only machine, please use torch.load with map_location=torch.device(‘cpu’) to map your storages to the cpu, How to solve the error presented here with Pytorch in python in the context of deeplearning?

runtimeerror: attempting to deserialize object on a cuda device but torch.cuda.is_available() is false. if you are running on a cpu-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the cpu, How to solve the error presented here with Pytorch in python in the context of deeplearning?

Introduction

First of all, usually this error is encountered when trying to run your model code on the machine’s CPU instead of the GPU.

lib/python3.6/site-packages/torch/serialization.py", ... in validate_cuda_device
    raise RuntimeError('Attempting to deserialize object on a CUDA '
RuntimeError: Attempting to deserialize object on a CUDA device but 
  torch.cuda.is_available() is False. If you are running on a CPU-only machine, 
  please use torch.load with map_location='cpu' to map your storages to the CPU.

In this case you encounter an error which is a raised RuntimeError exception.

This means that you are looking to deserialize an object using code that runs with the GPU while the GPU is disabled.

Explanation – runtimeerror: attempting to deserialize object on a cuda device

Then, The error then occurs when you try to load the pytorch model using the torch.load instruction (see https://pytorch.org/docs/stable/generated/torch.load.html)

Example :

torch.load('mymodel.pt')

So when the reloading is done with the wrong configuration you get the error:

lib/python3.6/site-packages/torch/serialization.py", ... in validate_cuda_device
    raise RuntimeError('Attempting to deserialize object on a CUDA '
RuntimeError: Attempting to deserialize object on a CUDA device but 
  torch.cuda.is_available() is False. If you are running on a CPU-only machine, 
  please use torch.load with map_location='cpu' to map your storages to the CPU.

Solution

Also, As you can see in the Pytorch documentation (see https://pytorch.org/docs/stable/generated/torch.load.html) there is a map_location parameter – (a function, torch.device, string or a dict specifying how to remap storage locations).

This is where we must force the parameter to specify the location to use.

Note that if your model is registered and saved as using the GPU you will have to specify GPU otherwise you will have to put CPU. The objective here is to put a consistent parameter between what has been saved and what is reloaded.

And If you want to force CPU usage :

torch.load('mymodel.pt',map_location='cpu')

For CPU usage you can also use :

torch.load('mymodel.pt', map_location=torch.device('cpu'))
# Load on first GPU
torch.load('mymodel.pt', map_location=lambda storage, loc: storage.cuda(1))
# Lord on GPU 0 and 1
torch.load('mymodel.pt', map_location={'cuda:1':'cuda:0'})

External links :

https://pytorch.org/tutorials/beginner/saving_loading_models.html

https://pytorch.org/tutorials/recipes/recipes/save_load_across_devices.html

https://discuss.pytorch.org/t/saving-and-loading-a-model-in-pytorch/2610

Internal links – runtimeerror: attempting to deserialize object on a cuda device but torch.cuda.is_available() is false :

http://128mots.com/index.php/en/2020/11/20/deep-learning-pytorch-from-0-to-1-2/

http://128mots.com/index.php/en/category/non-classe-en/

importerror: iprogress not found. please update jupyter and ipywidgets

importerror: iprogress not found. And this is the solution if you get this error .

When trying to install Jupyter Widgets : Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html

importerror: iprogress not found. please update jupyter and ipywidgets

Error

You can check on the https://ipywidgets.readthedocs.io/en/stable/user_install.html to get the complete user install guide for Jupyter Widgets.

ImportError: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html

To solve this problem you need to setup Iprogress on jupyter lab :

pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension

importerror: iprogress not found – Internal Links :

http://128mots.com/index.php/category/python/

http://128mots.com/index.php/category/les-reseaux-sociaux/

http://128mots.com/index.php/en/2021/01/21/greedy-algorithm-python/

Note for old version of jupyter

Installing ipywidgets automatically configures Jupyter Notebook to use widgets.

This package does this by depending on the widgetsnbextension package. This package configures Jupyter Notebook to display and use widgets.

If you have an old version of Jupyter Notebook installed, you may need to manually enable the ipywidgets notebook extension with.

jupyter nbextension enable --py widgetsnbextension

Note for separate environnements between JupyterLab and IPython

If JupyterLab and the IPython kernel are installed in different environments.

You need to do it in 2 steps :

  1. Install jupyterlab_widgets
conda install -n base -c conda-forge jupyterlab_widgets
  1. Install ipywidgets on each kernels
conda install -n py36 -c conda-forge ipywidgets

importerror: iprogress not found – External Links :

https://ipywidgets.readthedocs.io/en/stable/user_install.html

https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html

Example using Python Jupyter Lab :

Now, to give change to an x ​​value of using these coins and banknotes, then we will check the first element in the array. And if it’s greater than x, we move on to the next element. Otherwise let’s keep it. Now, after taking a valuable coin or bill from the array of coinAndBill [i], the total value x we ​​need to do will become x – coinAndBill [i].

Here is the associated greedy python algorithm:

  pieceEtBillets = [500,200,100,50,20,10,5,2,1]
  i = 0
  while(x>0):
    if(pieceEtBillets[i] > x):
      i = i+1
    else:
      print(str(pieceEtBillets[i]))
      x -= pieceEtBillets[i];
renduMonnaieGlouton(33)#Exemple sur 33 euros

Greedy algorithm python – Coin change problem

A greedy python algorithm (greedy algorithm python) greedily selects the best choice at every step. He hopes that these choices lead to the optimal overall solution to the problem. So, a greedy algorithm does not always give the best solution. However in many problems this is the case.

A greedy python algorithm (greedy algorithm python) greedily selects the best choice at every step. He hopes that these choices lead to the optimal overall solution to the problem. So, a greedy algorithm does not always give the best solution. However in many problems this is the case.

Greedy Algorithm: Introduction

The problem of giving change is formulated as follows. How to return a given sum with a minimum of coins and banknotes?

Here is an example in python of the resolution of the problem:

If we consider the Euro monetary system without the cents we have the whole

EURO = (1, 2, 5, 10, 20, 50, 100, 200, 500)

Greedy algorithm python : Coin change problem

Now, to give change to an x ​​value of using these coins and banknotes, then we will check the first element in the array. And if it’s greater than x, we move on to the next element. Otherwise let’s keep it. Now, after taking a valuable coin or bill from the array of coinAndBill [i], the total value x we ​​need to do will become x – coinAndBill [i].

Here is the associated greedy python algorithm:

def renduMonnaieGlouton(x):
  pieceEtBillets = [500,200,100,50,20,10,5,2,1]
  i = 0

  while(x>0):
    if(pieceEtBillets[i] > x):
      i = i+1
    else:
      print(str(pieceEtBillets[i]))
      x -= pieceEtBillets[i];

renduMonnaieGlouton(33)#Exemple sur 33 euros

The output for 33 euro is then:

20
10
2
1

Another example with 55 euro of greedy python algorithm:

def renduMonnaieGlouton(x):
  pieceEtBillets = [500,200,100,50,20,10,5,2,1]
  i = 0

  while(x>0):
    if(pieceEtBillets[i] > x):
      i = i+1
    else:
      print(str(pieceEtBillets[i]))
      x -= pieceEtBillets[i];

renduMonnaieGlouton(55)#Exemple sur 55 euros

Output :

50
5

Conclusion

The problem of giving change is NP-difficult relative to the number of coins and notes of the monetary system considered (euro in this example). To go further, we can demonstrate that for certain so-called canonical money systems, the use of a greedy algorithm is optimal. A monetary system is said to be canonical if for any sum s the greedy algorithm leads to a minimal decomposition.

NP difficulty is the defining property of a class of problems informally “at least as difficult as the most difficult NP problems”.

A simple example of an NP-hard problem is the sum of subset problem. If P is different from NP then it is unlikely to find a polynomial time algorithm that exactly solves this problem.

External links :

http://math.univ-lyon1.fr/irem/IMG/pdf/monnaie.pdf

http://www.dil.univ-mrs.fr/~gcolas/algo-licence/slides/gloutons.pdf

Internal links python greedy algorithm :

http://128mots.com/index.php/category/python/

http://128mots.com/index.php/category/non-classe/

Levenshtein Python Algo implementation Wagner & Fischer

Here is the levenshtein python implementation of the Wagner & Fischer algorithm (Wagner-Fischer). It allows to calculate the distance of Levenshtein (distance between two strings of characters).

Here is the python implementation of the Wagner & Fischer algorithm (Wagner-Fischer). It allows to calculate the distance of Levenshtein (distance between two strings of characters).

First, the goal of the algorithm is to find the minimum cost. Minimal cost to transform one channel into another. Then a recursive function allows to return the minimum number of transformation. And to transform a substring of A with n characters into a substring of B with the same number of characters. The solution is given. We must calculate the distance between the 2 letters at the same position in the chain A and B. Then Either the letters and the previous letter are identical. Either there is a difference and in this case we calculate 3 costs. So the first is to delete a letter from the chain A. And insert a letter in the chain A to substitute a letter from the chain A. Then we can then find the minimum cost.

Example of levenshtein python implementation :

import numpy as np

def levenshtein(chaine1, chaine2):
    taille_chaine1 = len(chaine1) + 1
    taille_chaine2 = len(chaine2) + 1
    levenshtein_matrix = np.zeros ((taille_chaine1, taille_chaine2))
    for x in range(taille_chaine1):
        levenshtein_matrix [x, 0] = x
    for y in range(taille_chaine2):
        levenshtein_matrix [0, y] = y

    for x in range(1, taille_chaine1):
        for y in range(1, taille_chaine2):
            if chaine1[x-1] == chaine2[y-1]:
                levenshtein_matrix [x,y] = min(
                    levenshtein_matrix[x-1, y] + 1,
                    levenshtein_matrix[x-1, y-1],
                    levenshtein_matrix[x, y-1] + 1
                )
            else:
                levenshtein_matrix [x,y] = min(
                    levenshtein_matrix[x-1,y] + 1,
                    levenshtein_matrix[x-1,y-1] + 1,
                    levenshtein_matrix[x,y-1] + 1
                )
    return (levenshtein_matrix[taille_chaine1 - 1, taille_chaine2 - 1])

print("distance de levenshtein = " + str(levenshtein("Lorem ipsum dolor sit amet", "Laram zpsam dilir siy amot")))

To calculate the Levenshtein distance with a non-recursive algorithm. We use a matrix which contains the Levenshtein distances. Then These are the distances between all the prefixes of the first string and all the prefixes of the second string.

Also we can dynamically calculate the values ​​in this matrix. The last calculated value will be the Levenshtein distance between the two whole chains.

Finally there are many use cases of the Levenshtein distance. Levenshtein distance is used in domains. Computational linguistics, molecular biology. And again bioinformatics, machine learning. Also deep learning, DNA analysis. In addition, a program that does spell checking uses, for example, the Levenshtein distance.

Links on the Wagner & Fischer algorithm (Wagner-Fischer) and the Levenshtein python distance or other language:

https://graal.hypotheses.org/tag/algorithme-de-wagner-fischer

https://fr.wikipedia.org/wiki/Algorithme_de_Wagner-Fischer

https://fr.wikipedia.org/wiki/Distance_de_Levenshtein

https://medium.com/@sddkal/wagner-fischer-algorithm-be0d96893f6d

https://www.python-course.eu/levenshtein_distance.php

Internal links on algorithms

http://128mots.com/index.php/category/python/

http://128mots.com/index.php/category/graphes/

PyTorch how to load a pre-trained model?

There are several approaches to recording (serializing) and loading (deserialize) patterns for inference in PyTorch.

For example you may need to load a model that is already trained and back up that comes from the internet. More recently I answered this question on a discussion forum https://discuss.pytorch.org/t/i-want-to-do-machine-learning-with-android/98753. I take advantage of this article to give some details.

SAVE AND LOAD OF A PRE-TRAINED MODE with load_state_dict

In PyTorch you can save a model by storing in its file its state_dict these are Python dictionaries, they can be easily recorded, updated, modified and restored, adding great modularity to PyTorch models and optimizers.

In my example:

ESPNet is backed up with this method

https://github.com/sacmehta/ESPNet/tree/master/pretrained/encoder

I managed to load the encoder model using the ESPNet class that makes a load_state_dict

import torch
model = ESPNet(20,encoderFile="espnet_p_2_q_8.pth", p=2, q=8)
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
traced_script_module.save("model.pt")

The exit is

Encode loaded!

Note that ESPNet uses the default GPU and that an adaptation in Model.py in https://github.com/sacmehta/ESPNet/tree/master/train was required by replacing:

self.encoder.load_state_dict(torch.load(encoderFile)

By:

self.encoder.load_state_dict(torch.load(encoderFile,map_location='cpu'))

Otherwise if you don’t make this adjustment don’t have the ability to launch on a GPU you’ll get the following error:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location-torch.device ('cpu') to map your storages to the CPU.
PYTORCH TORCHSCRIPT

BACKUP AND LOAD BY PYTORCH SCRIPT

https://pytorch.org/docs/stable/jit.html

TorchScript is a way to create models that can be made that can be optimized from the PyTorch code.

Any TorchScript program can be saved from a Python process and loaded into a process where there is no Python dependency.

The code below allows you to save the pre-trained ESPNet model that was backed up by the classic torch.save method via the use of TorchScript.

import torch


model = ESPNet(20,encoderFile="espnet_p_2_q_8.pth", p=2, q=8)
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
#Exemple de save avec TorchScript
torch.jit.save(traced_script_module, "scriptmodel.pth")

An example for loader via TorchScript below:

import torch
model = torch.jit.load("scriptmodel.pth")

RESOURCES ON THE SUBJECT

https://pytorch.org/docs/stable/jit.html

https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html

https://stackoverflow.com/questions/53900396/what-are-torch-scripts-in-pytorch

Algorithm the problem of the backpack (Knapsack problem) in more than 128 words

The problem of the algorithmic backpack is interesting and is part of the first digital science and computer science program.

This problem illustrates the gluttonous algorithms that list all the possibilities of solving a problem to find the best solution.

The problem of the backpack is a problem of optimization, i.e. a function that must be maximized or minimized and constraints that must be met.

The problem of the backpack

For a backpack of maximum capacity of P and N items each with its own weight and a set value, throw the items inside the backpack so that the final contents have maximum value.

Example of a statement:

  • Maximum backpack capacity: 11 units
  • Item number: 5
  • Object Values: $10.50,20,30.60
  • Weight of Objects: '1,5,3,2,4'

What is the maximum value that can be put in the backpack considering the maximum capacity constraint of the bag which is 11?

Gluttonous algorithm

An effective solution is to use a gluttonous algorithm. The idea is to calculate the value/weight ratio for each object and sort the object based on this calculated ratio.

You take the object with the highest ratio and add until you can't add any more.

In fractional version it is possible to add fractions of item to the backpack.

Implementation of the problem in non-fractional version

Here is an implementation of the problem in a non-fractional version, i.e. you can't add a fraction of an object to the bag. Only whole objects can be added.

itemsac class: 
    def __init__ (self, weight, value, index): 
        self.index - index         
        self.weight - weight 
        self.value
        self.report - value // weight 
  #Fonction for comparison between two ObjectsSac
  #On compares the ratio calculated to sort them
    def __lt__ (self, other): 
        return self.report< other.rapport 
  

def getValeurMax (weights, values, ability): 
        TableTrie[] 
        for i in range: 
            tableTrie.append (ObjectSac (weigh[i]ts, value[i]s, i)) 
  
        #Trier the elements of the bag by their report
        tableTrie.sort (reverse - True) 
  
        MeterValeur - 0
        for object in tableauTrie: 
            WeightCourant - int (object.weight) 
            ValueCourante - int (object.value) 
            if capacity - weightsCourant '0: 
                #on adds the object to the bag
                #On subtracts capacity
                capacity - weightsCourant 
                MeterValeur - ValueCourante
                #On adds value to the bag 
        return counterValeur 


Weights[1,5,3,2,4] 
Values[10,50,20,30,60] 
capacity - 11
Maximum value - getValeurMax (weight, values, capacity) 
print ("Maximum value in the backpack," ValueMax) 

The result is as follows:

py sacados.py 
Maximum value in backpack - 120

Implementation of the problem in fractional version

In a fractional version of the backpack problem you can add fractions of object to the backpack.

itemsac class: 
    def __init__ (self, weight, value, index): 
        self.index - index         
        self.weight - weight 
        self.value
        self.report - value // weight 
  #Fonction for comparison between two ObjectsSac
  #On compares the ratio calculated to sort them
    def __lt__ (self, other): 
        return self.report< other.rapport 
  

def getValeurMax (weights, values, ability): 
        TableTrie[] 
        for i in range: 
            tableTrie.append (ObjectSac (weigh[i]ts, value[i]s, i)) 
  
        #Trier the elements of the bag by their report
        tableTrie.sort (reverse - True) 
  
        MeterValeur - 0
        for object in tableauTrie: 
            WeightCourant - int (object.weight) 
            ValueCourante - int (object.value) 
            if capacity - weightsCourant '0: 
                #on adds the object to the bag
                #On subtracts capacity
                capacity - weightsCourant 
                MeterValeur - ValueCourante
                #On adds value to the bag 
            else 
                fraction - capacity / weightCouring 
                MeterValeur -Courante value - fraction 
                capacity - int (capacity - (weightsCourant - fraction)) 
                Break
        return counterValeur 


Weights[1,5,3,2,4] 
Values[10,50,20,30,60] 
capacity - 11
Maximum value - getValeurMax (weight, values, capacity) 
print ("Maximum value in the backpack," ValueMax) 

The result is as follows:

py sacados.py 
Maximum value in backpack - 140.0

Ethereum solidity tutorial – Build a step-by-step Blockchain Dapp

ethereum solidity tutorial :This article details a complete example of smart contract solidity creation for ethereum. This article is the continuation of the first 2 which also details the creation of the contract.

The first 2 articles provide a better understanding of the concept of blockchain and decentralized application.

Creating the project

A directory is created for the voting application project on songs.

mkdir vote-song-dapp

To accelerate development we will use a “truffle box”: https://www.trufflesuite.com/boxes

It’s sort of a template, an application canvas that allows you to focus on the Dapp by having a structure already created.

I will base my explanation on the pet-shop box available here: https://www.trufflesuite.com/tutorials/pet-shop. This is one of the first truffle tutorials to create a Dapp.

This truffle box includes the basic structure of the project as well as the user interface code.

Use the truffle unbox command:

truffle unbox pet-shop

As a reminder the installation of truffle is possible via the order:

npm install -g truffle

If you open the vote-chason-dapp folder with vscode then you get the following tree:

ethereum solidity tutorial
Dapp app project tree example (based on truffle pet-shop)
  • contract: storage of the application’s smart contract
  • migration: Migrations allow smart contracts to be transferred to the Ethereum blockchain (local test or mainnet). Migrations also allow you to link smart contracts with other smart contracts and start them.
  • node_modules: The node_modules folder contains libraries downloaded from npm.
  • src: Front-end application directory (customer)
  • test: Storage of tests for the application
  • truffle-config.js: Javascript file that can execute any code needed to create your configuration.

Creating the smart contract

As a reminder we are developing an application that allows to elect the favorite song of voters.

We will first create the part that allows to create a vote for the best song based on 3 eligible songs.

The contract written in solidity is as follows:

TopChanson contract
        struct Song
        uint ID;
        title string;
        uint counter;
    }
    uint public counterDeChansons;
    mapping (uint - Song) public songs;

    function addChansonElligible (string memory nomChanson) private
        CounterDeChansons;
        songs -[compteurDeChansons] Song (CounterDeChansons, NameChanson, 0);
    }

    TopChansons(public) function
        addChansonElligible ("Moonlight");
        addChansonElligible ("Mom the little boats");
        addChansonElligible ("Ah! Crocodiles");
    }

}

Note the use of “mapping (uint – Song) public songs;”

Related: https://solidity.readthedocs.io/en/v0.6.6/types.html#mapping-types

This data structure will allow us to store the titles of eligible songs like a hash table. That is, a table that takes as an access key in our case a uint that is the song ID and allows to recover the value that is a structured song type.

The Song type is structured, see solidity documentation: https://solidity.readthedocs.io/en/v0.6.6/types.html#structs

Here there is a special case on the feature addChansonElligible, it takes into argument the name of the song which is a string character chain. If you don’t add the keyword “memory” you get the following error:

TypeError: Data location must be “storage” or “memory” for parameter in function, but none was given.

For function settings and return variables, the location of the data must be explained for all type variables (struct, mapping, thong).

The contract is migrated via the order:

truffle migrate --reset

We then get:

Compiling your contracts...
===========================
Compiling ./contracts/Migrations.sol
Compiling ./contracts/TopChanson.sol

To follow …

Ethereum solidity tutorial – Liens internes :

http://128mots.com/index.php/2020/03/30/construire-une-application-decentralisee-full-stack-pas-a-pas-ethereum-blockchain-dapp-en-plus-de-128-mots-partie-1/

http://128mots.com/index.php/2020/04/02/construire-une-application-decentralisee-full-stack-pas-a-pas-ethereum-blockchain-dapp-en-plus-de-128-mots-partie-2/

http://128mots.com/index.php/category/python/

Build a step-by-step, decentralized application (Ethereum Blockchain Dapp) in more than 128 words – Part 1

This article aims to explain the key concepts of blockchain, dapp (decentralized app), smart contract and tokenization.

Blockchain

A blockchain is a decentralized database, it is shared between several nodes that has a copy of that database.

Block

A request for a user to add data to the database is a transaction. Transactions are grouped and added to a block in the blockchain.

Note that all data in this shared register, the blockchain, is secured by cryptographic hash and validated by an algorithm that is a consensus among network users.

Block concept in a blockchain

Minor

Minors are network users who use a program to validate new transactions and record them on the blockchain.

Example of a miner's farm equipped to calculate transactions on the blockchain (via complex mathematical and cryptographic problem solving), miners receive a "reward" for their work.

Blockchain Ethereum

Ethereum is an open source platform that uses blockchain technology to run decentralized applications (dapps).

This platform is based on the creation of Smart Contract, it is a program that contains data and functions called by applications.

Based on the blockchain there is no centralized database but a register shared and maintained in peer to peer by users.

This technology can be used to exchange currencies or to create decentralized applications that call smart contracts and store their data in blocks of the blockchain.

Public Blockchain

In a public blockchain there is no permission, everyone can join the blockchain network, which means they can read, write or participate with a public blockchain.

Public Blockchains are decentralized, no one has control over the network and they remain secure because the data cannot be changed once validated on the block chain.

Public blockchain platforms such as Bitcoin, Ethereum, Litecoin are un authorized blockchain platforms, striving to increase and protect the anonymity of the user.

Private Blockchain

In a private blockchain there are restrictions to filter who is allowed to participate in the network and what transactions.

Private blockchains tend to be associated with identity management tools or a modular architecture on which you can plug in your own identity management solution.

This may be an OAuth solution service provider that uses Facebook, LinkedIn, for example,…

Token Ethereum

Ethereum tokens or tokens are digital assets that are built from the Ethereum blockchain. These are tokens that attest that you have a value (economic for example). These tokens are based on Ethereum's existing infrastructure.

To store, receive, send ether (cryptocurrency on the blockchain ethereum) or tokens (which are tokens that are digital assets), you need at least one account. The easiest way to create an account is:

It is possible to create its own token to create its decentralized application that uses the public blockchain ethereum.

Tokenisation of financial assets

Tokenization is a method that converts the rights of an asset (financial, real estate …) into digital tokens (tokens).

Example for a 400,000 Euro apartment. Tokenizing it consists of turning it into 400,000 tokens (the number is arbitrary, the Issue can be 4 million or 100 chips).

Tokens are issued on a kind of platform that supports intelligent contracts, for example on Ethereum. The goal is for tokens to be freely exchanged.

When you buy a token, you actually buy a share of the ownership of the asset (from the apartment of 400,000 euros).

Buy 200,000 chips and you own half the assets. The Blockchain is shared register that is immutable, it ensures that once you buy tokens, no one can delete your property.

Decentralized application

Decentralized applications are applications that communicate with the blockchain. The decentralized application interface is similar to any website or mobile application.

The Smart Contract represents the central logic of decentralized application.

Illustration of a DApp that uses a blockchain with smart contracts combined with the looters of Swarm and Whisper.
Source: Ethereum Stack exchange

Smart Contract

Smart Contracts contain all the business logic of a DApp. They are responsible for reading and writing data in the blockchain, so they execute business logic.

Intelligent contacts are written in a programming language called SOLIDITY https://solidity.readthedocs.io, similar to Javascript.

To read on the subject:

ANGULAR in less than 128 words – TypeScript – Part 5

This article follows the first four on the subject ANGULAR and deals with the language TypeScript:

Use of classes

As in other languages a class allows to create objects and gathers variables and functions that are strongly related "Highly Related"

Class example

Class Person
  name: string;
  first name: string;

  To be more
    console.log ('My name is'- this.name' - this.prenom);
  }
}

Modules:

Class storage can be done in separate files, in this case it is a module statement.

The modules make the class accessible outside the file. The class must first be exported via "export" to be visible example of person.ts:

export class Person
  name: string;
  first name: string;

  To be more
    console.log ('My name is'- this.name' - this.prenom);
  }
}

example of hand.ts file that imports the Person class:

import - Person - from "./person";

let person - new person();

Note that there are Angular modules that will be imported with the mention @angular example:

import - Component - from '@angular/core';

Read:

https://www.typescriptlang.org/docs/handbook/modules.html

https://www.angularchef.com/recette/50/

ANGULAR in more than 128 words – Part 1

Angular is a framework for building client applications, based on HTML/CSS and JavaScript/TypeScript.

Angular offers the following benefits:

  • Revealing Pattern Module: organizes the code into one or more modules and gives a better structure.
  • Clean and structured architecture.
  • Reusable code.
  • Application more easily testable.

Architecture:

  • Front-End: Takes care of the presentation logic. Made up of HTML / CSS / TypeScript / Angular
  • Backend: Takes care of business logic. Made up of Data – API

Create a first Angular app:

NodeJS: The Node.js execution environment includes everything you need to run a program written in JavaScript. To install the link https://node.js.org

Node Package Manager: This is an online control utility that facilitates the installation of packages, version management and dependency management.

Angular-Cli: a command line interface to automate your development workflow. It allows you to:

  • Create a new Angular app.
  • Run a development server with "Live Reload" support to preview your app during development.
  • Add features to your Angular app.
  • Run unit tests
  • Run end-to-end tests
  • Build the app for deployment in production
  • Deploy your app to a server

Installing Angular-cli online ordering:

npm install -g @angular-cli

This notation with 'NPM' allows nPM packages to be spaced out of names. Each user and organization on NPM has its own reach and they are the only ones who can add packages.

This is useful for several reasons:

  • Allows organizations to clearly state which packages are "official" and which are not. For example, the scope @angular, ensures that it was published by the Angular core team.
  • The name of the package should be unique to within its scope of publication but not to the entire npm registry.
    For example, the name of the http package is already taken in the main repository npm, but Angular may also have angular/http.

For more details the documentation can be found at this link: https://docs.npmjs.com/

Create an Angular package:

ng new package-test-angular

Edit the code of the Angular project created:

I advise you to edit the code with the vsCode editor: https://code.visualstudio.com/ or with the code editor Sublime Text https://www.sublimetext.com/

If you use vscode the following command can be used at the root of your project.

Code.

Deploy your angular project on the local machine server:

ng serve

The app is then searchable on localhost:4200.