<?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 HackerCulture on Medium]]></title>
        <description><![CDATA[Stories by HackerCulture on Medium]]></description>
        <link>https://medium.com/@hackerculture?source=rss-eab17725e227------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*An2P5vsr5dfKp0KdpgQfSA.png</url>
            <title>Stories by HackerCulture on Medium</title>
            <link>https://medium.com/@hackerculture?source=rss-eab17725e227------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 14 May 2026 08:01:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hackerculture/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[The Ultimate Python Programmer Roadmap (2023)]]></title>
            <link>https://medium.com/hackerculture/the-ultimate-python-programmer-roadmap-2023-e6f79322f84b?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f79322f84b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 21:43:20 GMT</pubDate>
            <atom:updated>2023-01-30T18:32:33.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lWtIS9OFW3eUXMHb.jpg" /></figure><p><em>Originally published at </em><a href="https://www.hackerculture.com"><em>https://www.hackerculture.com</em></a><em> on January 10, 2023.</em></p><p>Python is the most loved programming language by both beginners and experts, according to multiple surveys. And not only software developers but other people from different disciplines use Python for a variety of different tasks, such as data analysis and visualization, artificial intelligence and machine learning, automation, etc.</p><p>There has never been a better time to learn Python, and with our resources created by professional Python developers with decades of experience, you can learn the skills and techniques that really matter in the real world. You can use Python to build web apps, mobile apps, and desktop applications, as well as software testing and even some actual hacking.</p><p>Whether your goal is to learn python for web development, data science, or machine learning, we’ll go over the most important libraries and resources you need to learn after getting the basics down.</p><h3>Python Basics</h3><p>First, we need to install python so we can play around with it:</p><p><a href="https://www.hackerculture.com/python-setup/">Setting Up Python and Virtualenvs with Pyenv</a></p><p>Then, you can follow this roadmap to go from Python beginner to knowing <em>“just enough to be dangerous”</em> with Python. While this list doesn’t cover every single feature, it does cover many of Python’s most noteworthy features and will enable you to read and write Python modules and programs.</p><ol><li><a href="https://www.hackerculture.com/intro-to-python/">Python Basics: Code Your First Python Program</a></li><li>Variables and operators</li><li>Numbers and math</li><li>Strings and string methods</li><li><a href="https://www.hackerculture.com/basic-python-data-types/">Basic Data Types in Python</a></li><li>Loops in Python</li><li>Exception handling</li><li>Modules</li></ol><p>This section will give you the tools to make complex applications and introduce you to concepts about Object Oriented Programming (OOP) in Python:</p><h3>Advanced Python Topics</h3><p>This section builds upon the previous ones and teaches you how to use frameworks and libraries available in the Python language:</p><p>Once you have gone through all the previous steps, you should have everything you need to make use of Python in real-world applications.</p><p>Python is used in almost every industry, and you have a few career path options. Let’s look at some of these.</p><h3>Python for Web Development</h3><p>The role of a web developer is to build websites and applications that are accessible using a web browser. Python is typically used on the backend side.</p><p>A popular web framework that many companies use to build web applications is <strong>Flask</strong>. This tutorial will help you become familiar with building apps with Flask:</p><p><a href="https://realpython.com/flask-connexion-rest-api/">Python REST APIs with Flask</a></p><p>You should also become familiar with databases. This tutorial covers how to integrate databases with your Flask server:</p><p><a href="https://realpython.com/flask-connexion-rest-api-part-2/">Connecting a Database to your Flask Project with SQLAlchemy</a></p><p>You can also learn how to deploy Flask apps so you can share them with the world in this article:</p><p><a href="https://realpython.com/courses/deploy-python-script-web-flask/">How to deploy your Flask apps</a></p><p>Finally, you may be interested in learning more about the web and how your users will interact with your apps on their browsers. This course will help you become more of a well-rounded full-stack web developer:</p><p><a href="https://www.coursera.org/specializations/web-design">Web Design Course for Everybody</a></p><h3>Python for Automation</h3><p>Automation is the field of performing tasks that are repetitive or time-consuming, such as data entry, web scraping, and automation of various system processes, in a way that they can be reused and repeated effortlessly.</p><p>A specific use case for automation is the continuous testing of software projects, in which we write scripts to interact with an existing program and report errors.</p><p><a href="https://realpython.com/python-testing/">Getting started with testing in Python</a></p><p>Automation can also be used to control other software, such as a web browser, Excel, or even hardware, such as robotic systems. Some libraries worth checking out for this are:</p><h3>Python for DevOps</h3><p>DevOps engineers are responsible for implementing and maintaining infrastructure to support software systems, and they work to ensure that software systems are deployed quickly, efficiently, and with minimal downtime.</p><p>This book provides a comprehensive introduction to the field of DevOps:</p><p><a href="https://amzn.to/3GToK8H">Python for DevOps: Learn Ruthlessly Effective Automation</a></p><p>Some of the other technologies used by DevOps engineers to automate software deployments and maintain a smooth operation are:</p><h3>Python for Data Science</h3><p>A data scientist’s primary concern is to extract insights and knowledge from data. This typically involves a number of different tasks, including collecting and cleaning data, developing predictions and forecasts using statistics, and visualizing results.</p><p>A data scientist must be familiar with databases and should be able to query large amounts of data in order to identify patterns and trends. Usually, the main tools used by data scientists are:</p><p>If you want to get deeper into data science, consider the following books:</p><p><a href="https://amzn.to/3vR97IT">Data Science from Scratch</a> <a href="https://amzn.to/3XhZOx6">Python for Data Analysis: Data Wrangling with Pandas, NumPy, IPython</a></p><h3>Python for Machine Learning</h3><p>A machine learning engineer creates and develops computer programs that can “learn” from data and make predictions or decisions without being explicitly programmed to do so to solve real-world problems like predicting the weather or detecting facial expressions.</p><p>This typically involves working with large sets of data, which can be explored with the <strong>pandas</strong> library to prepare the data for use in models:</p><p><a href="https://pandas.pydata.org/docs/getting_started/intro_tutorials/">Getting started with Pandas in Python</a></p><p>A very popular library that helps with training machine learning models for different problems is <a href="https://www.simplilearn.com/tutorials/python-tutorial/scikit-learn">Scikit-learn</a>.</p><p>If you are interested in models that use language, check out this NLP resource:</p><p><a href="https://towardsai.net/p/nlp/natural-language-processing-nlp-with-python-tutorial-for-beginners-1f54e610a1a0">Natural Language Processing (NLP) with Python — Tutorial</a></p><p>If you prefer to read a book instead, these books are an excellent way to get into machine learning with Python:</p><p><a href="https://amzn.to/3QwgPBB">Introduction to Machine Learning with Python</a> <a href="https://amzn.to/3k9sMRp">Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow</a></p><h3>Tips for learning Python programming</h3><p>Learning how to write computer programs is hard, but learning Python, in particular, is significantly easier than many other programming languages. These tips will help you stay focused and motivated to achieve your goals:</p><ul><li>Have patience. Learning a new language always requires more effort and time, so understand that it will take time to let everything sink in.</li><li>Don’t feel intimidated by complex terms, errors, and issues. Don’t give up, this happens to everyone in programming. Research the topic using other resources and come back to it with a clear mind.</li><li>Frustration and pain are a part of the process. Embrace them instead of avoiding them, and you will conquer them.</li><li>Be consistent. If you are not consistent in learning, it will take a lot more time and effort.</li><li>Don’t try to learn everything at once. It’s better to practice a specific topic every day before moving on to the next.</li><li>Build small projects to try out the things you learn and build up your confidence. You should add them to your github profile to help you land jobs.</li></ul><p><strong>Did you find this helpful?</strong><br>I’d love to hear about it. Please let me know in the comments.</p><p><strong>Do you have any questions?</strong><br>Leave your question in a comment below, and we’ll answer it with our best advice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f79322f84b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackerculture/the-ultimate-python-programmer-roadmap-2023-e6f79322f84b">The Ultimate Python Programmer Roadmap (2023)</a> was originally published in <a href="https://medium.com/hackerculture">HackerCulture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python asyncio — A Guide to Asynchronous Programming]]></title>
            <link>https://medium.com/hackerculture/python-asyncio-a-guide-to-asynchronous-programming-cf04402a4f53?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf04402a4f53</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 22:00:25 GMT</pubDate>
            <atom:updated>2023-03-03T17:51:09.015Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python asyncio — A Guide to Asynchronous Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8050QqeG_rZucnsqxNnSfQ.jpeg" /></figure><blockquote>Originally published at <a href="https://www.hackerculture.com/ultimate-python-programmer-roadmap/">https://www.hackerculture.com</a> on January 9, 2023.</blockquote><p>In this guide, we’ll introduce asynchronous programming in Python and review fundamental concepts like how to define, create and run asynchronous functions, coroutines, and some common use cases and best practices.</p><p>You may have seen asyncio in a new project you started working on. Or perhaps in a code example of how to perform a common task:</p><ul><li>Perhaps you need to use an API and the code examples use asyncio.</li><li>Or you need to integrate a new library that uses asyncio.</li><li>Or you found some code snippets that use asyncio.</li></ul><p>Once you understand the concepts in this guide, you will be able to develop programs that can leverage the asyncio library in Python to process many tasks concurrently and make better use of your machine resources, such as additional CPU cores.</p><h3>Table of Contents</h3><ol><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#introduction-to-asynchronous-programming">Introduction to Asynchronous Programming</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#getting-started-with-asyncio-in-python">Getting Started with Asyncio in Python</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#what-is-the-event-loop">Working with Asyncio Event Loops</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#what-are-coroutines">What Are Coroutines</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#using-asyncio-for-network-programming">Using Asyncio for Network Programming</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#advanced-asyncio-concepts">Advanced Asyncio Concepts</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#when-to-use-asyncio">When to Use Asyncio</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#when-not-to-use-asyncio">When Not to Use Asyncio</a></li><li><a href="https://www.hackerculture.xyz/python-asyncio-guide-to-asynchronous-programming/#best-practices-for-asynchronous-programming-in-python">Best Practices for Asynchronous Programming in Python</a></li></ol><h3>Introduction to Asynchronous Programming</h3><p><strong>Asynchronous</strong> refers to the concept of not occurring at the same time as something else. In the context of programming, asynchronous refers to the execution of tasks that do not block the flow of execution of other tasks. This means that multiple tasks can be performed concurrently, rather than sequentially.</p><p>This is achieved by using asynchronous function calls, which return control to the calling function before the task is completed, allowing other tasks to be executed in the meantime.</p><p>For example, we can make an asynchronous function call. This will issue the request to make the function call and will not wait around for the call to complete. We can choose to check on the status or result of the function call later.</p><p>One of the main benefits of asynchronous programming is improved performance, as it allows for non-blocking IO operations and allows multiple tasks to be performed simultaneously.</p><h3>Getting Started with Asyncio in Python</h3><p>The asyncio module contains utilities to implement asynchronous programming in Python.</p><p>It allows you to write concurrent code using asynchronous programming techniques rather than traditional thread-based concurrent programming.</p><p>You may be wondering how asyncio differs from traditional thread-based concurrent programming in Python…</p><p>Asyncio is particularly useful in Python because it allows you to write concurrent code in a single-threaded environment, which can be more efficient and easier to work with than using multiple threads.</p><h3>Understanding the async, await syntax</h3><p>We use def async to define asynchronous functions in Python. These are special types of functions that don&#39;t execute right away when called. Instead, they are scheduled, and we must then use await to execute and wait for the function to return.</p><p>This last point is key and is the reason why async functions are so powerful.</p><p>We can also execute async functions in other parts of our program with asyncio.run()</p><h3>What is the Event Loop</h3><p>The <strong>event loop</strong> is the central mechanism in asyncio that schedules and runs asynchronous tasks. It works by continuously polling for events and running the appropriate tasks when they are ready.</p><p>You can think of the event loop as a kind of “coordinator” that manages the execution of asynchronous tasks.</p><h3>Creating and customizing event loops</h3><p>By default, asyncio will create an event loop for you when you use asyncio.run() or call asyncio.AbstractEventLoop.run_until_complete(). However, you can also create and customize your own event loop if needed.</p><pre>loop = asyncio.get_event_loop()<br>loop.run_until_complete(an_async_function())<br>loop.close()</pre><p>The event loop starts with the loop.run_until_complete() method, which blocks until all tasks have completed. Finally, the event loop is closed with the loop.close() method.</p><p>Here are some other ways you can run an event loop in Python using the asyncio module:</p><ol><li>loop.run_forever(): This method runs the event loop indefinitely. It blocks until the event loop is stopped with the loop.stop method or until an exception is raised.</li><li>loop.run_until_complete(future): This method runs the event loop until the given future is completed. It blocks until the future is done or until an exception is raised.</li><li>loop.run_in_executor(executor, func, *args): This method runs the given func in a thread or process executor and returns a <strong>Future</strong> object. The event loop will run until the Future is done or until an exception is raised.</li><li>loop.run_as_soon_as_possible(callback): This method schedules the given callback to be run as soon as possible. It does not block.</li><li>loop.call_later(delay, callback, *args): This method schedules the given callback to be run after the specified delay in seconds. It does not block.</li></ol><h3>What Are Coroutines</h3><p>A coroutine is a task that can be suspended and resumed. In the context of asynchronous programming, when we talk about tasks that can be performed concurrently, we are referring to coroutines.</p><p>Therefore, coroutines are the unit of concurrency used in asyncio programs.</p><p>Many coroutines can be created and executed at the same time. They have control over when they will suspend and resume, allowing them to cooperate as to when concurrent tasks are executed.</p><p>This is called <strong>cooperative multitasking</strong> and is different from the multitasking typically used with threads called <em>preemptive multitasking</em>.</p><p>A coroutine can be defined using the async def expression. It can take arguments and return a value, just like a function. Calling a coroutine function will create a coroutine object, but it <strong>does not</strong> execute the coroutine function right away.</p><pre>async def my_coroutine(delay):<br>    await asyncio.sleep(delay)<br>    print(f&#39;Finished waiting for {delay} seconds&#39;)<br><br># creates but does not execute the coroutine<br>coroutine_1 = my_coroutine(1)<br># await starts the coroutine and blocks until finished<br>result = await my_coroutine(2)</pre><p>When a coroutine is created but never executed, we will see a warning like this when the Python program finishes:</p><pre>sys:1: RuntimeWarning: coroutine &#39;my_coroutine&#39; was never awaited</pre><p>We can avoid this warning and support top-level await expressions by starting the Python interpreter with a default event loop. This is also the default in IPython.</p><pre>python -m asyncio script.py</pre><p>Having top level await is neat, but it can cause problems too. There can only be one event loop running in a thread. If any of your code tries to launch an event loop, perhaps by calling asyncio.run(), you&#39;ll get an error, so be careful.</p><h3>What’s so great about coroutines</h3><p>Threads and processes achieve multitasking managed by the operating system (OS) that chooses which threads and processes should run, when, and for how long. The OS switches between threads and processes rapidly, suspending those that are not running and resuming those granted time to run. This is called <strong>preemptive multitasking</strong>.</p><p>Coroutines in Python provide an alternative type of multitasking called <strong>cooperating multitasking</strong>. This allows coroutines to cooperate by design, choosing how and when to suspend their execution.</p><p>Another key aspect of coroutines is that they are more lightweight than threads. This means they are faster to start and use less memory. They may use less than 1 KB of memory to execute. Essentially a coroutine is a special type of function, whereas a thread is represented by a Python object associated with an operating system thread with which the object must interact.</p><p>Coroutines are a new alternate, interesting, and powerful approach to concurrency, different from thread-based and process-based concurrency. As such, we may have thousands of threads in a Python program, but we could easily have tens or hundreds of thousands of coroutines just in one thread.</p><p>You can also schedule coroutines for execution in separate threads, with <a href="https://www.hackerculture.xyz/python-threads-multithreading-guide/#threadpoolexecutor">ThreadPoolExecutor</a>, or separate processes using <a href="https://www.hackerculture.xyz/running-processes-python-multiprocessing-guide/#processpoolexecutor">ProcessPoolExecutor</a>.</p><h3>How to Run Blocking Tasks with Asyncio</h3><p>We often need to execute a blocking function call within an asyncio application because, in practice, most workloads include a mix of IO-bound operations and also CPU-bound operations.</p><p>This could be for many reasons, such as:</p><ul><li>To execute a CPU-bound task like calculating something.</li><li>To execute a blocking IO-bound task like reading or writing from a file.</li><li>To call into a third-party library that does not support asyncio yet.</li></ul><p>Making a blocking call directly in an asyncio program will cause the event loop to stop while the blocking call is executing. It will not allow other coroutines to run in the background.</p><p>This can be prevented by running the blocking call outside of the event loop, which we can do with asyncio.to_thread().</p><p>The <strong>asyncio.to_thread()</strong> function takes a function to execute and any arguments. It returns a coroutine that can be awaited or scheduled as an independent task. The function is then executed in a separate thread.</p><p>The <strong>asyncio.to_thread()</strong> function creates a <strong>ThreadPoolExecutor</strong> behind the scenes to execute blocking calls.</p><p>As such, the <strong>asyncio.to_thread()</strong> function is only appropriate for IO-bound tasks, and we should not use this method of asyncio for CPU bound tasks.</p><h3>Using Asyncio for Network Programming</h3><p>Network calls are a good use case for asyncio since they’re IO-bound, and we can just fire and forget the write or read<em>,</em> and our program can go on to perform other tasks. The caller does not need to wait for the operation to complete before returning, so we should not waste time just checking on them.</p><p>The read and write operations are performed somehow (e.g., by the underlying operating system or perhaps a task queue like Kafka), and the status of the action and/or data is retrieved by the caller later, once available, or when the caller is ready.</p><p><strong>Non-blocking</strong> IO is a way of performing IO where reads and writes are requested, although performed asynchronously. The caller does not need to wait for the operation to complete before returning. Non-blocking IO is implemented in practice with asynchronous programming.</p><p>Let’s go through a few asyncio examples that implement non-blocking IO in client and server networking:</p><h3>HTTP server</h3><p>This is an example of an asyncio-based HTTP server that serves static files from a given directory. It uses the aiohttp library to handle HTTP requests and responses.</p><pre>import asyncio<br>from aiohttp import web<br><br>async def handle(request):<br>    with open(&#39;index.html&#39;, &#39;rb&#39;) as f:<br>        return web.Response(body=f.read(), content_type=&#39;text/html&#39;)<br><br>async def main():<br>    app = web.Application()<br>    app.add_routes([web.get(&#39;/&#39;, handle)])<br>    return app<br><br>if __name__ == &#39;__main__&#39;:<br>    web.run_app(main())</pre><h3>WebSocket server</h3><p>This is an example of an asyncio-based WebSocket server that broadcasts messages to all connected clients. It uses the websockets library to handle WebSocket connections.</p><pre>import asyncio<br>import websockets<br><br>async def broadcast(websockets, message):<br>    for ws in websockets:<br>        await ws.send(message)<br><br>async def handler(websocket, path):<br>    async for message in websocket:<br>        await broadcast(websockets, message)<br><br>async def main(host, port):<br>    server = await websockets.serve(handler, host, port)<br>    await server.wait_closed()<br><br>if __name__ == &#39;__main__&#39;:<br>    asyncio.run(main(&#39;127.0.0.1&#39;, 8888))</pre><h3>WebSocket client</h3><p>This is an example of an asyncio-based WebSocket client that connects to a server, sends a message, and prints the response. It uses the websockets library to handle the WebSocket connection.</p><pre>import asyncio<br>import websockets<br><br>async def main():<br>    async with websockets.connect(&#39;ws://localhost:8888&#39;) as websocket:<br>        await websocket.send(&quot;Hello, world!&quot;)<br>        response = await websocket.recv()<br>        print(f&#39;Received: {response}&#39;)<br><br>asyncio.run(main())</pre><h3>Advanced Asyncio Concepts</h3><p>So far, we’ve only seen examples of how to run a single asynchronous function to perform non-blocking IO operations.</p><p>When we have many operations to run concurrently, we need to coordinate and manage those operations. Fortunately, the asyncio module has some functions that make it easier for us.</p><h3>How to use asyncio.gather() to wait for multiple async tasks</h3><pre>import asyncio<br><br>async def task_one():<br>    print(&quot;Starting task one&quot;)<br>    await asyncio.sleep(1)<br>    print(&quot;Finishing task one&quot;)<br>    return 1<br><br>async def task_two():<br>    print(&quot;Starting task two&quot;)<br>    await asyncio.sleep(2)<br>    print(&quot;Finishing task two&quot;)<br>    return 2<br><br>async def main():<br>    # This will wait for all the coroutines<br>    results = await asyncio.gather(task_one(), task_two())<br>    print(results)<br><br>asyncio.run(main())</pre><p>This code will produce the following output:</p><pre>Starting task one<br>Starting task two<br>Finishing task one<br>Finishing task two<br>[1, 2]</pre><p>As you can see, the tasks are run concurrently rather than sequentially. This can be useful for improving the performance of an application by allowing it to make better use of available CPU resources.</p><p>The <strong>asyncio.gather()</strong> method accepts many arguments and returns a list of the results returned by all the coroutines.</p><p>It is also common to create many coroutines beforehand and then gather them later. We can collect many coroutines together into a list either manually or using a list comprehension. We can then unpack this list as arguments to gather(). Note the use of the star operator (*) here:</p><pre># creates many coroutines<br>coros = [my_async_task(i) for i in range(10)]<br>...<br># then, run the tasks<br>results = await asyncio.gather(*coros)</pre><h3>How to use asyncio.wait() to manage multiple asynchronous tasks</h3><p>The <strong>asyncio.wait()</strong> function blocks and returns a tuple containing two sets of tasks: those that have completed and those that are still pending. In this example, we iterate over the completed tasks and print their results.</p><p>Using the asyncio.wait() function, you can easily manage multiple asynchronous tasks and perform actions when they have completed. This can be particularly useful for situations where you need to wait for multiple tasks to complete before moving on to the next step of your program and for setting timeouts for some tasks.</p><pre># Run these tasks and wait <br>tasks = [task_one(), task_two()]<br>    completed, pending = await asyncio.wait(tasks)<br><br>    results = [t.result() for t in completed]<br>    print(results)</pre><p>Alternatively, we could use the asyncio.as_completed() function to run concurrent tasks and iterate their results as they become available. This is possible because asyncio.as_completed() returns an iterable of the coroutines that can be awaited.</p><h3>Chaining multiple asynchronous tasks</h3><p>There are situations where you may need to perform a series of asynchronous tasks in a specific order. Since coroutines are awaitable, another coroutine can await it. You may use this class to chain async tasks since the asyncio library does not (yet) provide a similar function.</p><pre>class Chain:<br>    &quot;A class to execute async tasks sequentially&quot;<br>    def __init__(self, tasks):<br>        self.tasks = tasks<br><br>    async def __call__(self, *args, **kwargs):<br>        for task in self.tasks:<br>            args = await task(*args, **kwargs)<br>            args = (result,)<br>        return result</pre><p>To use this class, you can pass a list of asynchronous tasks to the constructor and then call the Chain instance to execute the tasks in the specified order. The result of each task is passed as an argument to the next task in the chain.</p><pre>chain = Chain([task_one, task_two])<br># block until tasks are performed synchronously<br>result = await chain() # returns the last task result</pre><h3>When to Use Asyncio</h3><p>Coroutines are an alternative to threading-based concurrency that is provided by the Python language and further supported by the asyncio module. They are suited to non-blocking IO with subprocesses and sockets. However, blocking IO and CPU-bound tasks can be used in a simulated non-blocking manner using threads and processes under the covers.</p><p>Any program written using threads or processes can be rewritten or instead written using coroutines if we so desire.</p><p>A coroutine is even more lightweight than a process. Processes, like threads, are created and managed by the underlying operating system and are represented by a <strong>multiprocessing.Process</strong> object.</p><p>This means that coroutines are significantly faster than a process to create and start and take up much less memory. A coroutine is just a special function, whereas a Process is an instance of the interpreter that has at least one thread.</p><p>As such, we may have thousands of threads in a Python program, but we could easily have tens or hundreds of thousands of coroutines all in one thread.</p><h3>When Not to Use Asyncio</h3><p>There are many misconceptions about Python concurrency and especially around asyncio. Using asyncio does not magically solve all the issues with Python.</p><p>For example:</p><ul><li>Asyncio works around the Global Interpreter Lock (GIL).</li><li>Asyncio is faster than using threads.</li><li>Asyncio avoids the need for locks and other synchronization methods.</li><li>Asyncio is easier to use than threads.</li></ul><p>These are all <strong>False</strong>.</p><p>Only a single coroutine can run at a time by design, and they cooperate to execute. This is just like threads under the GIL. However, the GIL still applies to asyncio code, and the performance of asyncio programs may be affected by the GIL in the same way as multithreaded programs. So asyncio is not faster and is also not multithreaded and not parallel.</p><p>Any program you can write with asyncio, you can also write with threads, and it could actually be as fast or even faster. It could also probably be simpler and easier to read and interpret by other developers.</p><p>If you need to bypass the GIL and take full advantage of multiple CPU cores in your Python program, you may want to consider using a different concurrency framework like <a href="https://www.hackerculture.xyz/running-processes-python-multiprocessing-guide/">multiprocessing</a> and other libraries such as concurrent.futures. These frameworks allow you to create multiple processes, each with its own Python interpreter and GIL, which can run in parallel on separate CPU cores.</p><p>Any concurrency pitfalls you might expect with threads, you can also encounter with coroutines. You must ensure coroutines are thread safe and safe from deadlocks and race conditions, just like with threads or processes.</p><p>Another reason not to use asyncio is that you may not like asynchronous programming. Even though asynchronous programming has been popular for some time now in various programming communities, it is different from procedural, object-oriented, and functional programming, and some developers just don&#39;t like it.</p><p>If you don’t like it, don’t use it. It’s a fair reason.</p><p>You can achieve concurrency in many ways other than using asynchronous programming, using threads or processes as needed.</p><p>You can learn all about threads and processes in our guides:</p><p><a href="https://www.hackerculture.xyz/running-processes-python-multiprocessing-guide/">Running Multiple Processes in Python — A Multiprocessing Guide</a></p><h3>Best Practices for Asynchronous Programming in Python</h3><p>These are some tips that will have you writing efficient and maintainable asynchronous code and save you lots of headaches:</p><h3>Use asyncio’s high-level APIs whenever possible</h3><p>The asyncio library provides several high-level APIs that make it easy to write concurrent code. For example, you can use the gather function to run multiple tasks concurrently or the as_completed function to iterate over a group of tasks as they complete. These APIs can help you write efficient and maintainable code, as they abstract away many of the low-level details of concurrent programming.</p><h3>Avoid blocking the event loop</h3><p>The event loop is the heart of asyncio, and it is responsible for scheduling and executing asynchronous tasks. If you block the event loop, you can cause performance issues and disrupt the execution of other tasks. To avoid blocking the event loop, use non-blocking IO operations whenever possible, and avoid using blocking functions such as time.sleep or threading.Lock.</p><h3>Use async context managers and async iterators</h3><p>Async context managers and async iterators can help you write asynchronous code that is easy to understand and maintain. For example, you can use async context managers to manage resources that need to be acquired and released asynchronously, or you can use async iterators to iterate over asynchronous data streams in a natural and intuitive way.</p><h3>Common pitfalls to avoid when doing asynchronous programming</h3><ol><li>Forgetting to await asynchronous tasks: When you await an asynchronous task, you are telling the event loop to execute that task and pause the current task until the awaited task completes. If you forget to await a task, it will be scheduled to run, but the event loop will not wait for it to complete before moving on to the next task. This can lead to unexpected behavior and race conditions.</li><li>Not using asynchronous functions when appropriate: On the other hand, it is important to use asynchronous functions when appropriate, as this can significantly improve the performance and scalability of your application. If you have long-running tasks or tasks that perform IO operations, consider using asynchronous functions to ensure that they do not block the event loop.</li><li>Not using synchronization techniques: Any concurrency pitfalls you might expect with threads, you can also encounter with coroutines. While only one coroutine can run within the event loop at one time, they can be suspended and resumed while using a shared variable. You must ensure coroutines are safe from deadlocks and race conditions, just like with threads or processes.</li></ol><p>If you keep these practices in mind and avoid the multiple pitfalls related to concurrency and asynchronous programming, you should be able to develop Python programs that can process many tasks concurrently.</p><p>You may even want to experiment with running asynchronous tasks combined with other concurrency techniques, especially when pairing asyncio with multiprocessing and <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor">concurrent.futures.Executor</a> instances.</p><h3>References</h3><ul><li><a href="https://docs.python.org/3/library/asyncio-eventloop.html">Event Loop</a></li><li><a href="https://docs.python.org/3/library/asyncio-task.html">Coroutines</a></li><li><a href="https://amzn.to/3Q47hh3">Using Asyncio in Python</a></li><li><a href="https://superfastpython.com/python-asyncio/">Python Asyncio The Complete Guide</a></li></ul><p><strong>How are you using asyncio in your programs?</strong><br>I’d love to hear about it. Please let me know in the comments.</p><p><strong>Do you have any questions?</strong><br>Leave your question in a comment below, and I’ll answer it with my best advice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf04402a4f53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackerculture/python-asyncio-a-guide-to-asynchronous-programming-cf04402a4f53">Python asyncio — A Guide to Asynchronous Programming</a> was originally published in <a href="https://medium.com/hackerculture">HackerCulture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I started the atomic-fns library]]></title>
            <link>https://medium.com/hackerculture/why-i-started-the-atomic-fns-library-cf6df8fb0342?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf6df8fb0342</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lodash]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Sat, 05 Nov 2022 15:00:34 GMT</pubDate>
            <atom:updated>2022-11-05T22:29:44.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wgbq5uf9cU4gVn0l" /></figure><p>Open source is more important than ever, and more companies are realizing the benefits and increasing their adoption. As long as it’s something popular that can speed up the development process, why not use it? It doesn’t cost anything!</p><p>Well, it doesn’t cost <em>money</em>… But I’ve found there are more subtle costs that could end up having a huge impact on the business, and we should consider them before introducing any dependencies to existing products or processes.</p><p>There’s the cost of distributing the libraries you’re using (and their dependencies) to your customers in your builds. That means your customers need to download a larger bundle, which makes their experience a bit slower.</p><p>There’s the maintenance cost of outdated libraries, which often include outdated dependencies. Those could have known vulnerabilities with known exploits (and fixes), which can damage the brand, business, and customers.</p><p>When a library is no longer maintained, it’s almost impossible to get support or request new features. The issues pile up on an endless list of open bugs. And those bugs are almost never fixed when you need them to be. You can count on Murphy’s Law to kick in here.</p><p>Then there’s the cost of the workarounds. Once you start uncovering bugs and you realize nobody is coming to save you, there are two possible outcomes: you either stop using that library, or you try to make it work on your own, taking on weeks of additional work.</p><p>On the other hand, there are specific characteristics that separate the quality open-source projects from their abandoned counterparts:</p><ul><li><strong>Bundle sizes.</strong> Good projects are modular, so you can import only what you need and keep your bundle sizes low. JavaScript libraries can be checked using <a href="https://bundlephobia.com/">bundlephobia.com</a> — also, look for libraries that are <a href="https://www.smashingmagazine.com/2021/05/tree-shaking-reference-guide/">tree-shakeable</a>.</li><li><strong>Source code.</strong> If you aren’t able to inspect the code, <em>don’t use it because it could explode</em>. But also, is the code clear? Are there comments? Could you explain how it works to others?</li><li><strong>Up to date.</strong> Look at the commit history. Are there recent commits and bug fixes landed? Are they keeping their dependencies up to date?</li><li><strong>Test coverage.</strong> If there are no tests, how do we know the code does what it’s supposed to do? Browse through the tests and make sure that they cover enough cases.</li><li><strong>Open issues.</strong> Check the project’s open issues to make sure the maintainers are active and listening. Check for a roadmap too.</li><li><strong>No vulnerabilities.</strong> Run npm audit after adding a new dependency to check that it doesn&#39;t introduce vulnerabilities. Bonus points if the library you plan to use has zero dependencies.</li><li><strong>Documentation.</strong> Can you find available docs that show how the library is meant to be used? Official or otherwise, having something you can refer to and share with other team members is super valuable.</li></ul><p>Recently, I’ve had to estimate these costs when deciding on which libraries to use for a new project and was considering using the popular lodash library. Until I started looking at their long list of <a href="https://github.com/lodash/lodash/issues">open bugs</a>, realizing this project has been dead for the past 6 years, and then I read their source code, ridden with custom macros and over-engineered abstractions (see <a href="https://github.com/lodash/lodash/blob/master/clone.js">clone</a>). And then it hit me...</p><p>This must be why there are so many open bugs. It takes so much effort to understand just one basic function that most people won’t even try. Hell, even the original maintainers probably can’t understand it at this point because of all the abstractions.</p><p>So I started working on a <a href="https://github.com/adrian2x/atomic-fns">similar library</a> to replace my lodash imports, and a handful of other libraries. But the main goal is that it should be easy to learn, easy to test, and easy to maintain. There are plenty of <a href="https://atomic-fns.dev/">docs</a> available to get you started, and I hope you join the conversation on <a href="https://github.com/adrian2x/atomic-fns">github</a> to help shape its future.</p><p><a href="https://github.com/adrian2x/atomic-fns">GitHub - adrian2x/atomic-fns: Like Lodash, but for ESNext and with types.</a></p><p><em>Originally published at </em><a href="https://hackerculture.xyz/introducing-atomic-fns-library/"><em>https://hackerculture.xyz</em></a><em> on November 5, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf6df8fb0342" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackerculture/why-i-started-the-atomic-fns-library-cf6df8fb0342">Why I started the atomic-fns library</a> was originally published in <a href="https://medium.com/hackerculture">HackerCulture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Gentle Introduction to Python Programming]]></title>
            <link>https://medium.com/@hackerculture/a-gentle-introduction-to-python-programming-9062c34e9134?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/9062c34e9134</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Wed, 05 Oct 2022 14:00:45 GMT</pubDate>
            <atom:updated>2023-01-30T18:33:49.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CnHxE1RyA7PRWV2s.jpg" /></figure><p><em>Originally published at </em><a href="https://www.hackerculture.com/intro-to-python/"><em>https://www.hackerculture.c</em>om</a><em> on October 5, 2022.</em></p><p>Programming offers a chance to develop creativity, reasoning, and problem-solving skills. As a programmer, you get to bring ideas to life through code and using logic to create programs that can be executed by a computer.</p><p>If you know how to write computer programs, you can do all sorts of useful things. You might not be able to write programs to control cars, traffic lights, or your fridge right away, but you could make web pages, your own games, or even a program to help you with your homework.</p><p>When faced with obstacles, programming requires you to use problem-solving to find solutions. While it can be challenging (and at times frustrating), programming is also a fun and rewarding activity! The skills gained from programming can be beneficial in multiple professions, even if your chosen career is not directly related to computers.</p><h3>How to Learn to Code</h3><p>Like anything you try for the first time, it’s always best to start with the basics. Gymnasts don’t usually do backflips on their first try. If you jump ahead too quickly, not only will the basic ideas not stick in your head, but you’ll also find the content of the later articles more complicated than it actually is.</p><p>Remember that the better you understand the basics, the easier it will be to understand more complicated ideas later on. When you find something frustrating or too challenging, here are some things that I find helpful:</p><ol><li>Break a problem down into smaller pieces. Try to understand what a small piece of code is doing or think about only a small part of a difficult idea (focus on a small piece of code rather than trying to understand the whole thing at once).</li><li>If that still doesn’t help, it might be best to leave it alone for a while. Sleep on it and come back to it another day. This is a good way to solve many problems, and it can be particularly helpful for computer programmers.</li></ol><h3>What is a Computer Program</h3><p>A <strong>program</strong> is a list of steps for a computer to follow. <em>Programs</em> are made up of lines of code. Each line tells the computer something specific about how to follow these instructions.</p><p><em>Software</em> is a collection of <em>computer programs</em>.</p><p>Programs are like thoughts. If you didn’t have thoughts, you would probably just sit on the couch all day, staring at the ceiling. Your thought “get up off the couch” is a command or instruction that tells your body to stand up. In the same way, computer programs use commands to tell computers what to do.</p><h3>The Python Programming Language</h3><p>Like humans, computers use multiple languages to communicate-these are called programming languages. A <em>programming language</em> is simply a way to talk to a computer by using instructions that both humans and computers can understand.</p><p>The Python programming language has many features that make it extremely useful for beginners. Most importantly, you can use Python to write simple, efficient programs quite quickly. Python doesn’t use as many complicated symbols as other programming languages, which makes it easier to read and a lot friendlier for beginners.</p><blockquote><em>The Python programming language was actually named after the </em>Monty Python’s Flying Circus<em> TV show, not after the snake.</em></blockquote><h3>Installing Python</h3><p>To install Python, navigate to <a href="https://www.python.org/downloads/">python.org/downloads</a> and click on <strong>Download Python</strong>. At the time of this writing, the latest version is 3.11.1. Make sure you download a version higher than 3.10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/0*EegbbYmfqjxQ5gvV.png" /></figure><p>Once downloaded, double-click the file to run the installer.</p><p>Make sure you select <strong>Add Python to PATH</strong>, and accept all the defaults as you click through the installer.</p><p>When the setup is complete, you will find your Python folder inside the <strong>Applications</strong> folder on your computer.</p><p>Now that you have Python installed, we can write our first program!</p><h4>For Windows</h4><p>Search for the <strong>Command</strong> application in the <strong>Start Menu</strong> or the Windows search box.</p><p>Enter python in all lowercase. You should see a message from Python like this:</p><pre>$ python Python 3.11.0 (main, Jan 9 2023, 15:58:34) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin<br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>&gt;&gt;&gt;</pre><p>Here, you can play around with the Python interpreter. Note the three greater-than signs (&gt;&gt;&gt;) are called the <em>prompt</em>. This means Python is waiting for our input.</p><h4>For Mac</h4><p>Python is already installed on most Macs, but it’s probably an outdated version and not the one you want.</p><p>To see which version of Python is installed, open the <strong>Terminal</strong> application from the <strong>Applications</strong> folder and enter python3. You should then see the Python version and prompt.</p><p><strong>Note:</strong> A <em>shell</em> window (or terminal) is a command-line interface on a computer where you can type commands to the operating system and receive text output in return.</p><p>Enter the following line into the prompt:</p><pre>print(&quot;Hello World&quot;)</pre><p>You should see the “Hello World” line printed out.</p><p>To close the terminal session, press <strong>Ctrl-Z</strong> and <strong>Enter</strong>, or type exit() and press <strong>Enter</strong>.</p><p>But wait a second… you may be thinking, “ <em>How is this useful?</em>”. That’s a totally fair question. Let’s look at a more realistic example.</p><p>Copy and paste the following code into your Python shell, and press <strong>Enter</strong>. Or try clicking the <strong>Run</strong> button in this sandbox:</p><p><a href="https://replit.com/@HackerCulture/datetimepy#main.py">datetime.py</a></p><p><strong>Note:</strong> In Python, the hash symbol (#) indicates a comment. Anything following a hash char in your code is ignored by Python; they are just there for human readers. You can use comments to write notes in plain English within your programs.</p><p>Comments can also be used to experiment with your code. If you want to temporarily “turn off” some code so that it doesn’t run but don’t want to delete it entirely, start the line with a #. This will convert the line into a comment, which Python will ignore when running the program.</p><p>Let’s take a look at the code starting with this line:</p><pre>from datetime import datetime</pre><p>This imports a module called datetime from <em>somewhere</em>, which we will use to display the current date and time. You probably have no idea where it&#39;s coming from, and that&#39;s completely okay.</p><p>The second line is a bit different:</p><pre>today = datetime.now()</pre><p>It kind of sounds like this line is saying: today is equal to a datetime now, maybe? Or more like today <em>is</em> datetime now.</p><p>That’s pretty much exactly what this line does:</p><ol><li>It creates a new <em>variable</em> name called “<strong>today</strong>”.</li><li>It assigns the result of datetime.now() to the variable today.</li></ol><p>Finally, this prints out the value of the variable today.</p><pre>print(today)</pre><p>Now, try to change the name today in the last line to something else, like now, and run the code again.</p><h3>What to do if you see an error</h3><p>You may see an error this time, and the output is just the Python interpreter telling us where the problem is.</p><pre>Traceback (most recent call last):<br>  File &quot;/var/shared-data/code/main.py&quot;, line 6, in &lt;module&gt;<br>    print(now)<br>          ^^^<br>NameError: name &#39;now&#39; is not defined. Did you mean: &#39;pow&#39;?</pre><p>A NameError happens when we either forget to set a variable&#39;s name before using it or we made a spelling error when entering the variable name.</p><p>The output also reports that this error happened in line 6 of the file <em>main.py</em>. This can help us spot the error quickly.</p><p>If we change both of these lines to use the same name “now”, the code works again. Try copying these lines into your shell now:</p><pre>now = datetime.now()<br>print(now)</pre><p>Many programming mistakes are simple typos of one character in one line of code. If you spend a long time trying to find one of these mistakes, you’re not alone. Many skilled and experienced programmers spend hours looking for these types of small mistakes. Try to laugh about it and move on, knowing that this will happen a lot as you learn to code.</p><h3>Variables and Operations</h3><p>Variables are a way of storing things in a program. They’re essentially a way to name a value, and they point to the given value in memory. Their value can later be retrieved and used in expressions.</p><p>To create a variable, we simply type the name on the left side of an equal sign (=). The right side must be an expression. This can be a primitive value or a more complicated expression.</p><p>For example, we can assign the result of a calculation to a variable:</p><pre>weeks = 52<br>days = 5 * 52<br>vacation = 5 * 2 + 4<br>workdays = days - vacation<br>workweeks = workdays / 7<br>print(workdays)</pre><p>To find the value of a variable, we can use print followed by the name of the variable in parentheses. Try copying the code above to your shell, and then press <strong>Enter</strong>.</p><p>We can also tell Python to change the variable so that it contains a new value and also use more than one name or variable for the same value:</p><pre>days = 7<br>week = days<br>print(week)</pre><p>Here we’re changing the value of the variable days to 7 and then, we&#39;re saying that we want the variable week to refer to the current value of the variable days.</p><p>However, week isn&#39;t a very useful name for a variable because it doesn&#39;t tell us much about what the variable is used for. Let&#39;s call our variable days_in_week instead.</p><pre>days_in_week = 7<br>print(days_in_week)</pre><p>This makes it clear that we’re talking about the number of days in a week. Variable names can be made up of letters, numbers, and underscores (_), but they can&#39;t start with a number.</p><p>You can use any lowercase letters for variable names, but the name cannot contain a space, so we use underscores to separate words.</p><p>You should not use uppercase letters in variable names because they have a special meaning that we’ll discuss another time. Python is a case-sensitive language, which means that today is not the same as Today.</p><h3>The order of operations</h3><p>You can do all the basic math operations in Python using the corresponding <em>operators,</em> as you saw in that example.</p><p>We use parentheses in programming languages to control the order of operations. An operation is anything that uses an operator. Multiplication and division have a higher order than addition and subtraction, so they’re performed first. In other words, if you enter an equation in Python, multiplication or division is performed before addition or subtraction.</p><p>For example, in this expression, the numbers 2 and 10 are multiplied first, and then the number 5 is added to the product:</p><pre>5 + 2 * 10</pre><p>The result is 25.</p><p>We can change the order of operations (and the result) by adding the parentheses around the numbers:</p><pre>(5 + 2) * 10</pre><p>The result of this expression is now 70 because the parentheses tell Python to add 5 to 2, and then multiply the result by 10.</p><p>Parentheses can be nested, which means that there can be parentheses inside parentheses, like this:</p><pre>((5 + 2) * 10) / 7</pre><p>In this case, Python evaluates the innermost parentheses first, then the outer ones, and then the final division. So it adds 5 to 2, then multiplies the result by 10, and then divides that by 7.</p><h3>Saving Your Python Programs</h3><p>As we saw, we can write Python code directly into the shell window… but Python programs wouldn’t be very useful if you needed to rewrite them every time you wanted to use them.</p><p>Sure, it might be fine for short programs, but a large program could have millions of lines of code!</p><p>Luckily, we can save our programs for future use.</p><p>To create and save a new program, enter <strong>idle</strong> in the Windows search box, and select <strong>IDLE (Python 3.11.1 64-bit)</strong>. In a Mac, open your <strong>Applications</strong> folder and open the <strong>Python 3.11</strong> folder to find IDLE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*cERbxmlxDrSFhL9d.png" /><figcaption>The IDLE python shell</figcaption></figure><p>IDLE (Integrated DeveLopment Environment) is a Python file editor which let you write programs in Python.</p><p>When you open IDLE, you will see the Python shell. Click <strong>File › New Window</strong>. An empty window will appear.</p><p>Paste the code from the previous example into the window, then click <strong>File </strong>▸<strong> Save</strong>. Enter hello.py as the file name, and save it to your desktop. Then, you can click <strong>Run › Run Module</strong> to run it.</p><p>An alternative to IDLE for Python is <strong>Pycharm</strong>, which is loved by many Python programmers. You can download the free community Pycharm from their <a href="https://www.jetbrains.com/pycharm/download/">website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8y72p_kxOOoXGQ5U.png" /><figcaption>Opening Pycharm shows a Tip of the Day message</figcaption></figure><p>We prefer using Pycharm because it provides a more user friendly environment. It really works like a charm! You can use it to create new programs and to run saved programs directly from within Pycharm.</p><h3>Run your Python program from the Terminal</h3><p>We can also run our program from the Terminal by taking these steps:</p><h4>For Windows</h4><ol><li>Open the <strong>Command Prompt</strong> from the <strong>Start Menu</strong> or Windows search.</li><li>Enter cd Desktop in the command window to change the directory to the folder containing our program.</li><li>Type python hello.py to run the program.</li></ol><h4>For Mac and Linux</h4><ol><li>Open the <strong>Terminal</strong> app from Applications.</li><li>Enter cd ~/Desktop in your terminal to change the directory to the folder containing the program.</li><li>Type python3 hello.py to run it.</li></ol><p>With some luck, you should see the result of your Python program printed out!</p><h3>Recap</h3><p>You just learned how to set up Python and how to start playing with it! Also:</p><ul><li>How to save your programs</li><li>How to create variables to name values</li><li>How to use parentheses to control the order of operations.</li></ul><p>Now would be a great time for a celebratory dance! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9062c34e9134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Python 3.11 and Virtualenvs with Pyenv]]></title>
            <link>https://medium.com/hackerculture/setting-up-python-3-11-and-virtualenvs-with-pyenv-47f480965e75?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/47f480965e75</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Sat, 15 May 2021 19:00:42 GMT</pubDate>
            <atom:updated>2023-01-09T22:50:56.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z11IYTufW6dJBkdX.png" /></figure><p>Python comes preinstalled in most operating systems by default. But sometimes, you may want to upgrade to a newer version of Python or a new version of a library that you depend on which is not compatible with your current version of Python.</p><p>If you upgrade your system version, you may introduce changes that are not backward compatible, and you may find yourself hours deep into the rabbit hole of upgrading your entire system.</p><p>What we should do instead is use a library like Pyenv for installing multiple versions of Python and switching between them as needed.</p><p>We’ll also see how virtual environments can help us isolate changes between projects and how to keep project dependencies pinned to a specific version of Python.</p><h3>Getting Started</h3><p>First, we will install all the python toolchain dependencies and build tools. Even though Ubuntu ships with python installed, we still need some other libraries to build and run python packages. This is the recommended list of dependencies for sane build environments, according to pyenv instructions.</p><pre>sudo apt install -y make build-essential build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev python-dev python3-dev python3-pip python3-virtualenv python3-venv git</pre><p>Once that finishes, you should have all the necessary libraries installed. Now for the python specific part.</p><h3>Pyenv</h3><p>The recommended way to manage your python dependencies and packages is to encapsulate your builds inside a python virtual environment. You might be wondering if you really need this, the answer (unless you want to spend most of your time in package versioning hell) is definitely yes.</p><p>We’ll use <strong>pyenv</strong> to manage python installations.</p><pre>git clone https://github.com/pyenv/pyenv.git ~/.pyenv</pre><p>Or you can brew install pyenv if you are using macOS.</p><p>We also need to add these lines to your <em>.bashrc</em> (or <em>.zshrc</em> if you use <strong>zshell</strong>)</p><pre>export PYENV_ROOT=&quot;$HOME/.pyenv&quot; export PATH=&quot;$PYENV_ROOT/bin:$PATH&quot; eval &quot;$(pyenv init -)&quot;&#39;</pre><p>Finally, you will need to reload your terminal session to apply the changes, or run source ~/.bashrc.</p><p>Now, let’s go ahead and make sure we have Python installed.</p><pre>python3 --version # Python 3.8.6</pre><p>So my current version is 3.8.5, but there are newer versions out there. We can install them using <strong>pyenv</strong> without messing with the default system version.</p><pre>pyenv install 3.11</pre><p>Once that’s done, we can list all the installed versions with:</p><pre>pyenv versions<br>* system (...)<br>2.7.18<br>3.8.13<br>3.11.0</pre><p>You should see some output like that, which tells me I have a system version, and others installed and available.</p><p>The reason why this matters is that some legacy python code needs to run with <em>python2</em> while newer code should be using <em>python3</em> versions. Also, when a new version of python comes out, you can try it in a new project by installing it with <strong>pyenv</strong> without having to worry about other legacy code not being able to run on the newer version.</p><h3>Python virtual environments</h3><p>Let’s introduce virtual environments by looking at a problem you might encounter. You start working on some project which uses some pip package, like pandas. Without knowing about virtualenvs, you just do what one does to install pandas like <em>pip install pandas,</em> and just continue your work.</p><p>All is good and well… except for the fact that now you installed a version of pandas in your system dependencies, which means some code you wrote months ago that depended on pandas too is now broken <strong>because pandas changed versions,</strong> and now it’s incompatible with your old code. That can be very messy.</p><p>What we really want is to make sure whatever version of pandas we build our project with <strong>never changes behind the scenes</strong>, so our code stays working even though pandas itself might change in the future. This is known as <strong>locking your dependencies</strong>, and that’s exactly what virtualenvs are for.</p><p>Let’s install virtual environments on top of <strong>pyenv</strong>.</p><pre>git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv</pre><pre>echo &#39;eval &quot;$(pyenv virtualenv-init -)&quot;&#39; &gt;&gt; ~/.profile</pre><p>Now I’ll show you how you can use virtual environments to isolate dependencies for a new project. I recommend creating a src directory in your root dir and putting all your projects in there. Like this:</p><pre>mkdir ~/src/new-project cd ~/src/new-project</pre><pre>pyenv virtualenv 3.11 venv</pre><p>This just creates a new virtualenv which will use python3.10-dev called venv. You can use any version of python installed by <strong>pyenv</strong> and any name you like, I just happen to use venv for consistency.</p><p>The last step is to actually activate the environment, so every command we run in this directory is isolated from the rest of our python installations.</p><pre>pyenv activate venv</pre><p>Now, you should see something like this</p><pre>(venv) user@epyc02:~/src/new-project$</pre><p>That first part in the path is telling us we are inside a virtual environment called venv.</p><p>BTW you can exit the virtual environment with pyenv deactivate, in case you want to switch between projects or install some packages outside your project.</p><h3>Wrapping up</h3><p>OK, now you are all set with python and you can install any dependencies in your project by running pip install &lt;package&gt;. This will save your packages inside of your venv directory and they will be local to your project. If you&#39;re using <strong>git</strong> it&#39;s recommended to ignore everything under your venv directory, so go ahead and add venv to your gitignore.</p><p><em>Note: if you called it something other than venv, substitute your environment’s name below instead of venv.</em></p><pre>echo &#39;venv&#39; &gt;&gt; .gitignore</pre><p>That way, if you deploy your code later or someone is pulling your code but has a different type of CPU when they install the packages, they will actually get the right build for their particular environment.</p><p>And that is all for our python environment setup. Go write some code!</p><p><em>Originally published at </em><a href="https://www.hackerculture.xyz/python-setup/"><em>https://www.hackerculture.xyz</em></a><em> .</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47f480965e75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackerculture/setting-up-python-3-11-and-virtualenvs-with-pyenv-47f480965e75">Setting Up Python 3.11 and Virtualenvs with Pyenv</a> was originally published in <a href="https://medium.com/hackerculture">HackerCulture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ES6+ Stack]]></title>
            <link>https://medium.com/@hackerculture/the-es6-stack-9837f3c296d7?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/9837f3c296d7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Wed, 05 Apr 2017 20:09:01 GMT</pubDate>
            <atom:updated>2017-04-06T16:01:16.880Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript is finally growing up. It’s now running on the web, powering e-commerce websites such as Walmart.com and PayPal, streaming platforms like Netflix, mobile apps, analytics &amp; realtime monitoring, and even IoT devices. It’s also being revised and updated every year starting in 2015 and it’s ranked #1 Top Technologies, according to a recent StackOverflow Developer Survey.</p><p>The goal of this guide is to get you familiar with the core pieces of the JavaScript ecosystem: nodejs and npm, and set up a modern stack to build web applications taking advantage of all the latest and greatest features available in ES6+. Caffeine is not required, but highly recommended.</p><h4>Install latest nodejs LTS</h4><p>Something to know about node… things are constantly changing and it’s a bit of a moving target. <a href="https://nodejs.org/en/foundation/">The guys behind it</a> need to catch up with the latest features and specs while also providing support for current and legacy systems. So there are 2 main flavors: <strong>LTS</strong> and <strong>current</strong>. <em>LTS</em> stands for Long Term Support while <em>current</em> are short-circuit releases that include all the latest features that have been finalized in-between LTS releases. The safe bet is to go with <strong>LTS</strong> but if you’re just exploring or working on a toy project the current release is fine.</p><p><a href="https://nodejs.org/en/download/">Get the nodejs installer for your platform here,</a> or if you’d rather use your favorite package manager, <a href="https://nodejs.org/en/download/package-manager/">check out their guide here</a>.</p><p>To check that node was installed correctly, run this on your terminal.</p><pre>$ node -v</pre><p>If everything is ok, you should see the version number that you have installed. Now, let’s move on to the cool part.</p><h4>The Node Package Manager (npm)</h4><p>Nodejs comes with a powerful sidekick: <a href="https://docs.npmjs.com/getting-started/what-is-npm">npm</a>. This little tool allows you to add functionality to your projects without having to write the code yourself via packages. A <strong>package</strong> is just a program that someone else wrote and shared to the <a href="https://www.npmjs.com/">npm registry</a>. You can add-on those packages and build your programs like you’re playing with lego blocks.</p><p>To get started on a project, create a new directory and navigate to it using the terminal. Then tell npm that you’re starting a new project:</p><pre>$ npm init</pre><p>You will be prompted for the name of your application, version, description, license and so on. Just hit Enter and leave the defaults for now until you get to</p><pre>Is this ok? (yes).</pre><p>Hit enter one more time. This will generate a brand new package.json file in your project directory. Think of this file as the entry point to your program.</p><p>Open up package.json in your favorite editor and in the scripts section, we’ll add a start command, which will be executed whenever you want to run or deploy your code. Here’s an example:</p><pre>{<br>  &quot;name&quot;: &quot;helloworld&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<strong>,</strong><br>    <strong>&quot;start&quot;: &quot;node index.js&quot;</strong><br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><p>Next up, create a new index.js file inside your project directory and add the following snippet:</p><pre>console.log(&#39;Hello, World!&#39;)</pre><p>To run your code, just enter npm start in the terminal, and you should see the <em>Hello, World</em> message! Feel free to change this example to do math or evaluate any other expression. Remember, <em>it’s just JavaScript</em>.</p><p>Awesome! You are now ready to start creating applications using node and npm! In the next episode we’ll go over how to install packages from npm and how to reuse your own code in different parts of your apps.</p><blockquote><em>Liked this? Let me know by hitting the ♡ below.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9837f3c296d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The glass is full!]]></title>
            <link>https://medium.com/@hackerculture/the-glass-is-full-2a35a252bcf?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a35a252bcf</guid>
            <category><![CDATA[wisdom]]></category>
            <category><![CDATA[tao-te-ching]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Tue, 28 Feb 2017 04:53:33 GMT</pubDate>
            <atom:updated>2017-02-28T04:53:33.964Z</atom:updated>
            <content:encoded><![CDATA[<p>The glass is 100 % full — half water, half oxygen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a35a252bcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Today is my brother’s birthday.]]></title>
            <link>https://medium.com/@hackerculture/today-is-my-brothers-birthday-2cbf4e19f866?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cbf4e19f866</guid>
            <category><![CDATA[positive-thinking]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[happiness]]></category>
            <category><![CDATA[wisdom]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Fri, 24 Feb 2017 00:04:00 GMT</pubDate>
            <atom:updated>2017-02-24T00:04:00.428Z</atom:updated>
            <content:encoded><![CDATA[<p>Today is my brother’s birthday. He is turning 15 years old, and naturally I asked what he wanted as a gift. More specifically, I asked him to think of something he wanted that cannot be bought with money. His response was “talent and respect… also health, happiness and knowledge”. I was not expecting that but as his brother, it is my duty to at least try to get him close to those things by sharing what I’ve learned from my humble perspective.</p><p>I believe that in the end, everything comes from happiness. Once you get there, the rest is rather easy because no matter what you will still be happy, right? So what is happiness then? How do you get there? Maybe we need to understand unhappiness first. It’s like a virus that everyone has. We’re all sick from it. We wake up in the morning and we’re not happy. We go to school or work and still not happy. We encounter others who are not happy. Sometimes, we even enjoy the company of those who are chronically unhappy. And so it goes around that way. It is found in all the things we want and don’t have, like a pendulum swinging from where we are to where we want to be. And so happiness is what we find when the pendulum stops. It’s not something that can be bought, given or taken, it’s something you must find for yourself because sometimes one man’s treasure is another man’s garbage. All that matters in the end is what makes you happy. That’s how you become your own cure and your own medicine. Like all other virtues, it’s not something you get, it’s something you become.</p><p>So start where you are, today, with what makes you happy. What better time than the present?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cbf4e19f866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trust Yourself Always]]></title>
            <link>https://medium.com/@hackerculture/trust-yourself-always-cb5ecd622dfe?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb5ecd622dfe</guid>
            <category><![CDATA[clarity]]></category>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[good-vibes]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[affirmations]]></category>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Tue, 20 Dec 2016 21:33:47 GMT</pubDate>
            <atom:updated>2016-12-20T21:33:47.438Z</atom:updated>
            <content:encoded><![CDATA[<p>Trust Yourself Always</p><p>You know.</p><p>All the answers are deep down there.</p><p>And all the mysteries and secrets.</p><p>You will know.</p><p>Like you know the sun is shining on you.</p><p>Seek inside, your heart is trying to tell you something.</p><p>You always knew.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb5ecd622dfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing better jQuery code]]></title>
            <link>https://medium.com/@hackerculture/10-tips-for-better-jquery-code-6cc958141c8a?source=rss-eab17725e227------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cc958141c8a</guid>
            <dc:creator><![CDATA[HackerCulture]]></dc:creator>
            <pubDate>Thu, 29 May 2014 21:45:05 GMT</pubDate>
            <atom:updated>2022-12-07T22:55:00.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tips and best practices patterns to avoid common pitfalls and start writing better jQuery code</h4><p>jQuery is a really useful and cool platform that allows for rich web application development with very little effort. That’s probably why it has become the popular kid in the block everybody wants to play with. It is also very accessible to developers with all levels of experience, which is fantastic in a way, but has also produced an impressive amount of code that sucks really bad all over the web.</p><p>In this post we’ll take a look at some simple yet important techniques that will make your jQuery code faster and better.</p><h3>Use jQuery the right way</h3><p>Installing jQuery is the first requirement to start using jQuery. But are you installing and distributing jQuery <em>the right way</em>?</p><p>Always install the latest version of jQuery unless you have a good reason not to. The latest version will always have bug fixes, new capabilities and enhanced performance. Include the jQuery script from the <a href="https://developers.google.com/speed/libraries/devguide#jquery">Google Developers website</a> but also distribute jQuery alongside your app just in case the file can’t be loaded from the web. You should always add the jQuery reference at the bottom of your body. This way the page loading will seem faster in the user eyes. Here is an example</p><pre>&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.9/jquery.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;window.jQuery || document.write(&#39;&lt;script src=&quot;js/jquery.1.9.min.js&quot;&gt;\x3C/script&gt;&#39;)&lt;/script&gt;<br>&lt;/body&gt;</pre><p>If you are adding your scripts right before the closing body tag, you don’t need to add a call to <em>document.ready()</em> because at this point, the DOM was already loaded. What you should be doing, however, is wrapping your jQuery script with a <em>self-invoking anonymous function</em>, and passing the jQuery object in as a parameter to the function. The benefit of this practice is that if in the future you add another framework that also uses <em>$</em> as a pointer to an object, your jQuery code will play nice with it.</p><pre>(function($) { <br> // write your code here<br>})(jQuery);</pre><p>Finally, always combine and minify your scripts to reduce download sizes and to increase loading speed. There are several tools out there for this, and if you’re doing server side development your platform will most likely have tools for doing this automatically.</p><h3>Optimize your selectors</h3><p>This is probably the most important thing to take care of when working with jQuery. Selections can be made in many ways, but not all of them offer the same performance advantages. In the worst case, whenever you select an object from the DOM, jQuery has to scan through all the elements in the objects tree and try to match what you’re searching for to the element that is being scanned. This can be really slow if you have a complicated DOM structure and a lot of operations.</p><p>In most of the cases we can achieve much better performance by optimizing the selector that we are going to use. As a rule of thumb, <em>id</em> is always better than <em>element</em>, and <em>element</em> is always better than <em>class</em>. <em>Pseudoclasses </em>and <em>Attributes </em>are not even welcome in selectors. Use them only if you have <strong>absolutely</strong> no choice. The reason for this is that <em>id</em> and <em>element</em> selectors are backed by native JavaScript operations whereas classes not so much.</p><p>Always try to construct your selectors in a left to right model. This is less specific in the left side, more specific in the right side. For example</p><pre>$(‘.navbar-nav li p’);</pre><p>This will target all the <em>p</em> tags inside <em>li</em> tags inside an element with the <em>navbar-nav</em> class.</p><h3>Give your selectors a context</h3><p>If you use a context for your selectors, the search space is reduced, making your selector much more efficient. For example, let’s say you have a <em>div</em> with an id of <em>main</em>, and you want to target all the <em>a</em> elements with a class of <em>active</em>. While you could just select the elements directly, this would make jQuery search for them in the entire DOM. If you select the <em>div</em> element using its <em>id</em> instead and then find the <em>a</em> elements descending from there, the selector becomes much more efficient.</p><pre>$(‘#main a.active’); // slow<br>$(‘#main’).find(‘a.active’); // fast</pre><h3>Always cache selected elements</h3><p>Caching means that we store the selected element in a variable for later use. This way we don’t need to search for it in the DOM again. When we chain methods, we are leveraging the cached object too, as well as improving code size and readability, so do as much caching and chaining as possible.</p><pre>$actives = $(‘a.active’).show().fadeOut(); // chaining methods<br>$actives.css(&#39;opacity&#39;, 0.5); // re-using the cached element</pre><h3>Use .find() and .children()</h3><p>We already saw how to use <em>.find()</em> when we have a context for our selector. Actually, there is more than one way of creating a context for your selector, but <em>find()</em> and <em>children()</em> are the fastest ones.</p><p>The difference between them is that <em>children()</em> will only look at the direct children of the specified element, and <em>find()</em> will look at the entire tree, including grandchildrens and so on.</p><p>Here is a <a href="http://jsperf.com/jquery-selectors-context/81">test</a> that compares the performance of the different options.</p><h3>Efficient DOM manipulation</h3><p>The DOM is not a database, and even though jQuery allows us to treat it as such, there’s a cost associated to it. Insertions and update operations are particularly more complicated than finding elements in the DOM, and can be very slow.</p><h4>Detach elements from the DOM</h4><p>One good approach for improving DOM manipulation is calling <em>.detach()</em> in the element being modified. This will temporary remove the element from the DOM while retaining its properties to allow you to reinsert it later.</p><h4>Efficient append operations</h4><p>If you are attaching lots of elements to the DOM, it’s better to create one single element containing all the attachements and then append that to the DOM in a single operation. Another operation to consider here is string concatenation, which is not very efficient. The most efficient way is to push all your elements to a temporary array, and then calling join on the array to create one single string containing all the elements, and finally appending that to the DOM in a single operation. Here is an example:</p><pre>var arr = reallyLongArray;<br>var temp = [];<br>var i = 0;<br>var length = arr.length;<br>for (var a = 0; a &lt; length; a++) {<br> temp[i++] = &#39;&lt;tr&gt;&lt;td name=&quot;pieTD&quot;&gt;&#39;;<br> temp[i++] = arr[a];<br> temp[i++] = &#39;&lt;/td&gt; &lt;/tr&gt;&#39; ;<br> <br>}<br>$(&#39;table&#39;).append(temp.join(&#39;&#39;));</pre><h3>Leverage Event Delegation</h3><p>Event delegation is a powerful concept that can make your events perform much better. Let’s say you have a table with 1000 <em>td</em> elements, and you want to add a click event to the <em>td</em> elements. You could do this:</p><pre>$(&#39;table&#39;).find(&#39;td&#39;).on(&#39;click&#39;, function(){<br> $(this).slideUp();<br>});</pre><p>The problem with this approach is that you are attaching 1000 event listeners to the DOM. There is a better solution using event delegation, which attaches the click to the table itself and then specifies the elements that should be bound to the event. Example:</p><pre>$(‘table’).on(‘click’, ‘td’, function(){<br> $(this).slideUp();<br>});</pre><p>There’s a <a href="http://jsperf.com/jquery-event-delegation">big difference</a> between these approaches.</p><h3>Use jQuery only if you need it</h3><p>Many developers tend to forget that jQuery <strong>is</strong> JavaScript. If you need the <em>id</em> value of an element, you can get it using plain ol’ JavaScript. Creating a jQuery object has an associated cost that you can avoid if you use vanilla JavaScript. The same goes for loops. You will be better off by using native JavaScript <em>for</em> loops than <em>$.each()</em> loops. The bottom line is native functions are always faster than their counterparts.</p><blockquote>With great power comes great responsibility — Uncle Ben</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cc958141c8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>