<?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 Denis Benevolo on Medium]]></title>
        <description><![CDATA[Stories by Denis Benevolo on Medium]]></description>
        <link>https://medium.com/@denisbenevolo?source=rss-afc4c7a81439------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NeGNykCIEUS41aFsG0Zb2g.jpeg</url>
            <title>Stories by Denis Benevolo on Medium</title>
            <link>https://medium.com/@denisbenevolo?source=rss-afc4c7a81439------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:40:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@denisbenevolo/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[Asynchronous Programming With Kotlin Coroutines]]></title>
            <link>https://medium.com/@denisbenevolo/asynchronous-programming-with-kotlin-coroutines-6216e3686f95?source=rss-afc4c7a81439------2</link>
            <guid isPermaLink="false">https://medium.com/p/6216e3686f95</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Denis Benevolo]]></dc:creator>
            <pubDate>Fri, 03 May 2024 01:03:18 GMT</pubDate>
            <atom:updated>2024-05-03T12:04:33.730Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re in an era where asynchronous concurrency reigns supreme. Today’s front-end and mobile applications offer real-time feedback and communication. Meanwhile, server-side applications and services manage thousands of online users seamlessly, integrating dozens of micro-services. Learning about the asynchronous world is a demanding need for developers.</p><p>In this article, you will find:</p><ol><li>A quick reminder about processes and threads</li></ol><p>2. What are kotlin coroutines?</p><p>3. Why choose coroutines for asynchronous programming?</p><p>4. Kotlinx coroutines library</p><p>5. Coroutine cancelation and timeouts</p><p>6. Coroutines channel</p><p>7. Coroutines exception handling</p><p>8. Structured concurrency</p><h3>A quick reminder about processes and threads</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hafK5Hmg0SNAadh2xt5Uog.jpeg" /><figcaption>Process and Threads</figcaption></figure><p>Firstly, to better understand the problem that a coroutine aims to solve, let&#39;s refresh our minds with the concepts of a program, process, and thread. A <strong>program</strong> is an executable file. It contains the code, or a set of processor instructions, that is stored as a file on disk. When the code in a program is loaded into memory and executed by the processor, it becomes a <strong>process</strong>. <strong>Thread</strong> is the segment of a process which means a process can have multiple threads and these multiple threads are contained within a process. The operating system is responsible for the switching and scheduling between threads, memory resources can be shared between them, but processes don’t.</p><h3>What are kotlin coroutines?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*JIH3eDh0nvm3fN26BbwCLg.jpeg" /></figure><p>Kotlin coroutines is a feature to address asynchronous or non-blocking programming development. Kotlin coroutines is not operating-system-level concept. — Kotlin coroutines is user-level concept, kernel know nothing about coroutines. — Kotlin coroutines are <a href="https://www.geeksforgeeks.org/preemptive-and-non-preemptive-scheduling/">non- preemptive</a>, so it’s more efficient. Thousands of coroutines can run on only one thread.</p><p>The functionality that coroutines provide is the ability to <strong>suspend</strong> a piece of code at some point and resume it in the future without blocking the thread. This capacity is called suspension and if you want to know under the hoods how coroutines work <a href="https://www.youtube.com/watch?v=IQf-vtIC-Uc">check here</a>.</p><h3>Why choose coroutines for asynchronous programming?</h3><p>As developers, one of our greatest challenges is to keep our applications responsive and efficient, especially when dealing with asynchronous operations. Over the years, various approaches have emerged to tackle this issue, each with its strengths and limitations:</p><p><strong><em>Callbacks</em></strong><em>: Traditionally, callbacks have been used to handle asynchronous tasks. While effective in certain scenarios, they often lead to callback hell and make code hard to read and maintain[1].</em></p><p><strong><em>Futures, Promises, and Others</em></strong><em>: These constructs provide a more structured way to manage asynchronous operations, but they still suffer from readability issues and can become complex to handle in large-scale applications[1].</em></p><p><strong><em>Reactive Extensions</em></strong><em>: Popularized by frameworks like RxJava, Reactive Extensions offer powerful tools for handling asynchronous events in a reactive and composable manner. However, they come with a steep learning curve and may introduce unnecessary complexity for simpler use cases[1].</em></p><p><strong>Enter Coroutines: A Modern Solution</strong></p><p>Kotlin coroutines offer a fresh approach to asynchronous programming, combining the best aspects of concurrency management with the simplicity of sequential code. Here’s why they’re gaining traction among developers:</p><p><strong><em>Lightweight</em></strong><em>: Coroutines are designed to be lightweight, allowing multiple asynchronous tasks to run concurrently on the same thread without blocking it. This makes them ideal for scenarios where resource efficiency is crucial.</em></p><p><strong><em>Cancellation Support</em></strong><em>: With coroutines, it’s easy to cancel a running task, preventing unnecessary resource consumption and ensuring responsive behavior[1].</em></p><p><strong><em>Efficient Memory Management</em></strong><em>: By leveraging coroutine scopes, developers can efficiently manage memory and ensure that resources are released when they’re no longer needed. This helps prevent memory leaks and keeps applications running smoothly[1].</em></p><p><strong><em>Seamless Jetpack Integration</em></strong><em>: Kotlin Coroutines seamlessly integrate with various Jetpack libraries[1].</em></p><p><strong>Simplifying asynchronous concurrency</strong></p><p>While the technical advantages of kotlin coroutines are significant, perhaps their most compelling feature is their ability to simplify asynchronous concurrency programming. By allowing developers to write asynchronous code in a sequential manner, coroutines make complex tasks more manageable and reduce the risk of errors associated with traditional concurrency models.</p><p>In conclusion, Kotlin coroutines offer a modern, efficient, and developer-friendly solution to asynchronous programming challenges. By embracing coroutines, developers can build more responsive, maintainable, and scalable applications, without sacrificing readability or performance.</p><h3>Kotlinx coroutines library</h3><h3>Coroutine builders</h3><p>So, what exactly are coroutine builders? Let’s say that they are a connection between the suspending and non-suspending parts of our code. Since they are not suspended, they can be easily called from other non-suspending pieces of code. So let’s explore the three most essential coroutine builders.</p><h4>launch</h4><p>Using launch we start a new coroutine without blocking the current thread which can be seen in the example below.</p><p><strong>launch example:</strong></p><pre>fun main() {<br>    println(&quot;Start&quot;)<br>    scope.launch {<br>        delay(3000)<br>        println(&quot;Hello World!&quot;)<br>    }<br>    println(&quot;End&quot;)<br>    Thread.sleep(5000L)<br>}</pre><p>The launch function is an extension function on the CoroutineScope interface.</p><p>Another thing to notice here is that we need to call Thread.sleep at the end of the function. Without this line of code, the coroutine would end immediately after it was launched, and “Hello World!” wouldn’t be printed. This is because the delay function doesn’t block the thread; it suspends it.</p><h4>runBlocking</h4><p>The core functionality of coroutines is that they don’t block threads, only suspend them. There are cases, however, where blocking the thread can be useful. In the launch builder example, we needed to use the Thread.sleep function so the program wouldn’t end too soon.</p><p>Now let’s see how we can achieve the same behavior using runBlocking.</p><p><strong>runBlocking example:</strong></p><pre>fun main() {<br>    println(&quot;Start&quot;)<br>    runBlocking {<br>        delay(3000)<br>        println(&quot;Hello World!&quot;)<br>    }<br>    println(&quot;End&quot;)<br>}</pre><h4>async</h4><p>The async builder works very similarly to launch, but it produces a value. It’s often used to perform asynchronous tasks, such as obtaining data from two different places. It returns an object of type <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/">Deferred</a>&lt;T&gt;, where T is the type of the produced data.</p><p><strong>async example:</strong></p><pre>suspend fun getBooksFromStore1(): List&lt;String&gt;{<br>    delay(800)<br>    return listOf(&quot;Sapiens: A Brief History of Humankind&quot;, &quot;Muito Além do Nosso Eu&quot;)<br>}<br>suspend fun getBooksFromStore2(): List&lt;String&gt; {<br>    delay(700)<br>    return listOf(&quot;The Bible&quot;, &quot;The Prince&quot;)<br>}<br><br>fun main() = runBlocking {<br>    val booksFromStore1 = scope.async { getBooksFromStore1() }<br>    val booksFromStore2 = scope.async { getBooksFromStore2() }<br>    val books = booksFromStore1.await() + booksFromStore2.await()<br>    println(&quot;Books from Store 1 and Store 2 $books&quot;)<br>}</pre><p>Here we can see a much more practical example of the async builder. We are simulating a fetch of the books from two API calls. Then we parallelized two tasks instead of calling them one after another. After that, we created a list of books from 2 stores, which will hold the retrieved data, using the await function.</p><p>We used runBlocking to keep the program running until the fetching process was completed.</p><h3>Coroutine scope</h3><p>The coroutine scope is responsible for the structure and parent-child relationships between different coroutines. New coroutines usually need to be started inside a scope.</p><h3>Coroutine context</h3><p>The coroutine context is part of the core of every coroutine. Every coroutine we start is tied to a specific coroutine context. The context is defined inside the scope in which we start our coroutines.</p><p>CoroutineContext is defined as an interface.</p><p>If you open <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/">the documentation</a> of the interface you can see that the context is defined as an indexed set of Element instances, so the coroutine context consists of several context elements.</p><p>The most important elements are: CoroutineDispatcher, Job, CoroutineName and the ErrorHandler which we will explore below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRYADXOpv34VRtKcX1EkmA.jpeg" /><figcaption>Context elements.</figcaption></figure><h3>Job</h3><p>A job represents a cancelable thing with a lifecycle. The lifecycle is represented by its state. Here on the graph, you can see the states and the transitions between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8ekF57Wj-lg2EmqHptdgw.jpeg" /><figcaption>Job States</figcaption></figure><p>When the job is in the “active” state, it’s performing its job. In this state, child coroutines can be started. Most coroutines will start in the “active” state; only those that are started lazily will start in the “new” state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHNtEqz8GUDh08AT1liBqQ.png" /></figure><p>When a coroutine is executing its body, it’s in the “active” state.</p><p>After it’s done, its state changes to “completing,” where it waits for its children. After all its children are done, the state of the job changes to “completed.”</p><p>On the other hand, if a job cancels while running, its state changes to “canceling,” and after that to the “canceled” state.</p><p>Here you can see some examples that represent jobs in different states.</p><p>The first example shows how to create a job using a factory function Job( ). By default it is in the “active” state until we call job.complete( ) to complete it, and now the state changes to “completed”.</p><p>The example below shows a job launch that started lazily. As mentioned above, lazily started jobs are in the “new” state. Using the start( ) function, we change its state to “active.”</p><p>And lastly, we use <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/join.html">join( )</a> to await coroutine completion.</p><p><strong>lazily started job example:</strong></p><pre>suspend fun main() = coroutineScope {<br>    val lazyJob = launch(start = CoroutineStart.LAZY) {<br>        delay(2500)<br>    }<br>    println(lazyJob)<br>    lazyJob.start()<br>    println(lazyJob)<br>    lazyJob.join()<br>    println(lazyJob)<br>}</pre><h3>Cancelation</h3><p>After finishing some work, we should always clean our workspace. Put the tools away, clean off the dust, and so on.</p><p>The same rule applies to using coroutines. We need to make sure that we control the life cycle of the coroutine and cancel it when it’s no longer in use, because it can waste resources.</p><p>The previously mentioned Job interface has a cancel function, which allows its cancellation. When a job is canceled, its state changes to “canceling,” and at the first suspension point, a CancelationException is thrown.</p><pre>suspend fun main() = coroutineScope {<br>    val job = Job()<br>    launch(job) {<br>        for (number in 1..10) {<br>            delay(200)<br>            println(&quot;Current number: $number&quot;)<br>        }<br>    }<br>    delay(2500)<br>    job.cancelAndJoin()<br>    if (job.isCancelled){<br>        println(&quot;Job canceled.&quot;)<br>    } else {<br>        println(&quot;Job is still running...&quot;)<br>    }<br>}</pre><p>Once a Job is canceled it can’t be used as a parent for any new coroutines.</p><p>Here we can see a simple example of how it’s possible to cancel a job.</p><p>First, we create a job instance using the Job( ) factory function. We pass it as the coroutineContext element to the launch builder in which we simulate a process of printing numbers that lasts for 2000 milliseconds.</p><p>Below the launch builder we delay the job cancelation for 2500 milliseconds because we want to print all the numbers and only then cancel the job.</p><p>If we used a shorter time interval for the delay of canceling the job, it would be canceled before all the numbers were printed. For the cancelation, we use the cancelAndJoin( ) function.</p><p>It’s practical because it combines two functionalities at once, the cancel function and the join function which we use to wait for the cancelation to finish before we can proceed.</p><p>In the end, we simply check if the job was successfully canceled using the isCanceled function.</p><p>For more information about cancellation, you can check the official <a href="https://kotlinlang.org/docs/cancellation-and-timeouts.html">Kotlin guides</a>.</p><h3>Coroutine Channel</h3><p>Think of a coroutine channel as a communication pipeline where one coroutine can send data and another coroutine can receive it. It’s like passing messages between two parties in a smooth and asynchronous manner. Channels provide a way for coroutines to exchange information without blocking each other.</p><pre>import kotlinx.coroutines.channels.Channel<br>import kotlinx.coroutines.launch<br>import kotlinx.coroutines.runBlocking<br><br>fun main() = runBlocking {<br>    val channel = Channel&lt;Int&gt;()<br><br>    launch {<br>        for (i in 1..5) {<br>            channel.send(i)<br>        }<br>        channel.close()  // Don&#39;t forget to close the channel when done<br>    }<br><br>    launch {<br>        for (received in channel) {<br>            println(&quot;Received: $received&quot;)<br>        }<br>    }<br>}</pre><p>In this example, we create a channel of integers (Channel&lt;Int&gt;()). One coroutine sends numbers 1 to 5 to the channel, and another coroutine receives and prints them. The channel.close() is essential to signal that no more elements will be sent.</p><h3>Exception handling</h3><p>Errors, or rather accidents, happen every day in our lives, and the same happens in apps too. Even the most tested systems have bugs and unwanted behaviors.</p><p>If an uncaught exception slips by the program brakes, the same happens to the coroutine. So it is very important to have a good exception handling mechanism to catch them all.</p><p>The two most popular ways to handle coroutine exceptions are by using try-catch and the CoroutineExceptionHandler.</p><pre>fun main(): Unit = runBlocking {<br>    val scope = CoroutineScope(Job())<br>    scope.launch {<br>        try {<br>            throw RuntimeException()<br>        } catch (exc: Exception) {<br>            println(&quot;Caught: $exc&quot;)<br>        }<br>    }<br>}</pre><p>Here is a simple example of using the try-catch block to catch an exception.</p><p>If a coroutine doesn’t catch an exception, it doesn’t really throw the exception in the traditional way as, for instance, a regular function would.</p><p>Instead, it uses another exception-handling mechanism for propagating the exception up the hierarchy. Here we won’t go deep into structured concurrency and job hierarchy because it would be too much for this article, but you can check out more details about it <a href="https://www.thedevtavern.com/blog/posts/structured-concurrency-explained/">here</a>.</p><p>However, how can uncaught exceptions from failing coroutines be handled at the top of the hierarchy?</p><p>Well, we can handle them by using a CoroutineExceptionHandler. In the example below, the exceptionHandler is defined as a read-only variable that gets the coroutine context of the failed coroutine and the propagated exception as the input parameters.</p><p>After the creation of the exceptionHandler it can be passed as a context element to the launch builder.</p><pre><br>fun main(): Unit = runBlocking {<br>    val exceptionHandler = CoroutineExceptionHandler { ctx, exception -&gt;<br>        println(&quot;Caught $exception using CoroutineExceptionHandler&quot;)<br>    }<br>    val scope = CoroutineScope(Job() + exceptionHandler)<br>    scope.launch {<br>        throw RuntimeException()<br>    }<br>    delay(1000)<br>}</pre><h3>Structured Concurrency</h3><p>At its core, structured concurrency is a programming paradigm that emphasizes the organized and controlled execution of concurrent tasks. In the context of kotlin coroutines, it provides a structured way to launch and manage concurrent tasks within a specific scope.</p><ul><li>The scope is generally responsible for child coroutines, and their lifetime is attached to the lifetime of the scope.</li><li>The scope can automatically cancel child coroutines if something goes wrong or if a user simply changes their mind and decides to revoke the operation.</li><li>The scope automatically waits for completion of all the child coroutines. Therefore, if the scope corresponds to a coroutine, then the parent coroutine does not complete until all the coroutines launched in its scope are complete”</li></ul><p>Structured concurrency guarantees that when a suspend function returns, all of its work is done. Structured concurrency guarantees that when a coroutine errors, its caller or scope is notified.</p><ol><li>When a <strong>scope</strong> <strong>cancels</strong>, all of its <strong>coroutines</strong> <strong>cancel</strong>.</li><li>When a <strong>suspend fun</strong> <strong>returns</strong>, all of its <strong>work is done</strong>.</li><li>When a <strong>coroutine</strong> <strong>errors</strong>, its <strong>caller or scope is notified</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHm6t0Qsm5c73ivgt9qiKw.jpeg" /><figcaption>Structured concurrency</figcaption></figure><p><strong>References</strong></p><p>[1] <a href="https://kotlinlang.org/docs/coroutines-overview.html">https://kotlinlang.org/docs/coroutines-overview.html</a><a href="https://gist.github.com/chaxiu/d87870528bbfe3e9d7e481e1f6acace1"><br>[2] https://gist.github.com/chaxiu/d87870528bbfe3e9d7e481e1f6acace1</a><br>[3] <a href="https://github.com/Kotlin/coroutines-examples/tree/master/examples">https://github.com/Kotlin/coroutines-examples/tree/master/examples</a><br>[4] <a href="https://www.youtube.com/watch?v=_hfBv0a09Jc">https://www.youtube.com/watch?v=_hfBv0a09Jc</a><br>[5] <a href="https://www.youtube.com/watch?v=IQf-vtIC-Uc">https://www.youtube.com/watch?v=IQf-vtIC-Uc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6216e3686f95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Becoming a Proficient Programmatic Software Engineer]]></title>
            <link>https://medium.com/@denisbenevolo/becoming-a-proficient-programmatic-software-engineer-f506f0de6088?source=rss-afc4c7a81439------2</link>
            <guid isPermaLink="false">https://medium.com/p/f506f0de6088</guid>
            <dc:creator><![CDATA[Denis Benevolo]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 11:55:01 GMT</pubDate>
            <atom:updated>2024-04-25T11:55:01.396Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer: This article is a culmination of insights gathered from three influential books — “The Pragmatic Programmer,” “Pragmatic Thinking and Learning,” and “Cracking the Code Interview.” Its purpose is to provide guidance for aspiring engineers, fostering improvement, and adding value to projects through practical exercises and knowledge.</em></p><h3>What to Expect in This Article?</h3><ul><li>Identification of essential skills for Software Engineers.</li><li>A method for measuring skill expertise.</li><li>Tips and techniques to enhance learning skills.</li></ul><h3>Essential Skills for Software Engineers</h3><p>Determining the necessary skills for a Software Engineer depends on the context, varying between companies and endeavors. To provide a broad perspective, we reference major tech companies like Google, Amazon, Apple, and Microsoft. The following criteria, adapted from “Cracking the Coding Interview” by Gayle Laakmann McDowell, offer a comprehensive view:</p><p>Technical Skills</p><ul><li>Coding proficiency: Crafting clean, well-organized, and error-conscious code.</li><li>Computer Science fundamentals: A strong foundation in relevant technologies.</li><li>Experience: Demonstrating sound technical decisions, building challenging projects, and showcasing drive and initiative.</li></ul><p>General Skills</p><ul><li>Analytical skills: Independent problem-solving with optimal solutions.</li><li>Decision Making: Ability to make informed and reasoned decisions.</li><li>Communication skills: Clear technical communication and collaborative teamwork.</li><li>Experience in Agile Project and Methodology: Leadership or active participation in software development projects using agile practices.</li></ul><h3>Measuring Skill Expertise with the Dreyfus Model</h3><p>The Dreyfus model of skill acquisition initially applied to fields like chess and music, now extends to software engineering. It encompasses five stages:</p><p><strong><em>Novice </em></strong><em>-&gt; Limited experience, rigid adherence to rules.</em></p><p><strong><em>Advanced Beginner </em></strong><em>-&gt; Recognizes recurring situations, forms a mental model.</em></p><p><strong><em>Competent -</em></strong><em>&gt; Gained more experience, understands overall goals.</em></p><p><strong><em>Proficient </em></strong><em>-&gt; High expertise, intuitive grasp, adapts to scenarios.</em></p><p><strong><em>Expert </em></strong><em>-&gt; Mastery, high-level performance without conscious thought.</em></p><h3>Assessing Software Engineers at Different Stages</h3><p><strong>Novice:</strong></p><ul><li>Follows explicit instructions and coding guidelines.</li><li>Requires guidance for basic problem-solving.</li><li>Limited understanding of broader system architecture.</li></ul><p><em>Assessment Techniques:</em></p><ul><li>Evaluate adherence to coding standards.</li><li>Assess performance in simple coding exercises.</li><li>Review understanding of fundamental software engineering concepts.</li></ul><p><strong>Advanced Beginner:</strong></p><ul><li>Recognizes recurring patterns in coding tasks.</li><li>Forms a mental model of the software system.</li><li>Comfortable with basic coding tasks but may need guidance on complex issues.</li></ul><p><em>Assessment Techniques:</em></p><ul><li>Evaluate adaptability to new challenges.</li><li>Assess understanding of software system components.</li><li>Review performance in slightly more complex coding exercises.</li></ul><p><strong>Competent:</strong></p><ul><li>Understands overall project goals and contributes.</li><li>Relies on intuition and explicit rules.</li><li>Capable of troubleshooting and solving complex problems independently.</li></ul><p><em>Assessment Techniques:</em></p><ul><li>Evaluate role in team projects and impact.</li><li>Assess ability to address complex issues in the codebase.</li><li>Review collaboration and communication skills within the development team.</li></ul><p><strong>Proficient:</strong></p><ul><li>Intuitive grasp of software system situations.</li><li>Develops a personal coding style.</li><li>Demonstrates leadership in software development aspects.</li></ul><p><em>Assessment Techniques:</em></p><ul><li>Evaluate involvement in architectural decisions.</li><li>Review code quality and adherence to best practices.</li><li>Assess ability to mentor and support less experienced team members.</li></ul><p><strong>Expert:</strong></p><ul><li>Mastery of software engineering principles and practices.</li><li>Innovates and contributes significantly to the field.</li><li>High-level problem-solving without conscious thought.</li></ul><p><em>Assessment Techniques:</em></p><ul><li>Evaluate involvement in pioneering projects.</li><li>Review thought leadership contributions.</li><li>Assess impact on the organization’s technical strategy.</li></ul><h3>Tips for Skill Growth at Each Stage</h3><p><strong>For a Novice:</strong></p><ol><li>Follow Explicit Instructions: Begin with step-by-step instructions.</li><li>Build a Strong Foundation: Focus on fundamental concepts.</li><li>Practice Regularly: Engage in regular coding exercises.</li><li>Seek Feedback: Welcome feedback for improvement.</li><li>Understand Error Messages: Learn to interpret error messages.</li><li>Collaborate with Others: Participate in coding communities.</li></ol><p><strong>For an Advanced Beginner:</strong></p><ol><li>Expand Project Complexity: Take on slightly more complex projects.</li><li>Practice Real-World Application: Apply skills to real-world scenarios.</li><li>Explore Frameworks and Libraries: Familiarize with popular tools.</li><li>Continue Learning: Explore advanced concepts.</li><li>Participate in Collaborative Projects: Join open-source projects.</li><li>Refine Problem-Solving: Focus on refining skills.</li></ol><p><strong>For a Competent Software Engineer:</strong></p><ol><li>Understand the Big Picture: Focus on project goals.</li><li>Develop Intuition: Rely on intuition and experience.</li><li>Mentor Others: Share knowledge and mentor less experienced team members.</li><li>Optimize Code Efficiency: Pay attention to code optimization.</li><li>Adapt to New Technologies: Stay updated on new technologies.</li><li>Take Ownership of Projects: Demonstrate leadership in coding tasks.</li><li>Collaborate Effectively: Facilitate communication within the team.</li></ol><p><strong>For a Proficient Software Engineer:</strong></p><ol><li>Innovate and Contribute: Actively seek opportunities to innovate.</li><li>Mentorship and Leadership: Serve as a mentor and provide leadership.</li><li>Architectural Design: Take a leading role in architectural decisions.</li><li>Mastering Multiple Technologies: Master various programming languages.</li><li>Thorough Code Reviews: Conduct thorough code reviews.</li><li>Deep Understanding of Systems: Develop a deep understanding of the entire software system.</li><li>Automate and Optimize Processes: Identify opportunities to automate and optimize tasks.</li><li>Collaborate Across Teams: Collaborate seamlessly across different teams.</li><li>Risk Assessment: Evaluate and mitigate risks associated with code changes.</li><li>Lead Technical Discussions: Lead technical discussions within the team and with stakeholders.</li><li>Research and Development: Engage in research and development activities.</li><li>Continuous Learning and Teaching: Continue learning and actively participate in teaching and sharing knowledge.</li></ol><p><strong>For an Expert Software Engineer:</strong></p><ol><li>Innovate and Pioneer: Act as an innovator and pioneer in the coding domain.</li><li>Thought Leadership: Establish thought leadership within the coding community.</li><li>Mentorship and Teaching: Serve as a mentor and actively engage in teaching.</li><li>Architectural Vision: Shape the architectural vision of complex systems.</li><li>Expert in Multiple Domains: Demonstrate expertise in multiple coding domains.</li><li>Problem-Solving Beyond Coding: Apply problem-solving skills beyond coding.</li><li>Contribute to Open Source and Community: Contribute significantly to open-source projects and the coding community.</li><li>Anticipate Future Trends: Anticipate and contribute to future industry trends.</li><li>Drive Technical Excellence: Drive technical excellence across the organization.</li><li>Problem Solving at Scale: Solve complex problems at scale.</li><li>Navigate Ambiguity: Navigate through ambiguity and provide clarity.</li><li>Continuous Learning and Adaptation: Embrace continuous learning and adaptation.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f506f0de6088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Carta para o Eu do Futuro]]></title>
            <link>https://medium.com/@denisbenevolo/carta-para-o-eu-do-futuro-1e65ca6230fd?source=rss-afc4c7a81439------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e65ca6230fd</guid>
            <dc:creator><![CDATA[Denis Benevolo]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 13:49:57 GMT</pubDate>
            <atom:updated>2023-07-11T11:00:20.013Z</atom:updated>
            <content:encoded><![CDATA[<p>É meu camarada mais um ano, o que isso significa? <strong>Fisiologicamente com a sua idade atual</strong>, significa que a sua máquina atingiu a maturidade completa e que daqui em diante ela precisará de mais cuidados, investimento e atenção. Excessos, não serão absorvidos sem causar grande impacto. <strong>Profissionalmente, </strong>significa que você deu uma volta completa na crescente espiral. Se esforçou, se comprometeu, exercitou sua ética, honestidade, responsabilidade e certamente adicionou um décimo de produtividade nas suas entregas. Você começa a perceber que a excelência de si mesmo é a recompensa intrínseca de maior valor neste processo. E em se tratando de espiral está pronto para começar tudo de novo mas em um nível de expertise e maturidade mais elevado. <strong>Pessoalmente,</strong> significa que você começa a entender que a vida é feita de cada momento, os difíceis, os fáceis, os prazerosos e os não prazerosos. E não podemos simplesmente, editar nosso filme pessoal somente com momentos prazerosos ou fáceis. <strong>Acredito que toda adversidade traz consigo a semente de uma vantagem equivalente</strong>. Mas sem dúvidas os momentos vividos com alegria e felicidade ao lado de pessoas que amamos tem um valor super especial.</p><p>Pontos que na minha humilde opinião precisam ser observados ao longo da jornada:</p><p>0 — Tenha bem claro, se possível escrito, suas definições de AMOR, FELICIDADE e SUCESSO.</p><p>1 — Priorize as pessoas que você ama</p><p>2 — Escolha bem o lugar onde você cria suas raizes( Emprego e Relacionamento). <strong><em>É preferível uma vida de mortal vivida no lugar certo, do que uma vida de Deus no lugar errado.</em></strong></p><p>3 — Seja curioso, pessoas curiosas são mais amigáveis, menos agressivas e menos jugadoras, A curiosidade é o elemento base de um espirito com sede de conhecimento. Ter um olhar curioso em relação a vida nos ajuda a pararmos de sermos meros replicadores para nos tornamos criadores das nossas próprias ideias e visões de um determinado assunto.</p><p>4 — Seja disciplinado, pessoas que se comprometem verdadeiramente com o que precisa ser feito ao invés do que eles querem fazer, conseguem potência de agir suficiente para realizar seus planos.</p><p>5— Leve a sério a TRINDADE (Exercícios Físicos, Alimentação saudável e SONOOOO).</p><p>6— Nunca esqueça dos seus sonhos, os sonhos é o que mantém a máquina no mais alto grau de refinamento.</p><p>Agradecimentos especiais para Deus, esse ano estou vivendo o momento mais mágico de toda minha vida, a paternidade despertou toda a minha alegria e a minha potência de agir. Deus obrigado pela vida do Pedro, ele sem dúvidas foi um dos meus maiores presentes. Não tenho dúvidas que ser pai é a melhor forma de provar a fidelidade aos nossos próprios valores, afinal de contas queremos nutrir nossos filhos com a seiva que produzimos a partir das nossas ações ao longo da nossa jornada.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e65ca6230fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-World Example of MDP — Customer Support]]></title>
            <link>https://medium.com/@denisbenevolo/modeling-problems-as-markov-decision-process-b08163cd953?source=rss-afc4c7a81439------2</link>
            <guid isPermaLink="false">https://medium.com/p/b08163cd953</guid>
            <category><![CDATA[markov-decision-process]]></category>
            <dc:creator><![CDATA[Denis Benevolo]]></dc:creator>
            <pubDate>Sun, 13 Mar 2022 23:28:32 GMT</pubDate>
            <atom:updated>2022-03-13T23:37:28.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9YQkDkwM0SwSk8Cyn6MRg.png" /></figure><p>Markov Decision Processes(MDP) is a fundamental framework for probabilistic planning which allows formalization of sequential decision making where actions from a state not just impact the immediate reward but also the next states. If you are facing or trying to solve a problem that maximizes the long-term return, MDP is a good framework to help you. If you want to see more details about MDP you can take a look at this article &quot;<a href="https://medium.com/@denisbenevolo/an-introduction-to-probabilistic-planning-ee8202810e5b">An introduction to Probabilistic Planning</a>&quot;.</p><p>Modeling a problem as an MDP is the first step towards solving it, but sometimes it can not be an easy task to do.</p><p>To model a problem as an MDP we need to understand the agent-environment interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*NzG3pv0452zPJhkA-xXF6g.png" /></figure><blockquote>&quot;The decision-maker is called the <strong>agent</strong>. The thing it interacts with, comprising everything outside the agent, is called the <strong>environment</strong>. These interact continually, the agent selecting <strong>actions</strong> and the environment responding to those actions and presenting new situations to the agent. The environment also gives rise to <strong>rewards</strong>, special numerical values that the agent tries to maximize over time.&quot; [1]</blockquote><p>In an MDP, an agent interacts with an environment by taking actions and seek to maximize the rewards the agent gets from the environment. At any given time stamp t, the process is as follows</p><ol><li>The environment is in state St</li><li>The agent takes an action At</li><li>The environment generates a reward Rt based on St and At</li><li>The environment moves to the next state St+1</li></ol><p>The solution of a MDP is a deterministic stationary policy π : S → A that specifies the action a = π(s) to be chosen in each state s.</p><h3>Real-World Examples of MDP - Customer Support</h3><p>We need to decide how many services to offer to a customer of a company that has many digital products in order to maximize the longer-term return. Customers with a high degree of loyalty are &quot;inclined&quot; to spend more with others products, at the same time customer with more products want to have more company support.</p><p>Here we consider a very simplified version of the above problem; whether to <strong>support </strong>or <strong>charge</strong> a customer. Support in most part of cases means reinvesting the money received by the customer. We can model this problem as MDP as follows.</p><p><strong>States:</strong> The degree of customer loyalty related to a specific company. For simplicity assume, there are only four states; <strong>NONE, LOW, MEDIUM, HIGH</strong>. The four states are defined as follows</p><p>NONE -&gt;The user is not a customer yet.</p><p>LOW -&gt; New customer with low loyalty.</p><p>MEDIUM -&gt; Customer with more products.</p><p>HIGH -&gt; Customer with many products and high loyalty.</p><p><strong>Actions:</strong> For simplicity assumes there are only two actions; <strong>support</strong> and <strong>charge</strong>. Support means reinvesting customer money to create a better experience. Charge means saving money in a company bank account for example. For the state NONE, the only possible action is <strong>support</strong>.</p><p><strong>Rewards</strong>: Charge at certain state generates rewards, let’s assume the rewards of Charging at state <strong>LOW, MEDIUM and HIGH </strong>are $100, $200, and $500 respectively. If an action takes to <strong>NONE</strong> state then the reward is very low -$2500 as it requires to get a new CUSTOMER which takes time and money.</p><p><strong>State Transitions</strong>: Charging in a state has higher a probability to move to a state with a lower degree of loyalty. Similarly, support action has a higher probability to move to a state with a higher degree of loyalty (except for the state high).</p><p><strong>Objective Function: </strong>Total Expected reward discounted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*0a2iC_dTrvnPJq55D10kww.png" /><figcaption>Figure 1: Transition graph For CustomerSupport MDP</figcaption></figure><p>Figure 1 shows the transition graph of this MDP. There are two kinds of nodes. Large circles are <strong><em>state nodes</em></strong>, small solid black circles are <strong><em>action nodes</em></strong>. Once an action is taken the environment responds with a reward and transitions to the next state. Such state transitions are represented by arrows from the action node to the state nodes. Each arrow shows the <strong>&lt;transition probability, reward&gt; (0.4, $100)</strong>. For example, from the state <em>Medium</em> action node <em>Charge </em>has 2 arrows transitioning to 2 different states; i) <em>Low</em> with <em>(probability=0.7, reward=$200)</em> or ii) back to <em>Medium</em> with <em>(probability=0.3, reward=$200).</em> In the state <strong><em>NONE</em></strong>, the only action is <em>Support.</em></p><p><strong>IMPLEMENTATION</strong></p><p>The language chosen to implement this code was python. The below class is responsible for modeling the MDP. First, we need to set the probabilistic matrix represented by the self._P object. So if the agent is in one specific state and takes one action we set the probabilities to reach the others states. Another really important thing to do is set the Reward Function represent by self._R. So if the agent is in a specific state and takes one action what is the reward associated with this action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97df01bf37c7ed3f618bd3d94a4d0837/href">https://medium.com/media/97df01bf37c7ed3f618bd3d94a4d0837/href</a></iframe><p>To solve this problem we need to find an optimal policy that is gonna tell us which action is the best action for each state.</p><p>To help us find this policy we are gonna implement the Value Iteration algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc185284d5a1964bd4ae87ef8c5f763b/href">https://medium.com/media/cc185284d5a1964bd4ae87ef8c5f763b/href</a></iframe><p>This method returns the value function(V), the policy(Pol) and error(err).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*A0k0f9womVbrrwWkdZumnA.png" /><figcaption>Figure 2: Policy</figcaption></figure><p>The image above represents the optimal policy returned by the Value Iteration algorithm, the policy tells us the best moment that we should charge the customer, it can be used as insight on what we need to focus on, in order to maximize in a long-term the incomes of a company.</p><p><strong>OBSERVATIONS</strong></p><p>Real problems are more complex them the case showed here and probably has much more states and transactions, but the goal of this article was to share the way to model this sort of problem.</p><p><strong>FULL CODE</strong></p><p>All the code can be found here <a href="https://github.com/DeBenevolo/CustomerSupport">https://github.com/DeBenevolo/CustomerSupport</a></p><p><strong>REFERENCES</strong></p><p>[1] Reinforcement Learning: An Introduction by Richard S. Sutton and Andrew G. Barto</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b08163cd953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Saga Mobilisa]]></title>
            <link>https://medium.com/@denisbenevolo/a-saga-mobilisa-e5df69af7611?source=rss-afc4c7a81439------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5df69af7611</guid>
            <dc:creator><![CDATA[Denis Benevolo]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 12:45:53 GMT</pubDate>
            <atom:updated>2021-11-01T14:47:26.753Z</atom:updated>
            <content:encoded><![CDATA[<p>Não imaginávamos o que nos esperava nessa jornada de muito aprendizado, desenvolvimento e realizações. Com mais de 5 anos de existência a Mobilisa foi concebida com o propósito de ser uma grande fornecedora de soluções criativas, tecnológicas e digitais para empreendedores e empresas que queriam aumentar seus resultados e seu posicionamento digital, priorizando o atendimento humanizado e a seriedade.</p><p>Como idealista que sou queria ir além, minhas ambições eram criar um ambiente onde teríamos uma equipe extremamente coesa, participativa, com alto grau de sinergia e respeito, dentro de um ambiente de trabalho descontraído, agradável e &quot;prazeroso&quot;, sim isso mesmo você leu “prazeroso” afinal de contas queríamos pessoas apaixonadas pelo que faziam assim como nos sócios, para mim a jornada é a melhor <strong>recompensa</strong>. E para criar essa base precisávamos de pessoas <strong>intergaláticas</strong> que deveriam ter algumas características em comum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*LsXcQ5lK2B6shmO8qQBqTA.png" /><figcaption>Características desejadas do Time Mobilisa</figcaption></figure><p><strong><em>ATENDIMENTO </em></strong><em>Todo integrante tinha como missão encantar e surpreender nossos clientes.</em></p><p><strong><em>TINO COMERCIAL </em></strong><em>Todo integrante precisava desenvolver a capacidade de vender, não só os serviços Mobilisa, mas suas próprias ideias, seus projetos e a si mesmo para o Time e para qualquer outra pessoa. Sabemos na prática que todo projeto ambicioso e de impacto começa com uma ideia / sonho dentro das pessoas, e que precisa ser plantando em outras pessoas para poder se desenvolver e prosperar.</em></p><p><strong><em>CRIATIVIDADE </em></strong><em>Na minha opinião essa é a uma característica vital e que tem o maior poder de gerar valor e impactar o resultado final para o Cliente, e, ao mesmo tempo, mais difícil de se obter, pois, ela exige sacrifício pessoal e muitas horas de prática e estudo. Quanto mais amplo é o seu conhecimento sobre as experiências humanas mais chances você terá de criar projetos melhores e mais criativos.</em></p><p><strong><em>CONHECIMENTO TÉCNICO </em></strong><em>Sem dúvidas queríamos pessoas boas nos que elas faziam, não precisavam saber de tudo, isso é impossível e desconfie de pessoas que te vendem isso, mas queríamos pessoas que fossem competentes o suficiente para ter consciência das partes que ela precisava melhorar e que tivesse alta capacidade cognitiva e comprometimento para ter um aprendizado constante e não estacionário.</em></p><p><strong>SELF-ORGANIZING</strong> Aplicação da Inteligência emocional para gerenciar suas <strong>motivações e sentimentos</strong> para um desempenho de alta performance e o senso de Dono da Empresa. De forma geral significa pessoas capazes de tomar suas próprias decisões, capazes de gerenciar suas responsabilidades e o seu próprio cronograma para finalização de uma missão.</p><p><strong>PRAZER NO QUE FAZ</strong> Esse tópico pode ser interpretado de forma equivocada pelas pessoas, a palavra prazer é utilizada em termos mais amplos e profundo é quase um estado de espírito não algo temporário e passageiro, você tem que sentir que seu trabalho é relevante e entrega valor para outro ser humano e que cada vez que você se desenvolve como profissional você chega mais próximo do seu proposito de vida.</p><p>Depois dessa definição de características começou nossa busca pelos nossos <strong>inteligentes criativos intergaláticos. </strong>Que sorte a nossa conseguimos reunir uma Time incrível</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4k7opP_tE9H3haUtwvy5lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*z_wQ9pId3iCAMahRCuZ4gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*ygzKwRViESudDAA0YuhbPg.png" /><figcaption>Inteligentes Criativos Intergaláticos</figcaption></figure><p>Nossa paixão como sócios é o combustível que gera a energia para criarmos o <strong>Sonho Mobilisa</strong>, e a visão que criávamos ao longo do caminho ensinava, a direção, para nosso time nos ajudar escrever essa historia.</p><p><em>&quot;Você pode sonhar, criar, projetar e construir o lugar mais maravilhoso do mundo, mas são necessárias as pessoas para transformar o sonho em realidade” </em>WALT DISNEY</p><p>Atendemos e ainda atendemos muitos Clientes e executamos muitos projetos grandes. Qual foi nosso maior segredo até aqui? Preocupação real com os negócios dos nossos clientes e o foco no longo prazo.</p><h3>APRENDIZADOS ADQUIRIDOS NESSA SAGA</h3><p>Um projeto bem executado não começa com tecnologia ou ferramenta, ele começa conhecendo as pessoas envolvidas nele, suas expectativas, suas aspirações e seus sonhos, aprenda como as pessoas gostariam de vivenciar uma experiência e projete sua solução com base nisso. Pense digital use todas as ferramentas disponíveis para te auxiliar no seu processo Google Drive, Gmail, Trello e etc. E nunca perca de vista o humano que será beneficiado pela sua solução (facilitar a vida das pessoas deve ser o objetivo maior de qualquer solução tecnológica).</p><p>Pense grande e fragmente seus projetos ambiciosos de forma que te permita trabalhar nele um pouco todos os dias, é o trabalho contínuo e diário que te trará resultados excepcionais.</p><p>Atraia pessoas que goste das suas ideias, sua visão de mundo e que tenha a mesma sede de conhecimento e crescimento que você.</p><p><em>“Ação é a medida real da inteligência” </em>Napoleon Hill</p><p>A ação e a proatividade é algo mágico e contagiante ela se espalha, não fique só na teoria ou só no mundo das ideias, ou palavras sua ação tem o poder transformador e inspirador. Use todo seu potencial de <strong>“Enteléquia”,</strong> que significa transformar em real o que é potencial.</p><p>Aprenda a empolgar e engajar as pessoas. Você pode ter a melhor ideia do mundo, porém se não souber empolgar as pessoas, talvez sua ideia não terá tanta importância.</p><p>Seja <strong>corajoso </strong>para assumir risco, e seja cauteloso para gerenciá-los.</p><p>E por fim seja <strong>humilde</strong>, lembre-se por mais esperto, inteligente e bem-sucedido na sua carreira e na sua vida você não terá todas as respostas para os dilemas que irá enfrentar, você precisa adotar o aprendizado continuo com meta, e ter a consciência que qualquer outra pessoa tem o potencial de te ensinar algo. E se você não está alcançando os resultados que você desejou para sua vida e empresa talvez precisa subir mais um degrau no seu desenvolvimento pessoal. E lembre-se você é um simples ser vivo vivendo em um planeta dentre milhares de outros planetas que está dentro uma galaxia dentre outras milhares de galaxias. Seja gentil</p><h3>PRÓXIMAS SAGAS</h3><p>Estou desembarcando da nave, mas isso não significa desconexão…</p><p>é praticamente impossível se desconectar de algo que foi criado com tanto carinho, dedicação e esforço, a torcida o carinho os laços criados serão eternos.</p><p><strong>Diga não a mil coisas</strong>, a <strong>Mobilisa</strong> é tão magnifica e plural que aparecem projetos e clientes de diversos tipos e natureza e pelo nosso ímpeto sempre acabamos dizendo sim para todos. Isso enquanto é magnifico me exige tempo, energia e carinho que gostaria de direcionar para alguns projetos de produto digital e não digitais que quero investir nessa nova fase.</p><p>Isso não significa que eu não vou mais atender projetos de tecnologia customizados ou por demanda, pelo contrário quero aumentar o foco em nichos específicos trazendo mais tecnologia e mais resultados para esses nichos.</p><p>Aguardem as novidades ….🚀🚀</p><h3>AGRADECIMENTOS</h3><p>Tive a sorte grande de ter encontrado pessoas maravilhosas ao longo dessa SAGA, de forma especial queria agradecer o <strong>Sr. Gregório Marin</strong>, o cara mais maluco mais intergalático, positivo, verdadeiro e gentil que eu já encontrei. Sem ele esse sonho possivelmente não existiria dessa forma, ele sempre foi um incentivador e entusiasta da Mobilisa. ❤️</p><p>Agradeço meus queridos Sócios <strong>Isa e Greg</strong> a qual tenho tremendo respeito, carinho e admiração. A jornada até aqui foi uma delícia com vocês. Não tenho dúvidas que a Nave Mobilisa está em excelentes mãos. Dizem que nos tornamos a média das 5 pessoas que mais convivemos ao longo dos anos então, sem dúvidas tem muito de Greg e Isa dentro de mim, pois passamos muitos dias muitas horas construindo esse sonho.</p><p>Agradeço a todos os Mobilizers que passaram pela Mobilisa e ajudaram a construir esse sonho. E finalmente a todos os clientes que acreditaram e escolhem acreditar todos os dias na Mobilisa.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5df69af7611" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An introduction to Probabilistic Planning]]></title>
            <link>https://medium.com/@denisbenevolo/an-introduction-to-probabilistic-planning-ee8202810e5b?source=rss-afc4c7a81439------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8202810e5b</guid>
            <dc:creator><![CDATA[Denis Benevolo]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 20:08:19 GMT</pubDate>
            <atom:updated>2020-04-11T20:31:11.137Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is the first part of my Probabilistic Planning series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*B4xXGD3pXqbYeWld9quktA.png" /></figure><p>Markov Decision Processes(MDP) is a fundamental framework for probabilistic planning. MDPs are also used in Reinforcement Learning, but in this article, we will focus on probabilistic planning based on MDPs. But first of all, let me explain the difference between reinforcement learning problem(RLP) and probabilistic planning problems(PPP), both problems are an aspect of Machine learning, in RLP an agent learns to behave in an environment, by performing certain actions and observing the rewards/results which it gets from those actions so the objective would be to maximize the reward through experience and through interaction with the environment. In PPP we assume you have access to a model of the environment, and we try to solve it, we try to find a policy. It does not require collecting true experience from the real environment, but some planning methods are based on simulated experience from the known (or modeled) environment.</p><p>We will learn about MDP and its details:</p><ul><li>What is an MDP?</li><li>What is an MDP Solution?</li><li>How find an optimal MDP Solution?</li><li>Implementation using python</li></ul><p>There are situations where decisions must be made in <strong>sequence</strong> and <strong>instantaneously</strong>, and the result of each decision is not clear to the decision-maker, the actions are <strong>stochastics</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgT18PPa2h1z356Hi-23PQ.png" /><figcaption>UP ACTION</figcaption></figure><p>The environment is <strong>static</strong> and <strong>fully observable</strong> that is the current state of the system is known. These situations can be formulated mathematically as Markov decision processes, and given the probabilities of each value, it is possible to determine a policy that maximizes the expected outcome of a sequence of decisions.</p><h3>1.Markov Decision Processes</h3><p>MDP are models for sequential decision-making when outcomes are uncertain. The Markov decision process model consists of decision epochs, states, actions, rewards or costs, and transition probabilities. Choosing an action in a state generates a reward and determines the state at the next decision epoch through a transition probability function.</p><p>MDP it’s a tuple M = (S,A,P,R,γ)</p><ul><li>S is a discrete and finite set of completely observable states that we model the world;</li><li>A is a finite set of actions, performing an action allows the system to change from the current state to the next state;</li><li>P(·|s,a) is the probabilistic transition function that describes the effects of performing an action a ∈ A in a state s ∈ S resulting in a state s′ ∈ S;</li><li>R(s,a) is the reward function of performing an action a ∈ A in a state s ∈ S;</li><li>γ is the discount factor, where 0≤ γ &lt; 1, so after t stages the cost is discounted by γt</li></ul><p>The agent performs the actions in discrete steps over time. For each action performed, the state of the system is changed according to the P transition function, and the execution of an action in a state has a cost.<br>Decision-making is carried out over a horizon. The horizon is the number of steps (or decision times) that the agent has to act, which can be: finite, infinite or indeterminate. Thus, MDPs can be classified by their horizon into:</p><ul><li>MDP with <strong>finite horizon</strong> that has a fixed number of steps to be taken. We can imagine an agent who has a finite resource to perform a certain activity, for example: fuel, with no chance of refueling, this limits the number of steps to be taken.</li><li>MDP with <strong>infinite horizon</strong> is when steps are taken repeatedly, without the possibility of stopping.</li><li>MDP with <strong>indeterminate horizon</strong> is similar to the infinite horizon, but with the possibility of stopping as soon as the process reaches some final state, i.e., until some state that ends the process execution. This type of MDPs includes a set of meta <strong><em>G</em></strong> states.</li></ul><p>The solution to an MDP is a policy.</p><p>Regarding its relation to the steps (or decision times) a policy can be classified as:</p><ul><li><strong>Stationary</strong>, if the recommended action is independent of the number of decision steps. This means that the best action to be taken in the <strong><em>s</em></strong> state is always the same, regardless of time.</li><li><strong>Non-stationary</strong>, if the decision made depends on the decision step.</li></ul><p>It is very common to use stationary policies for an infinite horizon and non-stationary policies for a finite horizon. A policy can also be:</p><ul><li><strong>Deterministic</strong>, when each s in S state is always mapped into a single action.</li><li><strong>Stochastic</strong>, when a state is mapped into a set of actions, the action having a probability of being chosen.</li></ul><p>Other types of policies that we won&#39;t talk about are non-Markovian policies, in which the recommended action depends on the entire history of actions and states visited to date.</p><p>The solution of an infinite or indeterminate MDP is a deterministic stationary policy π : S → A that specifies the action a = π(s) to be chosen in each state s.</p><p>To compare two policies and find the optimal policy (π*), it is necessary to define a performance criterion. There are several criteria that can be used, among the best known the following can be mentioned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*TJk-hDJ2CARqIi6TyzbA8Q.png" /></figure><p>where<strong><em> t</em></strong> denotes the MDP horizon. These criteria are considered risk-neutral, as they do not take into account the risk of taking a certain decision step. The main objective is to minimize any of these criteria.<br>In this article, the focus is on the expected total discounted cost.</p><p>The policy value <strong><em>π</em></strong> starting in state <strong><em>s</em></strong> and running <strong><em>π</em></strong>, it is denoted by <strong><em>Vπ(s)</em></strong> and is defined as the expected sum of the discounted costs, where<strong><em> s₀=s</em></strong>, that is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*bEyys_zRr6nWgMkWd8vm6w.png" /></figure><h3>Optimal policy</h3><p>Among all possible policies for an MDP, it is desired to find an optimal policy that minimizes the expected total cost discounted. The optimal value function, represented by <strong><em>V*</em></strong>, is the value function associated with any optimal policy. Thus, for an amount that wishes to minimize its expected total discounted cost, <strong><em>V* </em></strong>satisfies the following fixed point equality or also called <strong><em>Bellman Equation</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*5_y6JDtEnx01P68Q_KrsCw.png" /></figure><h3>2.Algorithm for MDPs</h3><p>The three classic algorithms for solving MDPs are Value Iteration (VI), Policy Iteration (PI) and formulation using linear programming. In this article, we use the Value Iteration algorithm.</p><h3>Value Iteration</h3><p>A well-known algorithm for determining the <strong><em>V*</em></strong>(s) value of each MDP <strong><em>s</em></strong> in <strong><em>S </em></strong>state is the Value Iteration (VI) algorithm. Starting with an arbitrary <strong><em>V⁰</em></strong>, <strong><em>VI </em></strong>performs updates of all states s, calculating Vt based on the value of Vt-1.</p><p>The pseudo code of algorithm IV is shown in the algorithm. The algorithm receives an MDP and returns the optimal value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*oMmQ313CePlHNwSfdcg75w.png" /></figure><h3>3.Python Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*SaHHNgcTSu7PjVEtIhnX5Q.jpeg" /></figure><p>Now we are gonna solve the instances of Grid World Problem.</p><p>The <strong><em>Grid World problem</em></strong> has a 2D terrain map that is represented by a N x M grid. An agent (for example, a robotic vehicle) starts in a safe region and its goal is to travel to a certain destination. At each step, the agent can move north (N), south (S), east (E) or west (W). The probability of the action having the desired effect is 95%. In addition, there is<br> p = 5 % / 3 = 1.67 % probability of moving to one of the other 3 neighboring states.</p><p>The following two codes provide classes and functions for the resolution of discrete-time Markov Decision Processes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4e24fd5b8cc8d296396dd7b99b0855c/href">https://medium.com/media/c4e24fd5b8cc8d296396dd7b99b0855c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a39a269890c19013eb21bc903795339/href">https://medium.com/media/6a39a269890c19013eb21bc903795339/href</a></iframe><p>The code below is the implementation of the Value Iteration algorithm with a little modification to return the best policy as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c815996b836ab4bec9a5f7d3c6229544/href">https://medium.com/media/c815996b836ab4bec9a5f7d3c6229544/href</a></iframe><p>This code below models the Grid World Problem into a MDP, it is made by taking a PNG image, which every white pixel will be considered a cell of grid and the black pixel will be considered an obstacle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*6UOJqEKyRRKUlbzSRvEGJA.png" /><figcaption>Eg: Input for Gridworld_MDP_Pen_class</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa083d471ff4bfb4688af41a56b17ea1/href">https://medium.com/media/aa083d471ff4bfb4688af41a56b17ea1/href</a></iframe><p>Finally, the last code that will call all classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7ccc034c93ded18da02febe4ff2e81a/href">https://medium.com/media/f7ccc034c93ded18da02febe4ff2e81a/href</a></iframe><h3>The full Code</h3><p>All the code implementation can be found here <a href="https://github.com/Dbenevolo/MDP">https://github.com/Dbenevolo/MDP</a></p><h3>References</h3><p><a href="https://www.teses.usp.br/teses/disponiveis/100/100131/tde-30012020-115648/pt-br.php">https://www.teses.usp.br/teses/disponiveis/100/100131/tde-30012020-115648/pt-br.php</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8202810e5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Somos o que lembramos ou somos o que esquecemos ?]]></title>
            <link>https://medium.com/@denisbenevolo/somos-o-que-lembramos-ou-somos-o-que-esquecemos-db0b9b5b0bd?source=rss-afc4c7a81439------2</link>
            <guid isPermaLink="false">https://medium.com/p/db0b9b5b0bd</guid>
            <dc:creator><![CDATA[Denis Benevolo]]></dc:creator>
            <pubDate>Thu, 02 Mar 2017 14:11:10 GMT</pubDate>
            <atom:updated>2019-09-07T15:56:18.994Z</atom:updated>
            <content:encoded><![CDATA[<p>Apaixonado e curioso por neurociências e pelos mistérios da mente humana, decidi ainda no tempo da graduação ter uma experiência mais sólida e concreta neste universo complexo e misterioso, permeado por axônios, dendritos, sinapses e conexões inimagináveis. E como parte dessa paixão aceitei o desafio de publicar meu <strong>ensaio</strong> sobre os processos da memória desenvolvido em uma disciplina de neurociência cursada na Universidade de São Paulo.</p><p><strong>O OBJETIVO</strong> desse ensaio é discutir a importância das estruturas envolvidas no processo de arquivamento e de remoção das nossas histórias existenciais, as famosas janelas da memória, que em conjunto criam a percepção do nosso <strong>EU.</strong></p><p>Apesar desse tema estar em check e ter um grande destaque hoje em dia esse campo só teve um grande desenvolvimento nos últimos 60 anos com surgimento de novas tecnologias e pesquisas, o que significa que temos muito a aprender ainda sobre o tema, o que aguça ainda mais a minha curiosidade e desejo de desvendar esse corpo magnifico que é o cérebro humano.</p><p>Somos quem somos por causa daquilo de que nos lembramos. É isso que nos confere identidade e que permite-nos traçar nossa própria personalidade ou forma de ser. “<em>Cada um de nós é quem é porque tem suas próprias memórias” </em>(Izquierdo ,2004) . Nossa vida é frequentemente inundada de memórias, porém é uma parcela pequena das memórias que realmente nos marcam e que se instalam na nossa<strong> memória permanente</strong>, “<em>Hoje sabemos que nem tudo o que é adquirido forma memórias”</em> (Izquierdo, 2004, pág. 39), os esquecimentos funcionam como mecanismo de limpeza que ajudam a otimizar o trabalho do cérebro e também como filtro do conjunto de informação que são importantes para o individuo naquele instante. “<em>Assim, podemos afirmar que houve algo seletivo e proposital em nosso esquecimento”</em> (Izquierdo, 2004, pág. 17). O esquecimento que de acordo com algumas evidências que serão ponderadas a seguir pode ser considerado o processo hegemônico na construção da ideia de quem somos, através da limpeza e da filtragem das informações adquiridas pelos meios sensitivos. O que torna mais difícil e complexa a resposta a pergunta: Somos o que lembramos ou Somos o que esquecemos ?</p><p><strong><em>Memória</em></strong><em> é aquisição, a formação, a conservação e a evocação de informações </em>(Izquierdo, 2002, pág. 09)<em>. </em>No processo de aquisição existem três tipos de memórias com envolvimento direto na efetivação desse processo, que são: <strong>memória de curto prazo</strong> ou <strong>curta duração</strong>, <strong>memória de longa duração</strong> e <strong>memória de trabalho</strong>; esta última difere das duas primeiras principalmente pela capacidade de funcionar como “administrador” e filtro das informações externas e internas, e também pelo esquecimento rápido das informações . Nesse processo, <em>A </em><strong><em>memória de curta duração</em></strong><em> só serve para manter a informação disponível para o sujeito durante o tempo que requer para a memória de longa duração ser construída</em> (Izquierdo, 2004, pág. 35) ela é rapidamente adquirida e pode perdurar <em>até 6 horas</em> (Izquierdo, 2002, pág 51) ,o tempo médio necessário para a <strong>memória de longa duração</strong> ser efetivamente construída. Porém segundo Izquierdo essas duas memórias não podem ser entendidas como partes de um mesmo processo, mais sim duas séries de processos paralelos, independentes e complementares. A memória de trabalho faz a articulação das informações internas e externas, é ela que ao receber qualquer tipo de informação vai determinar se é nova ou não, e sobre tudo se é útil para o organismo ou não. Contudo esse diálogo depende da conservação da informação por pouco tempo para fazer a comparação com a “biblioteca” de memórias de curta e longa duração do organismo, porém para que seu funcionamento seja eficaz e funcional ela tem que comportar o dispositivo do esquecimento que é fundamental como diz Borges (1943), para poder <strong>generalizar</strong>. A <strong>generalização</strong> é essencial para a plena articulação de ideias e pensamentos, pois se lembrássemos de tudo que nos aconteceu em um dia, desde a cor do céu em determinada hora ou o que fizemos em cada minuto que se passou ao longo de 24 horas não conseguiríamos deter-se por um momento em uma única memória, o que nos impediria de analisá-las e compará-las com outras, significando que estaríamos preso na simples e pura sequência dos acontecimentos, tornaríamos meros espectadores da vida, sem mesmo ter a consciência disto.</p><p>O esquecimento em determinadas circunstâncias é detestável, como por exemplo na hora de pegar as chaves do carro, e então dar-se conta de que não se lembra onde deixou-a, ou quando se esforça para formar a imagem daquela professora ou pessoa que te marcou profundamente e que agora você não é nem capaz de lembrar mais da sua fisionomia, esses são alguns “efeitos colaterais” do esquecimento, aspectos estes que marcam e categoriza o esquecimento como algo negativo, porém olhando de uma outra perspectiva podemos nos dar conta da importância do esquecimento, por exemplo se todas as mulheres lembrassem da real dor do primeiro parto, sem dúvidas elas hesitariam em conceber outros filhos ou se lembrássemos das humilhações, afrontas, inimizades, fracassos e momentos desagradáveis da nossa vida viveríamos deprimidos, enraivecidos ou até mesmo depressivo o que atrapalharia nossa convivência social, inibiria a nossa esperança e a possibilidade de tentar ou querer arriscar novamente.</p><p>Existem alguns mecanismos de esquecimentos, que de fato não funcionam como perda real da memória, como: <strong>habituação, extinção e repressão</strong>. A habituação seria a progressiva diminuição da reação ou resposta frente à repetição do estimulo, na extinção se um estímulo não for reforçado com um estimulo incondicionado, provocará a extinção que não é propriamente o esquecimento, na verdade seria associação do primeiro com a recém — aprendida ausência do segundo, por exemplo, se vemos que com o choro não temos alimento deixamos de chorar para conseguir este. E por último a repressão que é um fenômeno concebido pela psicanálise, que seria o ato consciente de tornar algumas memorias inacessíveis, cujo acesso bloqueamos. Essas formas de esquecimentos estão presente no nosso cotidiano principalmente a habituação e a extinção que faz parte do nosso aprendizado, a extinção é usada como forma de terapia para curar algumas fobias, através do estimulo ao objeto de medo e com a falta de um estimulo incondicionado(que seria por exemplo o ataque de uma aranha) leva o individuo a extinguir aquele medo. Já a repressão faz o individuo reprimir as memórias que compreende episódios humilhantes, desagradáveis ou inconvenientes.</p><p>Um forma de tentarmos responder a pergunta central deste texto é abordamos um tema extensamente discutido nas teorias sociais que é a questão da <strong>Identidade</strong>, Algo que entendemos como pertencente ao nosso <strong>EU. </strong>E que de acordo com o que foi ponderado até agora podemos constatar que a ideia da construção da identidade se aproxima muito da concepção de <strong>sujeito sociológico</strong> no qual<em>… a identidade é formada na interação entre o eu e a sociedade,… este é formado e modificado num diálogo contínuo com os mundos culturais “exteriores” e as identidades que esses mundos oferecem. (Hall,2003, pág. 11) , </em>e como foi dito anteriormente um dos sistemas preponderantes na construção das memórias(e consequentemente da identidade) é a memória de trabalho, que gerencia as informações internas e a realidade que se apresentada para o sujeito, sendo que uma de suas principais características é a capacidade de perde informações ou melhor dizendo <strong>esquecer</strong>, com isso e de uma forma cuidadosa para que isso não seja entendido como um paradoxo, esse texto coloca o esquecimento como ator principal da ideia de quem somos. Partido do pressuposto que o esquecimento é o responsável por determinar o que será lembrado, ou melhor o que será “deletado”, podemos visualizá-lo também como integrante de um mecanismo de defesa do eu, no qual ele contribui com uma categorização das nossas vivências, validando-as ou não. Validador quando as nossas experiências vividas estão em sintonia com os desejos internos e com as exigências do mundo circundante e anulador quando ao contrário, por exemplo quando uma pessoa tem êxito em uma atividade que envolve a aprovação dos outros ela comumente lembrará desse episódio, porém se fracassar a chance de lembra detalhes e fatos ligados a esse evento é muito pequena.</p><p>Contudo o meio sociocultural no qual estamos inseridos junto com alguns mecanismos de esquecimentos tem uma peso decisivo na formação da ideia de quem somos, gerando memórias, e deste conjunto de memórias faz surgir essa ideia de identidade, que por sua vez esta intrinsecamente conectada a processos inconscientes ou consciente de proteção do nosso eu dentro de um contexto cultural, não que lembranças ruins não nos marquem ou não façam parte da nossa biblioteca de memórias, elas também são partes de nós, porém elas constituem partes de um sistema de aprendizado no qual lembramos dos nosso erros para evitar cometê-los novamente. Enfim com uma forma simplificada de mostrar o sistema de memória dos seres humanos, esse texto mostrou a relevância dos esquecimentos na vida das pessoas, relevância que alias não é nada trivial pelo contrário tem interferência direta e efetiva na construção de quem somos.</p><p>Enfim, Somos o que lembramos ou Somos o que esquecemos ?</p><p>Iván Izquierdo : Memória — Porto Alegre: Artmed, 2002.</p><p>Iván Izquierdo: A arte de esquecer : cérebro e memória — Rio de Janeiro : Vieira &amp; Lent, 2004.</p><p>Jorge Luiz Borges:Formas de esquecimento — Buenos Aires: Emecé, 1943.Stuart Hall:<em> </em>A identidade cultural na pós-modernidade: 2003.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db0b9b5b0bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>