dgplug member blogs

Reader

Read the latest posts from dgplug member blogs.

from mrinalraj

Before jumping to the answer let us first understand what is a non-technical group. The non-technical group is the group that conducts events and activities which are directly or indirectly related to managing the public at large. In my current college days, I have been part of several non-technical groups like Avalanche, Scriptink and some technical group like Decoders, Dgplug Technical groups are always a good option as they directly build your academics and problem-solving skills.

HENCE

Is it not economical to be a part of some technical groups as they also conduct competitions where I can interact with public? Yes, you can but just being in the technical group won't give you all skills related to Interpersonal as well as Intrapersonal. Interpersonal skills include teamwork, leadership, fluent communication, etc. Intrapersonal skills are the way you talk to yourself; includes self-esteem, open-mindedness, etc.

Advantage for being in Non-Technical groups

When you conduct non-technical events, you need to attract the crowd as they show little interest unless it is properly advertised and spoon-fed. Most of them find it a waste of time and the situation becomes worse if it has some entry fees. Then there comes your selling skills which include efficient communication, convincing power, body language, confidence and lot more. Below are the following positions where a group act as a sculpture which helps to give the right shape to your personality.

  • Letter permission: Drafting a letter is one of the important tasks as it is the first step to get permission. Here you learn how to frame a letter with utmost care.
  • Event Planning: Now deciding an event name and the idea requires a lot of creativeness. Because this will decide whether your audience will leave the venue happily or not.
  • Digital Poster: Now after the events are decided and date is fixed it's time to reach the maximum audience. Digital poster and pamphlets are the best and cheapest way to advertise. Here you learn editing tools like Adobe Photoshop, Premiere Pro, etc.
  • Handmade poster: Here you get to showcase your creativity in forms of brush and paints.
  • Sponsorship: To make all this stuffs require lots of money. Hence getting sponsors for your event is one of the most important tasks. Here you will develop marketing skills. No matter how good your product is but without proper marketing it is worthless.
  • Treasury: All the purchasing related kinds of stuff are handled by this person. Treasury is considered to be the backbone of the group. Here you will develop skills on where and how to spend money efficiently.
  • Team player : Great teams consist of the right people, not the best people. Every team member must understand the importance of working in a team because the team needs dedication and perseverance.
  • Anchoring: Anchoring helps you to overcome stage fear, enhances the ability to engage the audience and also improves your body language.

Technical Vs Non Technical Groups

Conclusion

So by now you might have got a fair idea on how non-technical groups work and how it helps in shaping your social interaction. But getting into these elite groups is not always an easy task. They have their rigorous recruitment test which includes: 1. Quantitative round, 2. Group Activity 3. GD (Group Discussion) 4. PI (Personal Interview) Being in a group helps in making your college life super memorable. ALL THE BEST!

 
Read more...

from Stories of raydeeam

I'm in the middle of the Ocean, drowning with few things. Trying to reach to the coast but I want to use so many things. I think, that's the reason why I am still stuck here with few things.

 
Read more...

from pradhvan

PyCon India is one of those conferences that I look forward to every year. This year marked my fourth conference in a row. I was excited to meet all my old friends and make some new ones.

ChennaiPy the local python user group of Chennai hosted this year's conference. This meant two things I will get to attend the conference in Chennai and also visit some beaches around Pondicherry. So yeah I was super excited.

The journey to the conference started on 11 October, I was traveling from Delhi with two of my friends Kuntal and Sakshi. Since we planned our journey in such a way that we would reach one night before the conference, we missed the pre-conference volunteer's meet. Kuntal and I were in a state of regret of not taking the morning flight as the pre-conference volunteer's meet are super fun. You get to see the venue beforehand, helps out with swag bags and interact with all the volunteers and organizers of the conference.

