WebAssembly – “Hello World” ”; Previous Next In this chapter we are going to write a simple program in C and convert it into .wasm and execute the same in the browser to get the text “Hello World”. Will make use of wasm explorer tool that will convert the C program to .wasm and will make use of the .wasm inside our .html file. The Wasm explorer tool which is available at https://mbebenita.github.io/WasmExplorer/ looks as follows − The C code that we are going to use is as follows − #include <stdio.h> char *c_hello() { return “Hello World”; } Update the first block in wasm explorer with the C code as shown below − Click on COMPILE Button to compile to WASM and WAT and Firefox x86 Web Assembly as shown below − Use the DOWNLOAD to get the .wasm file and save it as firstprog.wasm. Create a .html file called firstprog.html as shown below − <!doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Hello World</title> </head> <body> <div id=”textcontent”></div> <script type=”text/javascript”> //Your code from webassembly here </script> </body> </html> Let us now use firstprog.wasm to read the helloworld from the C function c_hello(). Step 1 Use fetch() api to read the firstprog.wasm code. Step 2 The .wasm code has to be converted into arraybuffer by using ArrayBuffer. The ArrayBuffer object will return you a fixed length binary data buffer. The code so far will be as follows − <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) </script> Step 3 The bytes from ArrayBuffer have to be compiled into a module by using WebAssembly.compile(buffer) function. The code will look like below − <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) </script> Step 4 To get the module we have to call the webassembly.instance constructor as shown below − <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) </script> Step 5 Let us now console the instance to see the details in the browser. <script type=”text/javascript”> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { console.log(instance); }); </script> The console.log details are shown below − To get the string “Hello World” from the function c_hello(), we need to add some code in javascript. First, get the memory buffer details as shown below − let buffer = instance.exports.memory.buffer;; The buffer value has to be converted to a typed array so that we can read the values from it. The buffer has the string Hello World in it. To convert to typed call the constructor Uint8Array as shown below − let buffer = new Uint8Array(instance.exports.memory.buffer); Now, we can read the value from the buffer in a for – loop. Let us now get the start point to read the buffer, by calling the function we wrote as shown below − let test = instance.exports.c_hello(); Now, the test variable has the start point to read our string. WebAssembly does not have anything for string values, everything is stored as integers. So when, we read the value from the buffer, they will be an integer value and we need to convert it into a string using fromCharCode() in javascript. The code is as follows − let mytext = “”; for (let i=test; buffer[i]; i++){ mytext += String.fromCharCode(buffer[i]); } Now, when you console mytext you should see the string “Hello World”. Example The complete code is as follows − <!doctype html> <html> <head> <meta charset=”utf-8″> <title>WebAssembly Add Function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id=”textcontent”></div> <script> fetch(“firstprog.wasm”) .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module)}) .then(instance => { console.log(instance); let buffer = new Uint8Array(instance.exports.memory.buffer); let test = instance.exports.c_hello(); let mytext = “”; for (let i=test; buffer[i]; i++) { mytext += String.fromCharCode(buffer[i]); } console.log(mytext); document.getElementById(“textcontent”).innerHTML = mytext; }); </script> </body> </html> We have added a div and the content is added to the div, so the string is displayed on the browser. Output The output is mentioned below − Print Page Previous Next Advertisements ”;
Category: Computer Programming
Tk – Selection Widgets
Tk – Selection Widgets ”; Previous Next Selection widgets are used to select different options in a Tk application. The list of available selection widgets are as shown below. Sr.No. Widgets & Description 1 Radiobutton Widget that has a set of on/off buttons and labels, one of which may be selected. 2 Checkbutton Widget that has a set of on/off buttons and labels, many of which may be selected. 3 Menu Widget that acts as holder for menu items. 4 Listbox Widget that displays a list of cells, one or more of which may be selected. A simple Tk example is shown below using selection widgets − #!/usr/bin/wish grid [frame .gender ] grid [label .label1 -text “Male” -textvariable myLabel1 ] grid [radiobutton .gender.maleBtn -text “Male” -variable gender -value “Male” -command “set myLabel1 Male”] -row 1 -column 2 grid [radiobutton .gender.femaleBtn -text “Female” -variable gender -value “Female” -command “set myLabel1 Female”] -row 1 -column 3 .gender.maleBtn select grid [label .myLabel2 -text “Range 1 not selected” -textvariable myLabelValue2 ] grid [checkbutton .chk1 -text “Range 1″ -variable occupied1 -command {if {$occupied1 } { set myLabelValue2 {Range 1 selected} } else { set myLabelValue2 {Range 1 not selected} } }] proc setLabel {text} { .label configure -text $text } When we run the above program, we will get the following output − Print Page Previous Next Advertisements ”;
Tk – Windows Manager
Tk – Windows Manager ”; Previous Next Window manager is used to handle the top level window. It helps in controlling the size, position, and other attributes of the window. In Tk, . is used to refer the main window. The syntax for window command is shown below − wm option window arguments The list of options available for Tk wm command is shown in the following table − Sr.No. Syntax & Description 1 aspect windowName a b c d Tries to maintain the ratio of width/height to be between a/b and c/d. 2 geometry windowName geometryParams Use to set geometry for window. 3 grid windowName w h dx dy Sets the grid size. 4 group windowName leaderName leaderName gives the leader of a group of related windows. 5 deiconify windowName Brings the screen to normal if minimized. 6 iconify windowName Minimizes the window. 7 state windowName Returns the current state of window. 8 withdraw windowName Unmaps the window and removes its details in memory. 9 iconbitmap windowName image Sets or returns the icon bitmap. 10 iconPhoto windowName image Sets or returns the icon photo. 11 command windowName commandString Records the startup command in the WM_COMMAND property. 12 protocol windowName arguments Register a command to handle the protocol request name, which can be WM_DELETE_WINDOW, WM_SAVE_YOURSELF, WM_TAKE_FOCUS. Eg: wm protocol. WM_DELETE_WINDOW Quit. 13 minsize windowName size Determines the minimum window size. 14 maxsize windowName size Determines the maximum window size. 15 title windowName titleText Determines the title for window. 16 attributes subOptions There are lots of attributes available like alpha, full screen and so on. Some of the above commands are used in the following example − #!/usr/bin/wish wm maxsize . 800 800 wm minsize . 300 300 wm title . “Hello” wm attributes . -alpha “.90″ wm geometry . 300×200+100+100 When we run the above program, we will get the following output − As you can see alpha is one of the attributes available. The list of commonly used subcommands are listed below − Sr.No. Syntax & Description 1 -alpha number Sets the alpha for window. 2 -fullscreen number Number can be 0 for normal screen or 1 for full screen. 3 -topmost number Sets or returns whether window is topmost.Value can be 0 or 1. Creating Window We can use toplevel command to create window and an example is shown below − #!/usr/bin/wish toplevel .t When we run the above program, we will get the following output − Destroying Window We can use destroy command to destroy window and an example is shown below − #!/usr/bin/wish destroy .t The above command will destroy window named .t. Print Page Previous Next Advertisements ”;
Tk – Basic Widgets
Tk – Basic Widgets ”; Previous Next Basic widgets are common widgets available in almost all Tk applications. The list of available basic widgets is given below − Sr.No. Widgets & Description 1 Label Widget for displaying single line of text. 2 Button Widget that is clickable and triggers an action. 3 Entry Widget used to accept a single line of text as input. 4 Message Widget for displaying multiple lines of text. 5 Text Widget for displaying and optionally edit multiple lines of text. 6 Toplevel Widget used to create a frame that is a new top level window. A simple Tk example is shown below using basic widgets − #!/usr/bin/wish grid [label .myLabel -text “Label Widget” -textvariable labelText] grid [text .myText -width 20 -height 5] .myText insert 1.0 “TextnWidgetn” grid [entry .myEntry -text “Entry Widget”] grid [message .myMessage -background red -foreground white -text “MessagenWidget”] grid [button .myButton1 -text “Button” -command “set labelText clicked”] When we run the above program, we will get the following output − Print Page Previous Next Advertisements ”;
Swift – Tuples
Swift – Tuples ”; Previous Next Tuples are used to store a group of values in a single value, for example (32, “Swift Programming”) is a tuple with two values that are 23 and “Swift Programming”. Tuples can store multiple values and each value is separated by a comma. It can store values of the same or different data types. They are helpful when we want to return multiple values together. Tuples are commonly used by the functions to return multiple values at the same time. Tuples are not used for complex data structures; they are useful for simple groups of related data. Syntax Following is the syntax of the Tuple − var myValue = (value1, value2, value3, value4, …, valueN) We can access the elements of the tuple with the help of dot notation followed by the element’s index − var result = tupleName.indexValue Example Swift program to create and access the elements of the tuple. import Foundation // Creating a tuple var myTuple = (“Romin”, 321, “Delhi”) // Accessing the elements of Tuple var name = myTuple.0 var id = myTuple.1 var city = myTuple.2 // Displaying the result print(“Employee name =”, name) print(“Employee id =”, id) print(“Employee city =”, city) Output Employee name = Romin Employee id = 321 Employee city = Delhi Tuple with different Data types In a tuple, we are allowed to store data of different types like (Int, Int, Float), (Float, Double, String), etc. You can also store data of the same data type like (Int, Int, Int), etc. Example Swift program to create a tuple of different data types. import Foundation // Creating a tuple with data of different data types var myTuple = (“Mona”, 21, “Mumbai”, 101) // Accessing the elements of Tuple var name = myTuple.0 var age = myTuple.1 var city = myTuple.2 var id = myTuple.3 // Displaying the result print(“Student name =”, name) print(“Student age =”, age) print(“Student city =”, city) print(“Student id =”, id) Output Student name = Mona Student age = 21 Student city = Mumbai Student id = 101 Assigning Tuple to Separate Variables We can assign the value of a tuple to a separate constant or variable so that we can access them using the name of that constant or the variable. Here the count of the constant or variable should be equal to the tuple’s values. Syntax Following is the syntax of assigning tuple values to a separate constant or variable − let (name1, name2) = tuple Example Swift program to create a tuple whose values are assigned to a set of constants. import Foundation // Creating a tuple var myTuple = (“Mickey”, 21, “Pune”) // Assigning tuple to a set of constants let(name, age, city) = myTuple // Accessing the value of tuples according to the constant print(“Student name =”, name) print(“Student age =”, age) print(“Student city =”, city) Output Student name = Mickey Student age = 21 Student city = Pune Tuple with Underscore in Swift We are allowed to use an underscore “_” with a tuple. It will ignore the part of the tuple with an underscore while decomposing the tuple. Or in other words, we can say that by using underscore we can ignore some tuple’s values. We are allowed to use multiple underscores with the same tuple to ignore multiple values. Syntax Following is the syntax of a tuple with an underscore − let (name1, name2, _) = tuple Example Swift program to create a tuple with underscore “_”. import Foundation // Creating a tuple var myTuple = (21, “Pune”, “CSE”) // Assigning a tuple to a set of constants let(age, _, branch) = myTuple // Accessing the values of tuples print(“Student age =”, age) print(“branch =”, branch) Output Student age = 21 branch = CSE Assigning Names to Individual Values in a Tuple In Swift, we are allowed to assign names to the individual elements of the tuple. We can also access the tuple’s elements according to their names. Syntax Following is the syntax for assigning names to a tuple’s elements − let myTuple = (id: 102, name: “Sona”) Example Swift program to create and access tuple elements according to their names. import Foundation // Creating a tuple var myTuple = (name: “Mona”, branch: “ECE”, year: 2022) // Accessing the values of tuples according to their names print(“Student name =”, myTuple.name) print(“Branch =”, myTuple.branch) print(“Current Year”, myTuple.year) Output Student name = Mona Branch = ECE Current Year 2022 Print Page Previous Next Advertisements ”;
Solidity – Style Guide
Solidity – Style Guide ”; Previous Next Style Guide helps to maintain code layout consistent and make code more readable. Following are the best practices following while writing contracts with Solidity. Code Layout Indentation − Use 4 spaces instead of tab to maintain indentation level. Avoid mixing spaces with tabs. Two Blank Lines Rule − Use 2 Blank lines between two contract definitions. pragma solidity ^0.5.0; contract LedgerBalance { //… } contract Updater { //… } One Blank Line Rule − Use 1 Blank line between two functions. In case of only declaration, no need to have blank lines. pragma solidity ^0.5.0; contract A { function balance() public pure; function account() public pure; } contract B is A { function balance() public pure { // … } function account() public pure { // … } } Maximum Line Length − A single line should not cross 79 characters so that readers can easily parse the code. Wrapping rules − First argument be in new line without opening parenthesis. Use single indent per argument. Terminating element ); should be the last one. function_with_a_long_name( longArgument1, longArgument2, longArgument3 ); variable = function_with_a_long_name( longArgument1, longArgument2, longArgument3 ); event multipleArguments( address sender, address recipient, uint256 publicKey, uint256 amount, bytes32[] options ); MultipleArguments( sender, recipient, publicKey, amount, options ); Source Code Encoding − UTF-8 or ASCII encoding is to be used preferably. Imports − Import statements should be placed at the top of the file just after pragma declaration. Order of Functions − Functions should be grouped as per their visibility. pragma solidity ^0.5.0; contract A { constructor() public { // … } function() external { // … } // External functions // … // External view functions // … // External pure functions // … // Public functions // … // Internal functions // … // Private functions // … } Avoid extra whitespaces − Avoid whitespaces immediately inside parenthesis, brackets or braces. Control structures − Braces should open on same line as declaration. Close on their own line maintaining the same indentation. Use a space with opening brace. pragma solidity ^0.5.0; contract Coin { struct Bank { address owner; uint balance; } } if (x < 3) { x += 1; } else if (x > 7) { x -= 1; } else { x = 5; } if (x < 3) x += 1; else x -= 1; Function Declaration − Use the above rule for braces. Always add a visibility label. Visibility label should come first before any custom modifier. function kill() public onlyowner { selfdestruct(owner); } Mappings − Avoid whitespaces while declaring mapping variables. mapping(uint => uint) map; mapping(address => bool) registeredAddresses; mapping(uint => mapping(bool => Data[])) public data; mapping(uint => mapping(uint => s)) data; Variable declaration − Avoid whitespaces while declaring array variables. uint[] x; // not unit [] x; String declaration − Use double quotes to declare a string instead of single quote. str = “foo”; str = “Hamlet says, ”To be or not to be…””; Order of Layout Elements should be layout in following order. Pragma statements Import statements Interfaces Libraries Contracts Within Interfaces, libraries or contracts the order should be as − Type declarations State variables Events Functions Naming conventions Contract and Library should be named using CapWords Style. For example, SmartContract, Owner etc. Contract and Library name should match their file names. In case of multiple contracts/libraries in a file, use name of core contract/library. Owned.sol pragma solidity ^0.5.0; // Owned.sol contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { //…. } function transferOwnership(address newOwner) public onlyOwner { //… } } Congress.sol pragma solidity ^0.5.0; // Congress.sol import “./Owned.sol”; contract Congress is Owned, TokenRecipient { //… } Struct Names − Use CapWords Style like SmartCoin. Event Names − Use CapWords Style like Deposit, AfterTransfer. Function Names − Use mixedCase Style like initiateSupply. Local and State variables − Use mixedCase Style like creatorAddress, supply. Constants − Use all capital letters with underscore to seperate words like MAX_BLOCKS. Modifier Names − Use mixCase Style like onlyAfter. Enum Names − Use CapWords Style like TokenGroup. Print Page Previous Next Advertisements ”;
Solidity – Comments
Solidity – Comments ”; Previous Next Solidity supports both C-style and C++-style comments, Thus − Any text between a // and the end of a line is treated as a comment and is ignored by Solidity Compiler. Any text between the characters /* and */ is treated as a comment. This may span multiple lines. Example The following example shows how to use comments in Solidity. function getResult() public view returns(uint){ // This is a comment. It is similar to comments in C++ /* * This is a multi-line comment in solidity * It is very similar to comments in C Programming */ uint a = 1; uint b = 2; uint result = a + b; return result; } Print Page Previous Next Advertisements ”;
Solidity – Strings
Solidity – Strings ”; Previous Next Solidity supports String literal using both double quote (“) and single quote (”). It provides string as a data type to declare a variable of type String. pragma solidity ^0.5.0; contract SolidityTest { string data = “test”; } In above example, “test” is a string literal and data is a string variable. More preferred way is to use byte types instead of String as string operation requires more gas as compared to byte operation. Solidity provides inbuilt conversion between bytes to string and vice versa. In Solidity we can assign String literal to a byte32 type variable easily. Solidity considers it as a byte32 literal. pragma solidity ^0.5.0; contract SolidityTest { bytes32 data = “test”; } Escape Characters Sr.No. Character & Description 1 n Starts a new line. 2 \ Backslash 3 ” Single Quote 4 “ Double Quote 5 b Backspace 6 f Form Feed 7 r Carriage Return 8 t Tab 9 v Vertical Tab 10 xNN Represents Hex value and inserts appropriate bytes. 11 uNNNN Represents Unicode value and inserts UTF-8 sequence. Bytes to String Conversion Bytes can be converted to String using string() constructor. bytes memory bstr = new bytes(10); string message = string(bstr); Example Try the following code to understand how the string works in Solidity. pragma solidity ^0.5.0; contract SolidityTest { constructor() public{ } function getResult() public view returns(string memory){ uint a = 1; uint b = 2; uint result = a + b; return integerToString(result); } function integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return “0”; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len – 1; while (_i != 0) { bstr[k–] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } Run the above program using steps provided in Solidity First Application chapter. Output 0: string: 3 Print Page Previous Next Advertisements ”;
Solidity – Environment Setup
Solidity – Environment Setup ”; Previous Next This chapter explains how we can setup Solidity compiler on CentOS machine. If you do not have a Linux machine then you can use our Online Compiler for small contracts and for quickly learning Solidity. Method 1 – npm / Node.js This is the fastest way to install Solidity compiler on your CentoS Machine. We have following steps to install Solidity Compiler − Install Node.js First make sure you have node.js available on your CentOS machine. If it is not available then install it using the following commands − # First install epel-release $sudo yum install epel-release # Now install nodejs $sudo yum install nodejs # Next install npm (Nodejs Package Manager ) $sudo yum install npm # Finally verify installation $npm –version If everything has been installed then you will see an output something like this − 3.10.10 Install solc Once you have Node.js package manager installed then you can proceed to install Solidity compiler as below − $sudonpm install -g solc The above command will install solcjs program and will make it available globally through out the system. Now you can test your Solidity compiler by issuing following command − $solcjs-version If everything goes fine, then this will print something as follows − 0.5.2+commit.1df8f40c.Emscripten.clang Now you are ready to use solcjs which has fewer features than the standard Solidity compiler but it will give you a good starting point. Method 2 – Docker Image You can pull a Docker image and start using it to start with Solidity programming. Following are the simple steps. Following is the command to pull a Solidity Docker Image. $docker pull ethereum/solc:stable Once a docker image is downloaded we can verify it using the following command. $docker run ethereum/solc:stable-version This will print something as follows − $ docker run ethereum/solc:stable -version solc, the solidity compiler commandlineinterfaceVersion: 0.5.2+commit.1df8f40c.Linux.g++ Method 3: Binary Packages Installation If you are willing to install full fledged compiler on your Linux machine, then please check official website Installing the Solidity Compiler. Print Page Previous Next Advertisements ”;
Socket.IO – Chat Application
Socket.IO – Chat Application ”; Previous Next Now that we are well acquainted with Socket.IO, let us write a chat application, which we can use to chat on different chat rooms. We will allow users to choose a username and allow them to chat using them. So first, let us set up our HTML file to request for a username − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); </script> <body> <input type=”text” name=”name” value=”” placeholder=”Enter your name!”> <button type=”button” name=”button”>Let me chat!</button> </body> </html> Now that we have set up our HTML to request for a username, let us create the server to accept connections from the client. We will allow people to send their chosen usernames using the setUsername event. If a user exists, we will respond by a userExists event, else using a userSet event. var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”);}); users = []; io.on(”connection”, function(socket){ console.log(”A user connected”); socket.on(”setUsername”, function(data){ if(users.indexOf(data) > -1){ users.push(data); socket.emit(”userSet”, {username: data}); } else { socket.emit(”userExists”, data + ” username is taken! Try some other username.”); } }) }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); We need to send the username to the server when people click on the button. If user exists, we show an error message; else, we show a messaging screen − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); function setUsername(){ socket.emit(”setUsername”, document.getElementById(”name”).value); }; var user; socket.on(”userExists”, function(data){ document.getElementById(”error-container”).innerHTML = data; }); socket.on(”userSet”, function(data){ user = data.username; document.body.innerHTML = ”<input type=”text” id=”message”> <button type=”button” name=”button” onclick=”sendMessage()”>Send</button> <div id=”message-container”></div>”; }); function sendMessage(){ var msg = document.getElementById(”message”).value; if(msg){ socket.emit(”msg”, {message: msg, user: user}); } } socket.on(”newmsg”, function(data){ if(user){ document.getElementById(”message-container”).innerHTML +=”<div><b>” + data.user + ”</b>: ” + data.message + ”</div>” } }) </script> <body> <div id=”error-container”></div> <input id=”name” type=”text” name=”name” value=”” placeholder=”Enter your name!”> <button type=”button” name=”button” onclick=”setUsername()”>Let me chat!</button> </body> </html> Now if you connect two clients with same username, it will give you an error as shown in the screenshot below − Once you have provided an acceptable username, you will be taken to a screen with a message box and a button to send messages. Now, we have to handle and direct the messages to the connected client. For that, modify your app.js file to include the following changes − var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”);}); users = []; io.on(”connection”, function(socket){ console.log(”A user connected”); socket.on(”setUsername”, function(data){ console.log(data); if(users.indexOf(data) > -1){ socket.emit(”userExists”, data + ” username is taken! Try some other username.”); } else { users.push(data); socket.emit(”userSet”, {username: data}); } }); socket.on(”msg”, function(data){ //Send message to everyone io.sockets.emit(”newmsg”, data); }) }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); Now connect any number of clients to your server, provide them a username and start chatting! In the following example, we have connected two clients with names Ayush and Harshit and sent some messages from both the clients − Print Page Previous Next Advertisements ”;