teleren/devto huggingface dataset:
automatic dependency injection in 4/5 lines of code
Tags: php, dependencyinijection, designpattern, dic
Published: 2023-04-30 22:18:34

---
title: automatic dependency injection in 4/5 lines of code
published: true
description: 
tags: php, dependencyinijection, designpattern, dic
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqtzeijqkuo77qmdfaal.jpg
series: php
---

## The project

You can find the code [here](https://github.com/sensorario/dependency-injection). 

## Prerequisite

You just have installed composer due to this script uses psr-4 autoloading.

## Usage

If you have a more complex situation like this

```php
class Foo {}
class Bar { public function __construct(Foo $foo) {} }
class Pub {
  public function __construct(Bar $bar) {}
  public function method() {
    return 42;
  }
}
class Animal { }
class Cat { public function __construct(Animal $animal) {} }
class Fizz {
  public function __construct(private Pub $pub) {}
  public function doSomething(Cat $cat) {
    return $this->pub->method();
  }
}
```

You can instance `Fizz` object and the run `doSomething` method just doing

```php
$result = injector(Fizz::class, 'doSomething');
```

## 5 line solution

This solution is not readable. Is just to create a clickbait.

```php
function injector($instance, $method = '__construct', $deps = []) {
    foreach ((new \ReflectionMethod($instance, $method))->getParameters() as $dep) {
        $className = (string) $dep->getType();
        $deps[] = new $className;
    }
    return $method == '__construct' ? new $instance(...$deps) : injector($instance)->$method(...$deps);
}
```

## Readable solution

This is a readable solution.

```php
function buildDeps($instance, $method, $deps = []) {
    $params = (new \ReflectionMethod($instance, $method))
        ->getParameters();
    foreach ($params as $dep) {
        $className = (string) $dep->getType();
        $deps[] = new $className;
    }
    return $deps;
}

function injector($instance, $method = '__construct') {
    $deps = buildDeps($instance, $method);
    return $method == '__construct'
        ? new $instance(...$deps)
        : injector($instance)->$method(...$deps);
}
```

And if you want to see the entire process of its creation (but, sorry, only in italian) [click here](https://youtu.be/9G_NO9n7wSI).
Find AWS Lambda Functions Executed in a Specific Time Range Using Boto3 and CloudWatch Logs
Tags: aws, python
Published: 2023-04-30 21:41:45

### Motivation

At times, we need to identify which Lambda functions were executed within a specific time range, primarily for troubleshooting or monitoring purposes. 

In this blog, I'll share a Python Boto3 script that allows you to search and discover which Lambda functions have execution results in their CloudWatch logs. 

(Note: You can also use CloudWatch Logs Insights to query the logs. If the number of target log groups is smaller than [the maximum limit of 50](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html), using Logs Insights on the Console might be more convenient.)


### Code

{% embed https://gist.github.com/shimo164/3de25a148e06036d5db56bcc81ffbaa2 %}

### Example results

This is the example of the results. I've found that the Lambda function `test-my2` was executed twice (`2 events`) between `2023-04-30 20:10:00+09:00` and `2023-04-30 21:10:00+09:00`.

```
Start. 2023-04-30 21:20:37
===
From 2023-04-30 20:10:00+09:00
To 2023-04-30 21:10:00+09:00
Check 65 log groups... wait...
---
/aws/lambda/test-my2
2 events
===
Finished.  2023-04-30 21:21:17
```

## Appendix

You can also use `logGroupNamePattern` instead of `logGroupNamePrefix`. (These are mutually exclusive. ) Note that boto3 version after 1.26.17 is required.

Refer to [the boto3 document](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs/client/describe_log_groups.html).
JavaScript Event Listeners, with Turbolinks and AJAX
Tags: discuss, javascript, rails, jquery
Published: 2023-04-30 21:40:30

What best practices do you follow to maintain a clean, logical set of initializers in a Rails app, taking Turbolinks and AJAX into account?

I've seen whole app initializes and single function listeners while looking through various open source apps. Some big Ruby on Rails app are set up like this:
https://github.com/forem/forem/blob/main/app/assets/javascripts/base.js.erb
https://github.com/gitlabhq/gitlabhq/blob/master/app/assets/javascripts/main.js

I've been primarily working on smaller Rails apps, and I've found it easiest to set up standalone listeners, similar to this:
```
// Turbolinks and AJAX listeners
$(document).on('turbolinks:render ajaxSuccess', function () {
  some_function();
}); 

// Document ready
// (Older versions of jQuery let me put ready in the first listener)
$(document).ready(function() {
  some_function();
});
```

Click and change listeners are added similar to this:
```
$(document).on('click', '.my-class', function() {
  some_function();
});
```
Boost Your Next.js Project with this Pre-Built Application Template
Tags: nextjs, mantine, typescript, react
Published: 2023-04-30 21:39:11

![Next.js Application Template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rolz5g99mr81o1pz0t3.png)

Are you planning to kick-start a new project using Next.js? Save time and energy by leveraging this comprehensive [Next.js Application Template](https://github.com/Liksu/next-template), which comes with predefined libraries, configurations, and components to help you get up and running in no time!

## Key Features

- **Top-notch libraries and configurations**: Next.js, Mantine, next-i18next, NextAuth.js, MongoDB, MDX, PM2, React GA4, TypeScript, and ESLint.
- **Predefined components**: Layout components, User components, HttpClient, ALink, ColorSchemeToggle, and Social Buttons.
- **Constants**: Auth options and Header Menu items.
- **Backend helpers**: MongoDB connection, Auth guard middleware, API Restrictor, HTTP Responses, and getTranslations helper.
- **Pages**: Predefined `_app`, `_document`, `404`, `500` and test sample pages `index`, `mdx-test`, and `profile/index`.

The template provides seamless integration with popular libraries such as Mantine, NextAuth.js, and MongoDB to create a modern and powerful stack. 

Mantine is a React component library that offers a range of components like core, dates, forms, modals, and notifications. With NextAuth.js, you'll have authentication and authorization out-of-the-box, while MongoDB enables an efficient database management system. 

Additionally, the template includes MDX support for better content management, PM2 for process management, and React GA4 for Google Analytics integration.

The predefined components, constants, and backend helpers will ensure you have a solid foundation for your project. The template covers a wide range of use cases, from user management to layout and social media integration. 

## Conclusion

The Next.js Application Template provides a powerful starting point for your web development projects. By using this template, you'll save time and effort in configuring and setting up the essential components, allowing you to focus on developing the unique features of your application.

Jump-start your Next.js journey with this robust template and experience a seamless web development process. Explore and use the template by visiting the GitHub repository: [https://github.com/Liksu/next-template](https://github.com/Liksu/next-template).
"Reflections On My Journey as a Software Engineering Student"
Tags: beginners, programming, learning, challenge
Published: 2023-04-30 21:05:26

Denzel Washington's quote highlights the inevitability of challenges and difficulties that come with pursuing our goals. It reminds us that, just as we pray for rain, we must also be prepared to deal with the mud that comes with it. Challenges are an integral part of the journey, and without them, we may lack the motivation needed to achieve our goals. Instead, we should embrace the obstacles we face and use them as opportunities for growth and development. Only by setting ambitious and challenging goals can we truly realize our full potential and live a fulfilling life.

As I near the end of my journey as a Flatiron student in
Software Engineering, I am filled with a sense of pride and accomplishment. This program has been challenging, but it has also been incredibly rewarding. Through it all, I have learned a great deal about myself and my capabilities.

Managing the demands of school, work, and family can be overwhelming, while being a 40-something with limited mental bandwidth has been a significant challenge.  There were times when exhaustion set in, and I struggled to keep up. Despite these challenges, I persevered and discovered that my strength and resilience far exceeded my expectations.


![quote](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/naf0go2bhaut8je17rw9.jpg)

I have learned a crucial lesson that I can steer my thoughts and emotions in the direction I want. During the program's initial stages, I faced anxiety, particularly when going through each phase's review, live coding, and interview questions. However, I chose not to succumb to pessimism and instead, I was able to maintain a positive outlook.

I believe that joining this bootcamp was a divine intervention, and I am grateful for the path that has been set for me. I trust that HE has always guided me and put the right people in my life to help me achieve my goals. My loved ones have been a constant source of support and inspiration, always there to offer me words of encouragement and motivation when I needed them the most. Their unwavering belief in me has been instrumental in propelling me towards success.
Download a file with react hook
Tags: react, javascript, frontend, webdev
Published: 2023-04-30 20:59:55

## What for?
Simply couldn't find a react hook that will let me just pass my data (string, arraybuffer) and download it as a file.

## Description

A react hook to handle data downloading as a file.
Without any dependencies and with typescript support.

## How to use?
Click here [react-downloadfile-hook](https://www.npmjs.com/package/react-downloadfile-hook)

```
npm install --save react-downloadfile-hook

yarn add react-downloadfile-hook
```

## Examples

#### Download properly through a link

This is a recommended method to handle downloading. You need to provide required `fileName`, `format/mime-type`, `data` properties into the hook.

```jsx
import { useDownloadFile } from "react-downloadfile-hook";

const { linkProps } = useDownloadFile({
  fileName,
  format: "image/svg+xml",
  data: `<svg><circle cx="50" cy="50" r="40"fill="red" /></svg>`,
});

<a {...linkProps}>Download SVG File</a>;
```

#### Download on click

The simplest way to handle downloading. It also named as a "force download a file". It uses old-school method, adding a link into the DOM and click it.

```jsx
import { useDownloadFile } from "react-downloadfile-hook";

const { downloadFile } = useDownloadFile({
  fileName,
  format: "image/svg+xml",
  data: `<svg><circle cx="50" cy="50" r="40"fill="red" /></svg>`,
});

<Button onClick={downloadFile}>Download SVG File</Button>;
```

#### Advanced handling

If your data is not a `string` type (`ArrayBuffer`, `Uint8Array`, etc), you may need to replace the built-in handler.
You need provide `onCreateBlob` callback that returns `Blob`.

```jsx
import { useDownloadFile } from "react-downloadfile-hook";

const { downloadFile, linkProps } = useDownloadFile({
  fileName,
  format: "image/svg+xml",
  data: new Uint8Array([1, 2, 3]),
  onCreateBlob: (data: uint8Array, format) => {
    const arrayBuffer = uint8Array.buffer;
    return new Blob([arrayBuffer], { type: format });
  },
});

<a {...linkProps}>Download File</a>;
<Button onClick={downloadFile}>Download File</Button>;
```

#### Cheers!
Writing flexible code - callback functions.
Tags: 100daysofcode, flatironschool, callbackfunctions, beginners
Published: 2023-04-30 20:35:28

Today, I'd like to share a simple example of how callback functions can be used in JavaScript to perform an operation asynchronously and handle the result when it's available.

A callback function is a function that is passed as an argument to another function and is executed at a later point in time.

Let's say you have a function called 'add' that accepts two numbers and a callback function. Inside the 'add' function, you add the two numbers together and pass the result to the callback function.

To use the 'add' function with a callback, you simply call it with the numbers you want to add and a function that handles the result. For example, you could call 'add(2, 3, callback)' with a function that logs the result to the console.

When the 'add' function is executed, it calls the function with the result of the addition, allowing you to handle the result in a separate piece of code. This is a powerful programming concept that can make your code more efficient, flexible, and maintainable.

```
function add(a, b, callback) {
  const result = a + b;
  callback(result);
}

add(2, 3, function(result) {
  console.log(result);
});
```

I hope this example helps you understand how callback functions work in JavaScript. If you have any questions or feedback or even want to critique a little, PLEASE leave me a comment, I'm still learning and love hearing others thoughts and better ways to work.

2/100
Open/Closed Principle
Tags: programming, oop, csharp, dotnet
Published: 2023-04-30 20:21:11

The Open/Closed Principle (OCP) states that:

> _Software entities should be open for extension but closed for modification._

This means that a class should allow for the addition of new functionalities without changing the existing code, while the behavior of existing classes should not be altered.

## Violation of the principle

Imagine having a class that calculates the area of different geometric shapes:

```csharp
public class AreaCalculator
{
    public double CalculateArea(object[] shapes)
    {
        var area = 0d;
        foreach (var shape in shapes)
        {
            if (shape is Rectangle)
            {
                var rectangle = (Rectangle)shape;
                area += rectangle.Width * rectangle.Height;
            }
            else if (shape is Circle)
            {
                var circle = (Circle)shape;
                area += Math.PI * Math.Pow(circle.Radius, 2);
            }
        }
        return area;
    }
}
```

This implementation violates the OCP because each time we add a new geometric shape, we have to modify the `CalculateArea` method by adding a new conditional `if` block.

## Application of the principle

To comply with the OCP, we can use inheritance and polymorphism by introducing an `IShape` interface with a `CalculateArea` method and ensuring that the classes of various shapes implement this interface:

```csharp
public interface IShape
{
    double CalculateArea();
}

public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public double CalculateArea()
    {
        return Width * Height;
    }
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public double CalculateArea()
    {
        return Math.PI * Math.Pow(Radius, 2);
    }
}
```

Now we can rewrite the `AreaCalculator` class to use polymorphism to calculate the area of shapes without having to modify the class each time a new geometric shape is added:

```csharp
public class AreaCalculator
{
    public double CalculateArea(IShape[] shapes)
    {
        var area = 0d;
        foreach (var shape in shapes)
        {
            area += shape.CalculateArea();
        }
        return area;
    }
}
```

## Conclusion

In this article, we have explored the Open/Closed Principle, which guides us in creating classes and modules that are resistant to direct modifications but amenable to extensions. This principle emphasizes the use of abstractions and inheritance to add functionality to classes without altering their original implementation. The result is code that is easier to maintain and more extensible, reducing the impact of changes on pre-existing implementations.

## References

- [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.pearson.com/en-us/subject-catalog/p/clean-code-a-handbook-of-agile-software-craftsmanship/P200000009044/9780132350884)
- [Adaptive Code: Agile coding with design patterns and SOLID principles](https://www.microsoftpressstore.com/store/adaptive-code-agile-coding-with-design-patterns-and-9781509302581)
Minimalist accordion design
Tags: uidesign, accordion, bootstrap, css
Published: 2023-04-30 19:49:15

In this article, we'll learn how to implement a bootstrap accordion with responsive.

First of all, create html structure
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smd3epkoepjrx6qq3ne7.png)


While development use the [boostrap](https://getbootstrap.com/) cdn

```
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"></script>
```

Adding accordion component with bootstrap

```
<div class="accordion" id="accordionExample">
    <div class="accordion-item">
      <h2 class="accordion-header" id="headingOne">
        <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Accordion Item #1
        </button>
      </h2>
      <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
        <div class="accordion-body">
          <strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
        </div>
      </div>
    </div>
</div>

```

Now we can get skeleton of accordion
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nya0pgjwhclc46lnlhj3.PNG)

and adding custom style using my source code

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ycjm3dejnv0m1vrmw9u.PNG)


Source will be available on : https://github.com/erajamanickam/simple-accordion

Live demo of minimalist accordion : 
https://simple-accordion-css.vercel.app/

Watch on video : https://www.youtube.com/watch?v=nBiMV9kCBqA&t=26s

Codepen : https://codepen.io/erajamanickam/pen/rNqzReE
Basic web scraping with php
Tags: php, webscraping
Published: 2023-04-30 19:19:43

Trying to fetch the above using php.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydrqkfnh3g0cc1805zfi.png)



```php
    public function __invoke()
    {
        $contents = file_get_contents('https://www.google.com/search?q=gold%20price%20kolkata');
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML($contents);
        libxml_clear_errors();

        $div_contents = $dom->getElementsByTagName('div');
        foreach($div_contents as $element)
        {
            if(str_contains($element->nodeValue, '10g of 24k gold (99.9%)'))
            {
                $prc = substr($element->nodeValue, strpos($element->nodeValue, "10g of 24k gold (99.9%)"), 300);//strpos finds position, substr taking the next 300 characters from the string
                return response()->json(['code'=>200, 'message'=>'Success', 'data'=>$prc], 200);
            }
        }

        return response()->json(['code'=>400, 'message'=>'Not Found', 'data'=>'empty'], 200);
    }

```

O/p:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yasifs7cpumgtmrjdgg1.png)
Postman VS Swagger
Tags: webdev, laravel, api, testing
Published: 2023-04-30 19:18:49


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxqgges5kfhvgsw4ddtw.png)

I will try not to delve into too many details while explaining as much as possible at the same time.

Swagger and Postman are both tools used for testing APIs, but they have significant differences. First, in terms of capabilities, Postman's testing capabilities are much greater in terms of dynamics, such as the existence of environments that include multiple links or the ability to automatically retain tokens between requests, in addition to the automation test feature in it.

However, in terms of functionality, Swagger excels in documentation as it allows you to save responses and their formats for each request.

As for the drawbacks, by default, any request sent by Postman will reset the cache on the server because it sends with the header "cache-control no-cache". On the other hand, Swagger has a caching issue because it does not have "no-cache" in the request header.

When to use caching and when not to is a big topic, but in summary, we do not use caching when there is continuous data updating. We use caching when there is a large amount of data or data that is updated infrequently, such as the plans on the website.

Another disadvantage of Swagger is that the headache is larger because it is code, and with one mistake, it can affect the documentation. On the other hand, a disadvantage of Postman is that you have to send a new collection every time you make changes, except if you have a workspace. After a certain number of users, it becomes paid, unlike Swagger, which is uploaded with the project for free.

Of course, web programmers prefer Postman, while front-end and mobile programmers prefer Swagger because they can pull the response without having to troubleshoot themselves and hit the request, in addition to the order. If the person who created the Postman collection is not organized, Swagger is actually easier for front-end and mobile programmers to understand.
In summary, Swagger and Postman have different strengths and weaknesses that make them suitable for different use cases. This post aims to provide a concise and useful overview of the topic

I tried to summarize the topic in a small post, hoping it would be useful and comprehensive.
That's it!"
link to the Arabic post :
https://lnkd.in/dmUdcmaJ
#testing #laravel #documentation #apitesting #developer #programming #swagger #postman #chatgpt3 #openai #grammarly