On reaching the Chennai airport we met with Dedipyaman, he was staying with us. His name was a bit unique so we called him twodee, which he later adopted as his nick. Traveling to our Airbnb apartment was a challenge in itself as none of us knew Tamil. We were staying with 13 other folks, I knew most of them besides one, Shubo. I had seen the nick on the #dgplug but haven't met him in person. When we arrived at the apartment only Shubo was present, rest came in an hour or two. As everyone settled, we played some rounds of Uno while enjoying pizzas just before going to bed.

The next day I left with twodee and Sakshi for the conference, we were running a bit late. When we reached the conference I saw Kuntal at the registration desk. We all got our attendee card and proceeded to the conference. I saw all my old friends, most of them I only personally meet during conferences as they all live in a different state. So it was fun to catch up. After roaming around the sponsors both I went to attend Pradyun's talk. The talk was titled Python Packaging – where we are and where we're headed, I was interested in the talk as only a handful of people maintain pip. Since it's such a huge ecosystem in itself it was interesting to get some insights from Pradyun's talk about how packaging works with pip and how are they planning to move forward. Later in the tea break, I met with Saurav and Haris. I learned a lot from the conversion we had during the tea break. These people have been in tech much before me. Saurav talked about his company Deepsource, how managing a small team with people who take up responsibility is easy. You don't have to worry about those formal things like timesheets, leave policy because people take responsibility for their work. Haris was working in a two-person team and shockingly carried a very old cell phone which didn't even have internet. So his take on life was very interesting.

The next day we had our annual #dgplug staircase meeting, this year since Kushal was sick. Sayan took the initiative of conducting the meeting. We discussed the first staircase meeting, what went wrong in this year's summer training that people weren't completing their tasks, weren't showing up in the IRC channel and what needs to be done now. I meet lambainsaan who I had always thought was a bot.

The meeting concluded at noon and it was just in time for me to catch up the talk “Let's hunt a memory leak” so I ran to the hall to get a good spot. Sanket was the speaker, he showed us various ways how he solved memory leak problems in a flask app in production while describing the whole memory management concept in Python. I rushed for lunch after the talk as I had to be in open spaces for the PyDelhi's session.

Anuvrat had registred the open space for PyDelhi and other communities of the north. The whole agenda of the open space was how to be consistent while conducting the meetup, what can we do in the meetup we get people to come often and how can we increase the quality of the talks. I liked one idea of pushing all the 101 sessions to blog posts or even hangout sessions a day before the event so we aren't limiting the target audience to just people who are starting in tech. Of what we have been observing in the recent meetups, experienced people who can help mentor people and give great talks have stopped attending meetups. The problem is there were a lot of 101 sessions happening. We concluded that we can shift those 101 sessions to blog posts and if someone wants to give a 101 session we can have themed meetups once in one-two months where they can present those talks. The open spaces were scheduled for half an hour but we stretched it a bit longer as more people started adding points to the discussion.

Before the closing keynote of the day I helped in volunteering at hall-B, I was so much excited for the keynote that during the tea break before the closing keynote I went and sat in the second row of the hall just so I can enjoy the talk from a good spot.

The conference ended with David Beazley keynote, he live coded a stack machine, wrote an interpreter for Web Assembly game that was initially written for Rust in Python and in the end added PyGame to make it into an actual game. It was a jaw-dropping moment for me, though I lost in the midway of his talk it was a bit advanced for me. But when I looked around most people were feeling the same. The keynote ended with standing ovation from all the people in the hall. For me, the whole closing keynote was like a movie it was such a joy to just watch David live code and nothing could have been a better way to end a conference.

The last day of our stay in Chennai was a bit weird as there was some issue with water in our apartment so we went a bit late to the workshop. I had bought tickets for David's workshop “Write your own Async”. In the workshop I tried to follow up with him, was writing code just as he would do it but after the second half, I was a bit lost so I just focused on listening to him. It was not exactly like a workshop but more of him giving us a problem and we would discuss the solution to it and he would live code the solution after the discussion. The solutions were so well designed that it would be similar to the inbuilt functions that the Async module has. As I tried to live coded with him so wasn't able to make some detailed notes that I could revisit later.But luckily he uploaded the workshop screencast so I can revise the concepts again.

