<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ayan Bag on Medium]]></title>
        <description><![CDATA[Stories by Ayan Bag on Medium]]></description>
        <link>https://medium.com/@ayanbag?source=rss-4002ba503c32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UVkmojmezbrvMYF_XJLDww.jpeg</url>
            <title>Stories by Ayan Bag on Medium</title>
            <link>https://medium.com/@ayanbag?source=rss-4002ba503c32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:25:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayanbag/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to Multi-threading in Python]]></title>
            <link>https://medium.com/@ayanbag/introduction-to-multi-threading-in-python-955e8608381a?source=rss-4002ba503c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/955e8608381a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Ayan Bag]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 08:07:39 GMT</pubDate>
            <atom:updated>2019-04-30T08:10:59.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrF4PKXYpNpcQJAWPX1wGw.png" /><figcaption>Pepper Python (Source: Heroku Art)</figcaption></figure><h3>Introduction</h3><p>Like multiprocessing,<strong> multithreading </strong>is a way of achieving multitasking. Most of the code we write in Python is single threaded. A python virtual machine runs behind the scene uses a thread called the <strong>main thread</strong> i.e <strong>main() </strong>to execute the code which has written.</p><p>A <strong>thread</strong> is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a <strong>thread</strong> is a sequence of such instructions within a program that can be executed independently of other codes.</p><p><strong>Multithreading</strong> is defined as the ability of a processor to execute multiple threads concurrently.</p><h4>Why use Multithreading?</h4><p>To make the best use of the underlying processor and to improve the performance of our application, we can create multiple threads that can execute in parallel making the best use of processor and also our application will give the best user experience, it will be very fast.</p><h4>Way to create Multithreading :</h4><p>To create multiple threads in our application, we have three ways :</p><ul><li>To use a function: We will define a function just like we define our function. Now we will create an object of type thread.</li></ul><pre>t=Thread(target=functionName,args)</pre><p>To the object, we will pass the target which is the function we have created, the name of the function and the second argument here is the argument to the function. After we invoke t.start() i.e.</p><pre>t=Thread(target=functionName,args)<br>t.start()</pre><p>When we do that the Python Virtual Machine will create a new thread that will run in parallel with the <strong>main </strong>thread and as a part of the thread the code within this function will be executed and the arguments are passed to the function.</p><ul><li>By extending the thread class:</li></ul><p>We will import the Threading Module and extend the thread class. And the second step is to override the run method.</p><ul><li>Without extending the thread class:(<strong>Hybrid Approach</strong>)</li></ul><p>In this method, we will create a class and also add function we want within that class and also add function we want within that class, but the class doesn’t extend the Thread Class. Instead, we will create an instance of the thread then we will pass myobj.display , the function which we to execute within the object as the target and the arguments in the second parameters.</p><pre>class MyThread:<br>       display() <strong>#function we want to create<br></strong>t=Thread(target = obj.display,args)<br>t.start()</pre><h3>Main Thread</h3><p>Behind the scenes, when we run our Python programs so far which is being single threaded, there was a <strong>main thread </strong>that was being created by the Python interpreter that represents our program.</p><p>To get the information on the main thread :</p><pre>import threading<br>print(threading.current_thread().getName())</pre><p>Output: Main Thread</p><p>where, <strong>current_thread()</strong> : gives info about current thread, and <strong>getName()</strong> : to get the name of the current thread.</p><p>Also to print the current thread name use the command : current_thread().getName()</p><h3>Thread using a function</h3><p>We are going to create a function that will display the number from 0 to 10 and then we will spawn that function off a thread of its own.</p><pre>from threading import Thread<br>def display_Number():<br>   i=0<br>   while(i&lt;=10):<br>     print(i)<br>     i+=1<br>#<strong>Now to spawn this function as a thread<br></strong>t=Thread(target= display_Number)</pre><pre>#<strong>To start the Thread<br></strong>t.start()</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>.<br>.<br>10</pre><p>Now the thread is no longer the main thread. The output is from a thread of its own.</p><h3>Thread extended the Thread Class</h3><p>We are going to extend a superclass called <em>Thread </em>and override the run method inside.</p><pre>from threading import Thread<br>Class MyThread(Thread):<br>     def run(self):<br>          i=0<br>          while(i&lt;=10):<br>               print(i)<br>               i+=1<br>t=MyThread()<br>t.start() #<strong>It is spawn of a new thread and invoke the run method<br>           that we have overridden</strong></pre><p>Creating a thread using a class :</p><pre>from threading import *<br>class MyThread:<br>      def display_Number(self):<br>            i=1<br>            while(i&lt;=10):<br>                print(i)<br>obj=MyThread() #<strong>Object of our class MyThread<br></strong>t=Thread(target=obj.display_Number)<br>t.start</pre><p>Output:</p><pre>1<br>2<br>.<br>.<br>10</pre><h3>Multi-Threading in Action</h3><p>To create a multithreading application, we have different thread objects.</p><pre>from threading import Thread<br>class MyThread:<br>      def display_Number(self):<br>          i=0<br>          while(n&lt;=10):<br>               print(i)<br>               i+=1</pre><pre>obj=MyThread()</pre><pre>#<strong>Starting Thread 1<br></strong>print(&quot;Thread 1&quot;)<strong><br></strong>t=Thread(target=obj.display_Number)<br>t.start()</pre><pre>#<strong>Starting Thread 2<br></strong>print(&quot;Thread 2&quot;)<br>t2=Thread(target=obj.display_Number)<br>t2.start()</pre><pre>#<strong>Starting Thread 3<br></strong>print(&quot;Thread 3&quot;)<strong><br></strong>t3=Thread(target=obj.display_Number)<br>t3.start()</pre><p>Output:</p><pre>Thread 1<br>0<br>1<br>2<br>3<br>4<br>Thread 2<br>0<br>1<br>2<br>3<br>4<br>5<br>6<br>Thread 3<br>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</pre><p><strong>Note: </strong>The scheduling of these threads is up-to-the thread scheduler.</p><p>Here in the above example, the Thread 1 prints from 0 to 4, then Thread 2 starts off. It depends on the Python thread scheduler. But all of them will do this work at the end. If we re-run the program could be totally different.</p><p>Output:</p><pre>Thread 1<br>1<br>2<br>..<br>10<br>Thread 2<br>1<br>2<br>3<br>..<br>10<br>Thread 3<br>1<br>2<br>3<br>..<br>10</pre><h3>Thread Synchronisation</h3><p>When multiple threads are accessing the same resources it is very important that it doesn’t corrupt each other resources or objects. For example: Booking tickets for films.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*-xTvcw3icjnKczpZCk0HzQ.png" /></figure><p>So that two different users never end up buying the same tickets or the same seats due to <strong>Thread Synchronisation</strong>.</p><p>Thread synchronization is defined as a mechanism that ensures that two or more concurrent threads do not simultaneously execute some particular program segment known as <strong>Critical section</strong>. And Critical section is referred to the parts of the program where the shared resource is accessed<em>.</em></p><p>We can lock an object for a particular thread using two different ways, using <strong><em>Locks</em></strong> or <strong><em>Semaphores</em></strong>.</p><h4>Locks</h4><p>Locks are the most fundamental synchronization mechanism provided by the <strong>threading</strong> module. Locks can be held by a single thread, or by no threads at all. If a thread attempts to hold a lock that’s already held by some other thread, execution of the first thread is halted until the lock is released.</p><p>Generally, Locks are used to synchronize access to shared resources. For each shared resource, we have to create a <strong>Lock</strong> object. When you need to access the resource, call <strong>acquire</strong> to hold the lock, and call <strong>release</strong> to release it:</p><pre>lock = Lock()</pre><pre>lock.acquire() <em># it will block if resources are already held</em><br>... access shared resources<br>lock.release()</pre><p>For proper functioning, we need to use<strong> try-finally </strong>so that<strong> </strong>the lock releases even if something goes wrong when accessing the resource.</p><pre>lock.acquire()<br>try:<br>   ...access shared resources<br>finally:<br>   lock.release() <em># release lock, no matter what</em></pre><h4>Semaphores</h4><p>A semaphore is a more advanced lock mechanism. A semaphore is based on an internal counter which is decremented each time acquire() is called and incremented each time release() is called. If the counter is equal to 0 then acquire() blocks. It is the Python implementation of the Dijkstra semaphore concept: P() and V(). Using a semaphore makes sense when you want to control access to a resource with limited capacity like a server.</p><p>Here is a simple example:</p><pre>semaphore = threading.BoundedSemaphore()<br>semaphore.acquire() <em># decrements the counter</em><br>... access the shared resource<br>semaphore.release() <em># increments the counter</em></pre><h3>Advantages and Disadvantages of Multi-Threading</h3><h4>Advantages</h4><ul><li>It doesn’t block the user. This is because threads are independent of each other.</li><li>Parallelize tasks</li><li>Enhanced performance on multi-processor machines.</li><li>Multi-threaded servers and interactive GUIs use multithreading exclusively</li></ul><h4>Disadvantages</h4><ul><li>Difficult to debug, the result is sometimes unpredictable</li><li>As the number of threads increases, complexity increases</li><li>Potential deadlocks lead to <strong>starvation </strong>i.e some threads may not be served with a bad design</li><li>Constructing and synchronizing threads are CPU/memory intensive.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955e8608381a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Sweet Introduction to R Programming]]></title>
            <link>https://medium.com/@ayanbag/a-sweet-introduction-to-r-programming-96726381eee6?source=rss-4002ba503c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/96726381eee6</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ayan Bag]]></dc:creator>
            <pubDate>Sat, 27 Oct 2018 18:21:04 GMT</pubDate>
            <atom:updated>2018-10-27T18:25:58.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZD3KZIlKNZtgVKw-3JFUwQ.jpeg" /></figure><p>R is a open source and very popular programming language and environment for statistical computer and graphics.R was designed by statisticians and was specialized for statistical computing, and thus is known as the <strong>lingua franca of statistics</strong>. It is mostly used in Data Science and Machine Learning. It is managed by R core development team — team of volunteer developer from across the globe. R provide a wide variety of statistical and graphical techniques and highly extensible.It was developed at Bell Laboratories by John Chambers and colleagues.R is a consolidated environment for performing statistical operation and generating R data analysis reports in graphical or text formats.</p><h4>History of R:</h4><p>R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and currently developed by the <strong>R Development Core Team</strong>. R is an implementation of the S programming Language and combines with lexical scoping semantics inspired by Scheme. John Chambers and colleagues developed S at Bell Laboratories. R was named partly after the first names of two R authors. The initial version of R is released in 1995 and a stable beta version released in 2000.</p><h4><strong>Language Features:</strong></h4><ul><li>R is a well defined and effective programming language which includes functions, loops, user defined function, input and output facilities and many more</li><li>R is both flexible and powerful.</li><li>R has effective data and storage facilities</li><li>R provides graphical facilities for data analysis</li><li>R is easy to learn and free to use as it is open sourced</li><li>R is interpreted language</li><li>R is Object-Oriented Programming Language</li><li>R supports matrix arithmetic.</li><li><strong>R is case sensitive</strong></li><li>R is widely use among mathematician and data miners for data analysis.</li></ul><h4>Alternatives of R:</h4><p>R is not only language in the domain of statistical computing and graphics. Some popular alternatives of R:</p><p><strong>Python</strong></p><p>Python is very powerful high level , object oriented language with very simple syntax.It is also extremely popular between data scientist and researcher. Most packages in R is equivalent to packages in Python.</p><p>The choice between R vs Python also depends on what you are trying to accomplish with your code. If you are trying to analyze a data set and present the findings in a research paper, then R is probably a better choice. But if you are writing a data analysis program that runs in a distributed system and interacts with lots of other components, it would be preferable to work with Python.</p><p><strong>SAS (Statistical Analysis System)</strong></p><p>SAS (Statistical Analysis System) introduced the SAS Business Intelligence &amp; Analytics Solution for large enterprises to explore their large data sets in a visually appealing format. SAS analytics is a data analytics tool that is used increasingly in Data Science, Machine learning, and Business Intelligence applications.It has been the first choice of many private enterprise for their analytics for a long time.</p><p>Although SAS is extremely popular in commercial analysis, R and Python is gaining momentum in the enterprise space and companies are also trying to move towards open-source technologies.</p><p><strong>SPSS — Software package for statistical analysis</strong></p><p>SPSS is a popular statistical tool which is commonly used in the social sciences and is considered as easiest to learn among enterprise statistical software/tools.It is loved by non-statisticians because it is similar to excel. SPSS has the same downside as SAS — it is expensive. SPSS was acquired by IBM in 2009 for a reported $1.2 billion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jkpt7Ywss4vYTaQdWTIjqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OURUMzIYZcffJJySqkmNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5dHmiblEoV-fhNKWa1dTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*Spwo0Svq4QQah4HT5qlbdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*QM7lomuFrx3SSBC-J_ZdQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*JRyxaCTrH0USsEgcKNWGeg.png" /><figcaption>Courtesy: KDnuggets</figcaption></figure><h4>Why should we adopt R Programming Language ?</h4><ul><li>R is open source. Therefore Google is using R Programming as it is suitable language. By using R we can create any form of statistics and data manipulation.</li><li>R programming language is best for statistical, data analysis and machine learning. By using this language we can create objects, functions, and packages. We can use it anywhere. It’s platform- independent, so it can be applied to all operating system. It’s free, so anyone can install it in any organization without purchasing a license.</li><li>R, SAS, and SPSS are three statistical languages. Of these three statistical languages, R is the only an open source.R Programming is extensible and hence, R groups are noted for its energetic contributions. Lots of Rs typical features can be written in R itself and hence, R has gotten faster over time and serves as a glue language.</li><li>As companies gather more and more data, the demand for data scientists are also greatly increasing. Demand for R developers will no doubt be on the rise.</li></ul><h4>Working with R scripts:</h4><p>R provides the freedom of selecting and editing tools to interact with the native console. While scripting in R, you don’t need to type commands but rather call functions to achieve results. The R Console allows command editing.<br>The Prominent editors available for R programming language:</p><ul><li><strong>RGui</strong> (R graphical user Interface)</li><li><strong>RStudio </strong>— It is an integrated development environment (IDE) for R language and offers a very rich environment for editing and creating R scripts than RGui.</li></ul><h4>R Scripting:</h4><p>R holds a reputation for getting things done with very little code.Let us start scripting in R with a very simple program called “Hello World”.</p><pre>#printing Hello World<br>print(&quot;Hello World !!&quot;)</pre><p>And the output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*zywml41VkW2DhIngnYCErw.png" /></figure><p>Let create a more complex script in R to generate 1000 number in a random distribution and arrange them based on their frequency and create a bar chart.</p><pre>n &lt;- floor(rnorm(10000, 500, 100)) <br>t &lt;- table(n) <br>barplot(t)</pre><p>And the output of this script :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*M6I-O1tIT0EAkx7VNStMVg.png" /><figcaption>A Bar Plot</figcaption></figure><p><strong>NOTE</strong>: The extension of R scripts is <strong>.R</strong> .</p><h4>Conclusion:</h4><p>In a nutshell, R is easy to learn and use language. It is widely in practice and students and data scientists. With the data science predicted to grow immensely the importance of R is also undoubted. Hence learning R will the wisest decision you will make for launching your career in the big data space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96726381eee6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a terminal chat application with Real-Time file transferring capabilities]]></title>
            <link>https://medium.com/@ayanbag/creating-a-terminal-chat-application-with-real-time-file-transferring-capabilities-663a763ba420?source=rss-4002ba503c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/663a763ba420</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pusher]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Ayan Bag]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 23:14:27 GMT</pubDate>
            <atom:updated>2018-10-27T21:36:14.476Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a terminal chat application with Real-Time file transferring capabilities in 7 minutes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*DfmKdD8EwFzmpapP3lWj5Q.png" /><figcaption>It is better to have a conversation</figcaption></figure><p>In our daily life we encounter with many chat application which a really awesome. It takes a lot effort to develop and maintain these application because it involves a two way communication between different user and logging each and every request provide by server.</p><p>Getting inspired by the chat application as we see in Die Hard 4, I created my own realtime chat application . And I am here to share how I made this interactive real-time chat application with quite concise Python code.It also feature an in-app file transfer system.So, lets get started.</p><h4>Prerequisites</h4><p>Basic knowledge and understanding of python and its related concepts. Also need Python 3.x and pip installed and configured in your machine.</p><h4>Setting up your app:</h4><p>I build the server with the help of a third party dependency , Pusher. Pusher is a hosted service that make super easy to add real-time data and functionality to web, console and mobile application.</p><p><strong>Step 1:</strong> Create a account in pusher.com. I personally prefer to go with free account , if you use this project as a hobby project. In your free account , you will get <em>a daily message sending limit of 200,000</em> which will be enough for testing and using this chat app.</p><p><strong>Step 2:</strong> After creating a the account, navigate to your dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKNvvH9LHrTofPS1AwTPzw.png" /><figcaption>Your dashboard will look like this.</figcaption></figure><p>After you navigate to your dashboard , click the <strong>Create New App </strong>button.</p><p><strong>Step 3:</strong> Now fill the required information i.e your application name , cluster info ( it is a physical location of server to handle your request ), your tech stack(front-end and back-end) and something about your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*jho000oMW7YJCFQg92vqFw.png" /></figure><p>Then hit the Create My App button.</p><p><strong>Step 4:</strong> After that, a another dashboard will appear. Here navigate to App Key column and take a note of all <em>the app credential </em>(app_id,key,secret,cluster).</p><h4><strong>Creating our chat application</strong></h4><p><strong>Initial Stage:</strong></p><p>Firstly, it is preferred to create a isolated python environment for our app.It can be achieved by installing the package virtualenv. It is used to manage different environments in Python. This is so we do not end up with conflicting libraries which is different from project to projects.To install virtualenv , we have to run :</p><pre>sudo pip install virtualenv</pre><p>for windows, (run in cmd or Powershell as admin)</p><pre>pip install virtualenv</pre><p>Next, we need to create a virtual environment for our app</p><pre>virtualenv terminal_chat</pre><p>Now we are done with setting up the environment,we move to the new directory created and the activate the enviroment.</p><pre>#Changing the directory<br>cd terminal_chat<br>#activating the enviroment<br>source bin/activate</pre><p>for windows user,</p><pre>#changing the directory<br>cd terminal_chat<br>#activating the eniviroment<br>Scripts\activate</pre><p>Now we need to install the following libraries which are required in our project.</p><ul><li>PyInquirer : A collection of common interactive command line user interfaces.</li><li>termcolor : ANSII Color formating for printing color text in output terminal.</li><li>progress : A animation package to create animated progression bar in terminal.</li><li>pusher : The official Python library for interacting with the Pusher HTTP API.</li><li>pysher : Python module for handling pusher WebSockets. This will handle event subscriptions using Pusher</li><li>python-dotenv : Python module that reads the key, value pair from .env file and adds them to the environment variable.</li><li>sql.connector : Allows Python to communicate with MySQL database.</li></ul><p>To install, we need to run</p><pre>pip install termcolor pusher<br>pip install git+https://github.com/nlsdfnbch/Pysher.git <br>pip install python-dotenv PyInquirer progress<br>pip install mysql-connector</pre><p><strong>Creating a entry point for our app:</strong></p><p>Now, we need to create .env file which holds our environmental variable which connect our app with Pusher. Create .env file in your working directory.</p><pre>app_id=your_api_id<br>app_key=your_app_key<br>app_secret=your_app_secret<br>app_cluster=your_app_cluster</pre><p><strong>Creating User Login and Registration System:</strong></p><p>Now create user login and registration authorization system named login_auth.py and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af0c711f628658b9875baab96ac17abb/href">https://medium.com/media/af0c711f628658b9875baab96ac17abb/href</a></iframe><p>Before you run the script create a database named <strong>user_info </strong>and this database create a table named userwith columns:</p><ul><li>used_id : a unique id for each user</li><li>name : stores the name of each user</li><li>username : stores the username</li><li>passwod : stores the password</li></ul><p>You can create the database in Structured Query Language or in MySQL Workbench.</p><blockquote><strong>If you don’t know Structure Query Language(SQL) then go for MySQL Workbench, it provides GUI based environment for creating a database without any knowledge of SQL.</strong></blockquote><p><strong>Creating Chatroom Database:</strong></p><p>After you create user login system, its time to setup the chatroom for our users.Now , create a file named chatrooms_server.py and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d003eca20742ddebc59ae775dd380646/href">https://medium.com/media/d003eca20742ddebc59ae775dd380646/href</a></iframe><p>Again before you run this script, create a table named user under same database user_info with columns</p><ul><li>server_rooms : stores all registered chatroom</li><li>id : unused variable in the program but still required</li></ul><p><strong>Creating the File Transfer System :</strong></p><p>Now we will setup our FTP to transfer file in-app.Here, in my app I used DriveHQ FTP Service (Free Version).Only you have to sign up in <a href="https://www.drivehq.com/">www.drivehq.com</a> as free service user.You can use any FTP Service you want.</p><pre><strong>Cloud FTP Server Details of DriveHQ</strong>:(for free user)<br>FTP SERVER NAME: ftp.drivehq.com<br>IP ADDRESS : 66.220.9.50</pre><p>Now create a script called ftpserver.py and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff074db9505ea46187e4d63a01fdf7b/href">https://medium.com/media/6ff074db9505ea46187e4d63a01fdf7b/href</a></iframe><p>Above code, is used to upload the file provided by user in cloud and to download the file requested by user.</p><p>Here, ftplib is a File Transfer Protocol module that implements the client side of the FTP protocol.</p><p><strong>Creating the main app and its UI:</strong></p><p>Now create a file called terminalchat.py and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a6bcadc737be6e572f92df8ec0e8ede/href">https://medium.com/media/1a6bcadc737be6e572f92df8ec0e8ede/href</a></iframe><p>Let explain you what is happening in the above code.</p><p>We import termcolor to print color text, PyInquirer to print formatted menu in the console, progress to do animation in our console and finally load_env to load environment variables from .env file.</p><p>Here, we also imported ftpserver.py and user_login_reg.py so that we can use the functionality of those script in our terminalchat.py script.</p><p>The TerminalChat class then defined, with some properties</p><ul><li>pusher : this property will hold the Pusher server instance once it is available.</li><li>channel: this property will hold the Pusher instance of the channel subscribed to.</li><li>clientPusher: this property will hold the Pusher client instance once it is available.</li><li>user: this property will hold the details of the currently logged in user.</li><li>users: this property holds a static list of users who can log in, with their values as the password. In a real-world application, this would usually be gotten from some database</li><li>chatrooms: this property holds a list of all available chat-rooms one can join.</li></ul><p>Now let describe you the defined functions in terminalchat.py :</p><ul><li>main : This a entry point into our script. Here,we call welcome function , the login function and the chat selector function.After that, we have a while loop with getInput function so the function will be always running and we will always have a input to type new message to the terminal.</li><li>logincred : It is a login function. In this function we request username and password from user and calls login_auth_reg.login() function for authorizing the login.</li><li>chatselector: It also the user to create or enter into a specific chatroom. It will check whether the input chatroom exists or not. If it exists , the call initPusher , which initialized and setup Pusher to send and receive our message</li><li>getInput : It shows an input with the logged in user’s name in front, waiting for the user to enter a message and send</li></ul><p><strong>NOTE</strong>: In terminalchat.py is have used os.system(&#39;cls&#39;) as my development environment is Windows. If you running this script in Linux, replace os.system(&#39;cls&#39;) to os.system(&#39;clear&#39;) .</p><p><strong>Connecting to the Pusher server:</strong></p><p>Now we will connect the server to our client i.e our chat app. So to implement that we need import the following packages in terminalchat.py .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5474e30e8551d9e28165f67ac50b2b8/href">https://medium.com/media/b5474e30e8551d9e28165f67ac50b2b8/href</a></iframe><p>After this add this segment of code in terminalchat.py :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecd95c53e9a3f67d763a771f1a5c9aad/href">https://medium.com/media/ecd95c53e9a3f67d763a771f1a5c9aad/href</a></iframe><p>In initPusher function, we initialize a Pusher instance to a variable named pusher , passing in our app_id ,app_key, app_secret and app_cluster . After that we initialize a new Pysher client for Pusher. Here we Pysher as client library for Pusher because default library of Pusher only allows triggering of event and not subscribing them. We bind to the connection , the pusher:connection_established is pass to connectHandler function as its callback.After that, we call connect on clientPusher .</p><p>In connectHandler , we receive an argument as data , which comprise of connection data that comes from established connection between Pusher WebSockets. We subscribe to the channel, which has been chosen with Pusher, then bind to an event called newmessage, passing in the pusherCallback function as it’s callback.</p><p>In the pusherCallback method, we receive an argument called message, which returns the object of the new message received from Pusher. Here, we convert the message to a readable JSON format for Python, then check if the message isn&#39;t for the currently logged in user before printing the message to the screen alongside the sender’s name. We also print the logged in user’s name to the screen, with a colon in its front, so the user knows he can still type.</p><p>Now this segement of code at the end of getInput function of TerminalChat class:</p><pre>self.pusher.trigger(self.chatroom, u&#39;newmessage&#39;, {&quot;user&quot;: self.user, &quot;message&quot;: message})</pre><p>After receiving a message, we trigger a newmessage event to current chat-room,which pass the current user and message sent.</p><h3>Putting all pieces of Code into one file</h3><p>Here is what our terminalChat.py looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d017cb8fb90fd923c7d8399bf83113b1/href">https://medium.com/media/d017cb8fb90fd923c7d8399bf83113b1/href</a></iframe><h3>Demo</h3><p>The demo of our Terminal Chat App :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fwy43hNxlfKg%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dwy43hNxlfKg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fwy43hNxlfKg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bc07093591e0b9fad820a23116010c9/href">https://medium.com/media/0bc07093591e0b9fad820a23116010c9/href</a></iframe><p>Finally, thanks for bearing with me and reading till the last character! I applaud your patience 🙂.</p><p>Ref. : <a href="https://www.pusher.com/tutorials">https://www.pusher.com/</a></p><p>P.S: For my other projects, check my <a href="https://github.com/ayanbag">GitHub</a> Profile.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=663a763ba420" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>