The day ended with me saying goodbye to all the people that had stayed late during the dev sprints as workshop and devsprints were happening in parallel.

This marked the end to one more year of my PyCon India journey. It was my fourth PyCon India and the most special one. I stayed with people that I look up to in real life and had lots of fun. The funny thing is not all of them use Python as their day to day language yet they came to a conference dedicated towards the language. I guess that's the beauty of the community. You meet so many people from different backgrounds and learn from them which not only helps you be a better developer but also gives a different perspective towards your life.

 
Read more...

from darshna

A few months ago I came to know that pycon was happening in Chennai on the month of October, and I realized that attending this year's PyCon is necessary. Deep down I knew that after returning from Pycon I'll not only make new connection and potential people but also it'll change my perspective about the open-source world(in a good way). Also this was my first time that I'll be moving out from my home town, I asked mom that this will be a great opportunity for my exposure of life and experience, as unfortunately there's not much stuff happening in my college(except mass bunking and unnecessary gossip). And my Durga puja was over, packed my bags and left for Chennai. After 27 hours of a long journey, I reached the station, where communicating with people was a bit tough, but my ecstasy was unlimited of meeting that part of India(South). I couldn't sleep that night, I woke up early morning and got ready and reached the venue with one of my folks (@priyankasaggu) from dgplug. When I reached there I was amazed at the crowd which gathered there, I took my id card, and went in the venue, people were everywhere are. Earlier I didn't notice that goodies were being distributed if you play quiz from the respective booths of sponsors. At the evening after the event got over we (dgplug) members went to beach and spent some good time together. It was day 2 and coincidently I met some new friends who were from Kerala and thet were of my same batch and of same stream. So, I attended the keynote speaker who was Ines Montani, and yeah I did not understand everything as clear as water but yes, I did get an idea. And at the end of the day, we all the folks of dgplug went for dinner and enjoyed our meals and some quality time together.

Overall, my experience if I rate out of 10, it will 10/10...yeah every penny i spent to come here, every hour of my journey I spent to come here was worth it...Before coming to PyCon 2k19, I asked myself that none of my friends came from my college.. will it be worth it? Now I know yes it was worth it!

 
Read more...

from jason’s wotw blog

wotw, leisure

And to tell the truth I
don't want to let go of
the wrists of idleness, I
don't want to sell my life
for money, I don't even
want to come in out of
the rain.

And with this delightful Mary Oliver quote, this little blog, bids you adieu awhile.
I want to go and play in the rain :)

 
Read more...

from jason’s wotw blog

wotw, gut punch

means something knocks the wind out of you literally a punch to the gut. means to be suddenly be emotionally wound up, because of something you see or hear.

like I am about to do to you …


 
Read more...

from darshna

Here we will get to know about the If-else, control flow.

As the name says (if) it simply applies the condition applied to it. If the value of the expression is true, the command works according to it. #!usr/bin/env/ python 3 number= int(input("Enter a number:")) if number<100 print("the number is less than 100")

Else statement:– This is used when the (if)statement is not fulfilled.

#!usr/bin/env python3 number= int(input("Enter a number:") if number<100 print("The number is less than 100"); else print("The number is greater than 100");

 
Read more...

from mrinalraj

grep "unix" filename.txt : prints only line containing unix also higlights the “unix ” wherever it is present. unix is great os. unix is opensource. unix is free os. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

grep -n "unix" filename.txt : prints only line containing unix and also gives the no. line. 1:unix is great os. unix is opensource. unix is free os. 3:unix linux which one you choose. 4:unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

$grep "[2-3][0-9]" emp : Check for the string from 20 to 39 TCS101 Anu Engineer Manufacturing 30 35000 INFY02 Sona Developer Development 25 29000 TCS102 Raki Accountant Admin 31 32000 INFY03 Arun Engineer Manufacturing 28 34000 INFY04 Amit Accountant Admin 24 27000 TCS103 Nanda Engineer Manufacturing 29 37000 TCS104 Swathi Developer Development 28 29000

$ grep -v "[2-3][0-9]" emp :Invert the sense of matching, to select non-matching lines.

$ grep -n "[2-3][0-9]" emp : Displays in ordered list.(i.e. with line number) with string matching from 20 to 39. 1:TCS101 Anu Engineer Manufacturing 30 35000 2:INFY02 Sona Developer Development 25 29000 3:TCS102 Raki Accountant Admin 31 32000 4:INFY03 Arun Engineer Manufacturing 28 34000 5:INFY04 Amit Accountant Admin 24 27000 6:TCS103 Nanda Engineer Manufacturing 29 37000 7:TCS104 Swathi Developer Development 28 29000

$ grep -n "TCS[0-3][0-9][0-9]" emp : Displays only TCS employee details with line number present in the original file ranging from TCS000 to TCS399. 1:TCS101 Anu Engineer Manufacturing 30 35000 3:TCS102 Raki Accountant Admin 31 32000 6:TCS103 Nanda Engineer Manufacturing 29 37000 7:TCS104 Swathi Developer Development 28 29000

*NOTE : emp and student are the file names.*

 
Read more...

from mrinalraj

unix is great os. unix is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

sed -e 's/unix/UnIx/g' filename.txt : Searches for unix and replaces it with UnIx everywhere. Here g stands for making changes globally. UnIx is great os. UnIx is opensource. UnIx is free os. learn operating system. UnIx linux which one you choose. UnIx is easy to learn.UnIx is a multiuser os.Learn UnIx .UnIx is a powerful. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

sed 's/unix/UnIx/1g' filename.txt : Replaces with Unix globally from the first occurrence in a line. UnIx is great os. UnIx is opensource. UnIx is free os. learn operating system. UnIx linux which one you choose. UnIx is easy to learn.UnIx is a multiuser os.Learn UnIx .UnIx is a powerful. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

sed '3,5s/unix/UnIx/' filename.txt : It will replace the unix with UnIx from 3rd line till 5th line if present. unix is great os. unix is opensource. unix is free os. learn operating system. UnIx linux which one you choose. UnIx is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

sed '1,2s/unix/UnIx/' filename.txt: It will replace the unix with UnIx from 1st line and 2nd line. UnIx is great os. unix is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

sed '1,$s/unix/UnIx/' filename.txt : It will replace the unix with UnIx from 1st line till the last line. Here “$” indicates end line. UnIx is great os. unix is opensource. unix is free os. learn operating system. UnIx linux which one you choose. UnIx is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

sed '/unix/ a "Add a new line"' filename.txt : It adds “Add a new line” at the end of the line in which unix occurred. unix is great os. unix is opensource. unix is free os. “Add a new line” learn operating system. unix linux which one you choose. “Add a new line” unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. “Add a new line” linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

sed '/unix/ i "Add a new line"' filename.txt : i means insert the “Add new line” before the occurence of unix “Add a new line” unix is great os. unix is opensource. unix is free os. learn operating system. “Add a new line” unix linux which one you choose. “Add a new line” unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

sed '/unix/ c "Add a new line"' filename.txt : replace the line containing unix with the content “Add new line” “Add a new line” learn operating system. “Add a new line” “Add a new line”

 
Read more...

from mrinalraj

In Python there is no need to import any external libraries for file handling as it comes with an inbuilt library There are 3 main operations associated with the file. 1. Creating/Opening a file. 2. Writing into the file/ Reading from the file. 3. Closing a file.


Step 1: Creating Opening a file :

Syntax : filePtr = open("your_file_name.txt", "mode") Following are the modes supported in python: 1. “w”, “r”, “a”: To open files in write mode, read mode and append mode respectively. ex: filePtr = open("my_file.txt", "w") It will create a new file if the given file name doesn't exist else it will overwrite the contents of the given file.

filePtr = open("my_file.txt", "r") It will open a file only if it exists in the reading mode. i.e. we cannot edit the contents of the file.

filePtr = open("my_file.txt" , "a") It will append the contents of the file if already exists else it will create a new one.

  1. “w+”, “r+”, “a+” : To open a file in write and read mode, read and write mode, and append and read mode.

filePtr = open("my_file.txt", "w+") It will create a new file if the given file name doesn't exist else it will overwrite the contents of the given file. In this mode, we can also read the content of the file at the same time.

filePtr = open("my_file.txt", "r+") It will open a file only if it exists in the reading mode also we can edit the contents of the file unlike in “r” mode. ** Note: +r differs from +w mode as in +r mode it doesn't delete the content also it doesn't create a new file if doesn't exist.**

filePtr = open("my_file.txt" , "a+") It will allow simultaneous read and append operation on the file.

  1. “wb”, “rb”, “ab”: To open files in write, read and append in binary mode respectively. ex: filePtr = open("my_file.txt", "wb") It will create a new file if the given file name doesn't exist else it will overwrite the contents of the given file.

filePtr = open("my_file.txt", "rb") It will open a file only if it exists in the reading mode. i.e. we cannot edit the contents of the file.

filePtr = open("my_file.txt" , "ab") It will append the contents of the file if already exists else it will create a new one.

  1. “wb+”, “rb+”, “ab+” : To open a file in write and read, **read and write **, and append and read in binary mode.

filePtr = open("my_file.txt", "wb+") It will create a new file if the given file name doesn't exist else it will overwrite the contents of the given file. In this mode, we can also read the content of the file at the same time.

filePtr = open("my_file.txt", "rb+") It will open a file only if it exists in the reading mode also we can edit the contents of the file unlike in “r” mode.

filePtr = open("my_file.txt" , "ab+") It will allow simultaneous read and append operation on the file.


Step 2: Writing in a file/ Reading from the file:

We can write in a file using write() function Syntax : filePtr.write("THIS is a file CONTENT")

We can read from the file using read() and readline() function ex: content = filePtr.read(): This return the entire content of the file. content = filePtr.readline(): This returns only the content of one line in a file.


Step 3: Closing a file

Closing a file is very important as if it exceeds the top limit it can lead to the crashing of the program. So it is advisable to close a file. Syntax : filePtr.close()

 
Read more...

from pradhvan

This is the second part of the series, in the first part we talked about the general idea of concurrency, how it's different from parallelism and saw how Python handles concurrency.

Part 1: Talking Concurrency -1

In the second part of the blog, we will look into the modern solution towards the problem using the new Asyncio module.

Import Asyncio

In the last post, we looked into a basic code snippet on how can we write concurrently. We also discussed some of the basic terminology used while using the Asyncio module. If you don't remember you should quickly take a recap as we would look at those concepts in a bit detailed manner.

Before looking at some code, let's understand some basic terminologies that would help in understanding the code better.

  • Eventloop: it's an infinite loop that keeps track of all the running tasks. It manages all the suspended functions and executes them when the time is right. These functions are stored in the queue called as the Task Queue, the event loop constantly polls the task queue and passes them to the event loop. When a task is passed on to the event loop it returns back a future object.

  • Future: a future is an indirect reference to a forthcoming result. It can loosely be translated as promise you make to do something when a condition is met, so when the condition is met a future can “callback” when ready to be executed. Since everything is an object in python, future is also an object that has the __await__() method implemented and its job is to hold a certain state and result. The state can be one of three things:

Pending: it does not have a result or exception yet. Cancelled: it was canceled Finished: it was finished either with a result or exception.

Futures also have a method called the add_done_callback() this is method allows the function to be called as soon as the task is completed with its process and is returned with a result. Which is the python object that would be returned with the expected result or raise an exception when the task is finished.

  • Tasks: a task executes a coroutine in an event loop. In a program, asyncio.create_task(coroutine) wraps the coroutine into a task and schedules its execution. asyncio.create_task(coroutine) returns a task object. Every time a coroutine is awaited for a future, the future is sent back to the task and binds itself to the future by calling the add_done_callback() on the future. From now on if the state of the future changes from either canceled or finished, while raising an exception or by passing the result as a python object. The task will be called and it will rise back up to its existence.

Since a typical program will have multiple tasks to be executed concurrently, we create normally with asyncio.create_task(coroutine) but we run them with asyncio.gather().

  • Coroutine: Asyncio was introduced in Python 3.4, initially it started off as decorator based coroutines @asyncio.coroutine which used a yield from keyword. Later in Python 3.5 async and await keywords were introduced which made working/reading concurrent code much easier. I won't go into much detailed on how coroutines evolved to the new async def keyword, because I planning to write a separate blog on that.

As we looked into the basic definition of coroutines in the last blog, we can loosely describe them as restartable functions.

You make a coroutine with the help of the async def keyword and you can suspend the coroutine with the await keyword. Every time when you await the function gets suspended while whatever you asked to wait on happens, and then when it's finished, the event loop will wake the function up again and resume it from the await call, passing any result out. Since coroutines evolved from generators and generators are iterators with __iter__() method, coroutines also have __await__() which allows them to continue every time await is called.

At each step a coroutine does three things:

  • It either awaits a future
  • It awaits another coroutine
  • It returns a result.

Before moving forward, I want to talk about await. In Python, anything that can be awaited i.e used with the await keyword is called an awaitable object. The most common awaitable that you would use would be coroutines, futures and tasks. Thus anything is blocking get's put to the event loop using the await and added to the list of paused coroutines.

Now let's look at a very basic async program to understand how everything fits in together.

import asyncio

import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

asyncio.run(print_sum())

The sequence diagram below describes the flow of the above program.

tulip_coro.png

Now that we know all the basic terminology used in an async program let's look at a slightly complex code below for getting a better understanding all the jargons we learned above.

import asyncio


async def compute(x, y):
    """
    A coroutine that takes in two values and returns the sum.
    """
    print(f"Computing the value of {x} and {y}")
    await asyncio.sleep(1)
    return x + y


async def print_sum():
    """
    A coroutine that creates tasks.
    """
    value1 = asyncio.create_task(compute(1, 0))
    value2 = asyncio.create_task(compute(1, 0))
    value3 = asyncio.create_task(compute(1, 0))
    print(sum(await asyncio.gather(value1, value2, value3)))

asyncio.run(print_sum())

async def print_sum() and async def compute() are the two coroutines in the above program, the async def print_sum() as the main function used in the sync programming. The main function executes the entire program and all the functions related to it. The same approach is followed here, one coroutine awaits all the other coroutine.

Though this can be easily miss-understood, in that case, the program would just fine but would run in more like a sequential manner.

    value1 = await asyncio.create_task(compute(1, 0))
    value2 = await asyncio.create_task(compute(1, 0))
    value3 = await asyncio.create_task(compute(1, 0))
    print(sum(value1, value2, value3))

The above code can be a good example of how not to write async code, here using await on every task we are making all the calls sync thus making the program sequential. To avoid this asyncio.gather() is used in the program. To gather all the tasks in the program, value1, value2 and value3.

Finally, when all the tasks are gathered together, they are run concurrently.

Sync-Async-Sync

A lot of time you might be in a situation where you might have to call a sync function def from coroutine async def or have to call coroutine async def from sync function def. Ideally, you “shouldn't” use sync functions for calls that can be async like a database call because that is something that could provide further optimization. But there is nothing wrong with using a synchronous library for database, an async library for HTTP and gradually move things to async.

  • Sync-Async

Calling a sync function def from a coroutine async def. In that case, you run the sync function in a different thread using the threadpool executor. The runinexecutor() method of the event loop takes an executor instance, a regular callable to invoke, and any arguments to be passed to the callable. It returns a Future that can be used to wait for the function to finish its work and return something.

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

asyncio.run(main())
  • Sync-Async

When you have to call coroutines from the normal sync function. You just have to manually get_event_loo() , create tasks() and call the asyncio.gather() function. Since you can await, one thing you can do is create a queue with asyncio.queue() and use that queue to pass around the data between different coroutines.


import asyncio


async def compute(x, y, data):
    print(f"Computing the value of {x} and {y}")
    result = x + y
    await data.put(result)


async def process(n, data):
    processed, sumx = 0, 0
    while processed < n:
        item = await data.get()
        print(item)
        processed += 1
        value = item
        sumx += value
    print(f"The sum is:{sumx}")
    await asyncio.sleep(.5)


def main():
    loop = asyncio.get_event_loop()
    data = asyncio.Queue()
    sum1 = loop.create_task(compute(1, 4, data))
    sum2 = loop.create_task(compute(0, 0, data))
    sum3 = loop.create_task(process(2, data))
    final_task = asyncio.gather(sum1, sum2, sum3)
    loop.run_until_complete(final_task)


if __name__ == '__main__':
    main()

What now?

  • Just to get a better understanding of all the next syntax you learned, you can try out a sample problem mentioned below.

Write a program that reads log files and refires those URLs that have a 5xx status code. Once the refiring is done just add the &retry=True in the prefix of the URL and store them in a separate log file.

The log file will be a text file, you can check out a sample file here.

  • As I am still exploring the concept concurrency so I don't exactly know the best practices and pitfalls you should avoid while writing async code, but I highly recommend you check out asyncio: We Did It Wrong – roguelynn. This article can be a good followup after you are done with this one and are comfortable with syntax of asyncio.

Just before ending the blog I would like to thank maxking and Jason Braganza for helping me out in the blog.

In the next part of the series, I will be talking about threads and finally will conclude the series with asyncio based frameworks such as quart and aiohttp.

Happy Coding!

 
Read more...

from darshna

Be who you are, not who others tell you to be.

The above quote clearly replicates confidence and self-love. We somehow get affected by the negative comments and judgments passing by and try to change ourself so that people would accept us the way we are. Finally, when we arrange ourselves for the people to accept us there is again a judgment passing by and yet again we try to change ourselves. In the end, we forget the real us and be a toy for people's satisfaction. as we grow old we realize that we have left the true selves way back and been another person. Fat-shaming or Body shaming, being a dark-skinned girl or being extra bold even wearing a dark lipstick at daytime, or wearing clothes of your own choice attracts people's attention more than taking care of social and devastating issues happening day-to-day. Have you ever heard someone saying that look at the person who threw the packets on the side of a road or look at the person who is pissing at a public place, why aren't they ashamed? Yes, I am healthy and have a unique body shape that maybe most girls don't have or most guys make fun of it. So what? yes I am like this and I am proud of it but you will ignore it once or twice or maybe thrice. Ignorance is not a solution the mentality should be changed, and it can only change if people start teaching their children the value of respect and acceptance, acceptance of people as they are. That obviously doesn't include the acceptance of wrongdoings and violent nature of some people, but accepting the things to make this a society and a better place to live. Only then we can stand together and build a healthy community.

 
Read more...

from jason’s wotw blog

wotw, myth

the stories we tell ourselves as a culture, to explain what we could not really explain.

to help use make sense of the world, so that we’d not fuss over the unexplained and let us get on with our lives and make progress with the things we do understand.


 
Read more...

from darshna

After so many days I am continuing with Python again. Yes, I was not able to maintain the series properly, but let's get back to work and know what I read next in Python from the book of PYM. In Python most of the lines will have expressions and these expressions are made of operators and operands.

Operators

These are the symbols which tells the python interpretor to do the mathematical operation.

2+3
5
22.0/12
1.83333

To get floating results we need to use the division using any of operand as the floating number. To do modular operation use % operator.


#!/usr/bin/envv python3
days= int(input("Enter days:"))

month= days/30
days= days%30
print("Months= %d days= %d %(month, days))

Relational operators

operator ## meaning

< is less than > is greater than <= is less than or equal to >= is greater than or equal == is equal to != is not equal to

Note: // operator gives floor division result.

4.0//3
1.0

4.0/3
1.33333

Logical operator

To do a logical AND, OR we use these keywords.

 
Read more...