teleren/devto huggingface dataset:
PHP - Create your own logger like Monolog PSR-3 Logger Interface
Tags: php, tutorial, laravel, codequality
Published: 2021-11-11 18:21:03

## PHP Logger PSR-3: Logger Interface


Install the standard interfaces for Logger :

```
composer require psr/log
```
### Let's create the class that will extend the AbstractLogger
```php
<?php

namespace DevCoder\Log;

use DevCoder\Log\Handler\HandlerInterface;
use Psr\Log\AbstractLogger;

class Logger extends AbstractLogger
{
    protected const DEFAULT_DATETIME_FORMAT = 'c';

    /**
     * @var HandlerInterface
     */
    private $handler;

    public function __construct(HandlerInterface $handler)
    {
        $this->handler = $handler;
    }

    public function log($level, $message, array $context = array())
    {
        $this->handler->handle([
            'message' => self::interpolate((string)$message, $context),
            'level' => strtoupper($level),
            'timestamp' => (new \DateTimeImmutable())->format(self::DEFAULT_DATETIME_FORMAT),
        ]);
    }

    protected static function interpolate(string $message, array $context = []): string
    {
        $replace = [];
        foreach ($context as $key => $val) {
            if (is_string($val) || method_exists($val, '__toString')) {
                $replace['{' . $key . '}'] = $val;
            }
        }
        return strtr($message, $replace);
    }
}
```
### We create a interface for handlers
```php
<?php

namespace DevCoder\Log\Handler;

interface HandlerInterface
{
    public const DEFAULT_FORMAT = '%timestamp% [%level%]: %message%';
    public function handle(array $vars): void;
}

```

### Now we create a handler
```php
<?php

namespace DevCoder\Log\Handler;

class FileHandler implements HandlerInterface
{
    /**
     * @var string
     */
    private $filename;

    public function __construct(string $filename)
    {
        $dir = dirname($filename);
        if (!file_exists($dir)) {
            $status = mkdir($dir, 0777, true);
            if ($status === false && !is_dir($dir)) {
                throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s"', $dir));
            }
        }
        $this->filename = $filename;
    }

    public function handle(array $vars): void
    {
        $output = self::DEFAULT_FORMAT;
        foreach ($vars as $var => $val) {
            $output = str_replace('%' . $var . '%', $val, $output);
        }
        file_put_contents($this->filename, $output . PHP_EOL, FILE_APPEND);
    }
}
```

**How to use ?**
```php
<?php

$logFileName = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log';

$handler = new \DevCoder\Log\Handler\FileHandler($logFileName);
$logger = new \DevCoder\Log\Logger($handler);

$logger->log(\Psr\Log\LogLevel::EMERGENCY, 'an error has occurred'); 

```

Ideal for small project
Simple and easy!
[https://github.com/devcoder-xyz/php-logging](https://github.com/devcoder-xyz/php-logging)
Creating custom TypeORM Operators
Published: 2021-11-11 18:14:11

---
title: Creating custom TypeORM Operators
published: true
date: 
tags: 
canonical_url: https://joeflateau.net/posts/creating-custom-typeorm-operators
---

I spent an hour or two today trying to create a custom TypeORM `FindOperator`. I found a few results searching Google but all of them seem to be outdated and don’t work with the current release of TypeORM. Ultimately the solution was so easy, almost too easy.

I wanted to create a TypeORM operator for the [Postgres Regex Match Operator](https://www.postgresql.org/docs/9.3/functions-matching.html#FUNCTIONS-POSIX-TABLE). My first approach was to subclass FindOperator and override `toSql` which seems to now be called `getSql`. But that did not work (seems TypeORM ignores that now and builds the query based on the `type` property instead.) That’s probably the right thing to do because it allows them to implement operators differently based on the type of database TypeORM is connecting to. But that doesn’t help me, I just need PostgreSQL. So without further ado, here’s my solution:

```
import { Raw } from "typeorm";

let uid = 0;
export function RegexMatches(regex: string) {
  const paramId = `regex${uid++}`;
  return Raw((pathAlias: string) => `${pathAlias} ~ :${paramId}`, {
    [paramId]: regex,
  });
}

```

Yep, just wrap the `Raw` operator and output the condition that you want to match. In my case, the `~` Regex (case sensitive) Match operator. TypeORM escapes the path alias for you and your regex is passed as a parameter, so no problems with SQL injection here if your regex is built dynamically. The parameter name used must be unique if we want to use the operator more than once in a query, so we’ll create a unique id for that.
GitHub Actions Hackathon 2021 - Hosting an Angular application on GitHub Pages using GitHub Actions
Tags: actionshackathon21, github, opensource, angular
Published: 2021-11-11 18:05:49

### My Workflow

I created this workflow to deploy an application example built with Angular 12 on [GitHub Pages](https://pages.github.com/).


### Submission Category: 

DIY Deployments


### Yaml File

```yaml
name: GitHub Pages

on:
  push:
    branches:
    - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Setup Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '16'

    - name: Install dependencies
      run: npm install

    - name: Run tests
      run: npm run test:headless

    - name: Build
      run: npm run build:prod

    - name: Deploy
      if: success()
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: dist/angular-github-actions
        enable_jekyll: true
```


### Link to Code

{% github https://github.com/rodrigokamada/angular-github-actions/ %}


### Additional Resources / Info

This tutorial was posted on my [blog](https://rodrigo.kamada.com.br/blog/hospedando-uma-aplicacao-angular-no-github-pages-usando-o-github-actions) in portuguese and on the [DEV Community](https://dev.to/rodrigokamada/hosting-an-angular-application-on-github-pages-using-github-actions-5ag8) in english.
Free eBook for React Optimization and Development Resources
Tags: react, webdev, beginners, javascript
Published: 2021-11-11 18:04:28

![ebook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/er0vbdeoxdm5dp5qo2xv.png)

**ReactJS Optimization Techniques and Development Resources** ebook helps you to optimize your React App during the development stage using some open-source packages and avoid unexpected issues during production 🚀.

This also has a number of React development resources for

1. **10+ Hosting** services

2. **10K Plus** Open source UI Components List and

3. **15+ Custom Hooks** to fasten your development.

Grab your Copy now on **[Gumroad](https://nilanth.gumroad.com/l/NYkdN)**.

**Grab your free copy now**

Get more updates on [Twitter](https://twitter.com/Nilanth).

## Blogs

1. [How to Structure Your React Redux App](https://dev.to/nilanth/how-to-structure-your-react-redux-app-4d24)
2. [How to Reduce React App Loading Time By 70%](https://dev.to/nilanth/how-to-reduce-react-app-loading-time-by-70-1kmm)
3. [Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support](https://dev.to/nilanth/build-a-portfolio-using-next-js-tailwind-and-vercel-4dd8)
4. [No More ../../../ Import in React](https://dev.to/nilanth/no-more-import-in-react-2mbo)
5. [10 React Packages with 1K UI Components
](https://dev.to/nilanth/10-react-packages-with-1k-ui-components-2bf3)
6. [5 Packages to Optimize and Speed Up Your React App During Development](https://dev.to/nilanth/5-packages-to-optimize-and-speed-up-your-react-app-during-development-4h5f)
7. [How To Use Axios in an Optimized and Scalable Way With React](https://dev.to/nilanth/how-to-use-axios-in-an-optimized-and-scalable-way-with-react-518n)
8. [15 Custom Hooks to Make your React Component Lightweight](https://dev.to/nilanth/15-custom-hooks-to-make-your-react-component-lightweight-17cd)
9. [10 Ways to Host Your React App For Free](https://dev.to/nilanth/10-ways-to-host-your-react-app-for-free-27ga)
10. [How to Secure JWT in a Single-Page Application](https://dev.to/nilanth/how-to-secure-jwt-in-a-single-page-application-cko)
Management and the Future of AI with Azure's CTO
Tags: ai, azure, cloud, techtalks
Published: 2021-11-11 17:51:23

{% spotify spotify:episode:5a7inFgjcw1ea5rDBNZqXg %}

Has your entire career ever hinged on a single moment? For Darren Dillon, free beer in college set him on the path to a computer science degree and eventually a wildly successful career at Microsoft.

Today, as the CTO of Azure and AI at Microsoft Industry Solutions, Darren leads an impressive team of over 130 engineers and is at the forefront of cloud computing and AI technology.

Listen to Darren as he discusses his management philosophy, why he believes status reports are overrated, how to best think about building products for your end user and the implications of the GDPR on the future of AI.

## Episode Highlights Include:
* What GDPR means for the future of AI
* Why managers shouldn't believe status reports
* How "real people" use computers
* Advice for setting boundaries when working with close friends
* The future of cloud computing and Azure

## Join the Dev Interrupted Community
With over 2000 members, the Dev Interrupted Discord Community is the best place for Engineering Leaders to engage in daily conversation. No sales people allowed. [Join the community >>](https://discord.com/invite/devinterrupted)

![https://discord.com/invite/devinterrupted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdkw3dauehushxuopkb8.png)
Tools for generating REST API docs rapidly?
Tags: discuss, webdev, javascript, python
Published: 2021-11-11 17:37:28

So let's assume you have this REST API in whatever foo language, how will you document it if in hurry or you don't want to do complex things just for the sake of it.

Let's have a discussion and share resources (-.-)

PS: It's 11pm here so I may be on sleep mode after some time.
So here is a new Gatsby, Hugo & Jekyll theme (-.-) 🔥🔥
Tags: webdev, gatsby, javascript, opensource
Published: 2021-11-11 17:28:06

>I'm posting this after a long time, I think a year maybe. So making the comeback with creating some themes and sharing FOSS side projects that I created for myself.

So first one in the list is this Gatsby theme.
Actually, I created this theme first for Jekyll then Hugo and then for Gatsby.

## How it looks

![](https://raw.githubusercontent.com/sharadcodes/gatsby-theme-serial-programmer/main/screenshots/blog.png)


Here are all the repository links:

### [Gatsby Theme Serial Programmer](https://github.com/sharadcodes/gatsby-theme-serial-programmer)
[Live Demo](https://gatsby-theme-serial-programmer.vercel.app/)

### [Jekyll Theme Serial Programmer](https://github.com/sharadcodes/jekyll-theme-serial-programmer)
[Live Demo](https://sharadcodes.github.io/jekyll-theme-serial-programmer/)

### [Hugo Theme Serial Programmer](https://github.com/sharadcodes/hugo-theme-serial-programmer)
[Live Demo](https://sharadcodes.github.io/hugo-theme-serial-programmer/)

Wait for other side projects in next post.

Thank you for reading (-.-)
Github copilot demo
Tags: codex, openai, githubcopilot, github
Published: 2021-11-11 17:18:10

You can try out github copilot on vscode. You can try the below commands after getting access to github copilot. You can sign up now.

The demo link is : https://youtu.be/-dSQ1DTWRVs


TypeScript
----------
#!/usr/bin/env ts-node

import { fetch } from "fetch-h2";

// Determine whether the sentiment of text is positive
// Use a web service


Python
------

import datetime

def parse_expenses(expenses_string):
    """Parse the list of expenses and return the list of triples (date, value, currency).
    Ignore lines starting with #.
    Parse the date using datetime.
    Example expenses_string:
        2016-01-02 -34.01 USD
        2016-01-03 2.59 DKK
        2016-01-03 -2.72 EUR
    “""

Go Lang
--------------
package main

type Run struct {
    Time int // in milliseconds
    Results string
    Failed bool
}

// Get average runtime of successful runs in seconds


Javascript
------------

function calculateDaysBetweenDates(date1, date2) {



Go Lang
----------
package main

// Simple HTTP server that accepts a user's name and responds with a greeting


Java
-------
/** A Person class with name and age accessors and equals and hashCode. */
1 line of code: How to merge two Arrays and clean all duplicate entries
Tags: javascript, webdev, performance, codequality
Published: 2021-11-11 17:03:54

```javascript
const mergeArrayUnique = (a, b) => [...new Set([...a, ...b])];
```
Returns a new Array which contains all the values of the two Arrays. Ensures that the new array contains only unique values. Works only for primitive values (string, number, bigint, boolean, undefined, symbol, and null).

--- 


#javascript #webdev #productivity #codequality

---

## The repository & npm package

You can find the all the utility functions from this series at [github.com/martinkr/onelinecode](https://github.com/martinkr/onelinecode)
The library is also published to [npm as @onelinecode](https://www.npmjs.com/package/@onelinecode/onelinecode) for your convenience.

The code and the npm package will be updated every time I publish a new article.

---

Follow me on [Twitter: @martinkr](http://twitter.com/_martinkr) and consider to [buy me a coffee](https://www.buymeacoffee.com/martinkr)

Photo by [zoo_monkey](https://unsplash.com/@zoo_monkey) on [Unsplash](https://unsplash.com/s/photos/fuji)

---
Great Resources for Learning Java in 2021
Tags: java, programming, webdev, software
Published: 2021-11-11 16:57:24

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yu8ljz5u4qyxqhm0cx69.png)
#### **1\.** [**Java Video Tutorial by Derek Banas**](https://www.youtube.com/playlist?list=PLE7E8B7F4856C9B19)

This is a massive Java Video Tutorial. It starts with the things that you will need to start writing Java programs. Then it covers the information on Javas primitive data types. It proceeds to declaration statements, expression statements, all the types, and how to convert them. This tutorial starts slow, but by the end, you will be a Java expert.

[More info](https://www.youtube.com/playlist?list=PLE7E8B7F4856C9B19)

#### **2\.** [**Java (Beginner) Programming Tutorials**](https://www.youtube.com/playlist?list=PLFE2CE09D83EE3E28)

This tutorial introduces you to the basics of Java.

[More info](https://www.youtube.com/playlist?list=PLFE2CE09D83EE3E28)

#### **3\.** [**The Java Tutorials by Oracle**](https://docs.oracle.com/javase/tutorial/)

The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. They include hundreds of complete, working examples and dozens of lessons. Groups of related lessons are organized into "trails."

[More info](https://docs.oracle.com/javase/tutorial/)

#### **4\.** [**Object-Oriented Programming with Java**](https://moocfi.github.io/courses/2013/programming-part-1/)

This course will teach all the basics of computer programming, algorithms, and object-oriented programming using the Java programming language. The course includes comprehensive course materials and plenty of programming exercises, each tested using our automatic testing service Test My Code.

[More info](https://moocfi.github.io/courses/2013/programming-part-1/)

#### **5\.** [**Intro to Java Programming**](https://www.udacity.com/course/java-programming-basics--ud282)

This course will provide you with a basic foundation in Java syntax, the first step towards becoming a successful Java developer. You'll learn how computers make decisions and how Java keeps track of information through variables and data types. You'll learn to create conditional statements, functions, and loops to process information and solve problems. You'll even learn to use IntelliJ, a Java IDE (Integrated Development Environment) that professional developers use to build, compile, and debug your code. These are foundational programming skills, and mastering them is a must for all aspiring programmers. This course is the first in our Java Programming course series. After you complete this course, you'll be ready to take Object Oriented Programming in Java.

[More info](https://www.udacity.com/course/java-programming-basics--ud282)

‍*Originally posted at* [*raftlabs.co*](https://raftlabs.co/development/top-free-resources-to-learn-java?utm_source=devto&utm_campaign=crosspost)
Beginners socket.io code without cors error XD
Tags: javascript, beginners, websockets, webdev
Published: 2021-11-11 16:54:51

extensions required: live server that's all.

I am going to assume that you already have previous programming knowledge and that you have tried to use socket.io and for any reason it has not worked for you, so I will share you the code that I used to make my first socket and that it worked especially for the problem of cors.

to our blank project create the following files
![files to create our first websocket](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob8kt82wrr2b7vhatoxq.png)

launch a new project with `npm init -y` command it creates a file package.json then run `npm i nodemon socket.io` and add line 9 on your package.json file that will use nodemon with server.js
![package.json file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7lldadq4legucza7z6z.png)

add the following code to server.js file, usually live server use 5500 port,line 4 is where you give permission to connect...
![server.js file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhqviiflphgchx267qon.png)

else it'll deny you access  and will throw cors error

![cors error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8a32oel8gjzhzxw49aa1.png)

index.js
![index.js file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7gf17hroln5dbj8sr2ao.png)

html file
![html file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1dxauaa3vo9vwi8o1095.png)


once you have all we seen run `npm run serve` and console will show init server, then on html file open live server open console and will show...
![console will show init server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5tt701o5elmfmf3cqclj.png)


now that it works you have the basic to begin on websockets, finally you have to search more and better info to make upgrade your code

feel free to feedback

and there you go, my first basic beginners socket.io post
How to test your GitHub Actions locally
Tags: github, actionshackathon21, tutorial
Published: 2021-11-11 16:48:03

So Dev & GitHub Team just announced the Github Action Hackathon. I am also participating in it. But I ran into a troublesome problem, and I think some of you guys are too. That is **we always have to push the files to the remote repo in order to test the action, But it is a kinda pain to do it every time you make a change**. I finally have found a solution to this problem.

![](https://c.tenor.com/mRsNLeYI_qIAAAAC/only-one-alone-there-can-be-only-one.gif)

# [Act](https://github.com/nektos/act) the solution
> "Think globally, act locally"

The two important reasons that you should use Act:

* **Fast Feedback** - Rather than having to commit/push every time you want to test out the changes you are making to your .github/workflows/ files (or for any changes to embedded GitHub actions), you can use act to run the actions locally. The environment variables and filesystem are all configured to match what GitHub provides.
* **Local Task Runner** - I love make. However, I also hate repeating myself. With act, you can use the GitHub Actions defined in your .github/workflows/ to replace your Makefile!

> I copied them from [Act's readme](https://github.com/nektos/act), Because I am lazy

[Act](https://github.com/nektos/act) is pretty reliable for testing actions, And I can go into details but I would be just repeating the stuff that is already on [Act's Readme](https://github.com/nektos/act). So if you want deeper dive then you can check [Act's Repo](https://github.com/nektos/act).

I hope you guys can figure everything else yourselves, as I am also busy making my project for this hackathon. But I felt an urge to tell others about this amazing tool.

Have a good day, Best of luck!
Rajvir Singh
A better Linux gaming distro guide
Tags: linux, gaming
Published: 2021-11-11 16:37:56

## Introduction

I watched [this video](https://youtube.com/watch?v=0506yDSgU7M) by Linus Tech Tips, and decided to improve on his criticisms to hopefully create a better guide to choosing your Linux gaming distro.

## Basics

These are some common terms to know: 

* DE/Desktop Environment: This is the GUI interface to your OS.
* Terminal/TTY/Command Line: This is the text based interface to your OS.

## Note

As Linux is Free and Open Source Software, you can customize anything and everything you want on any distro. However, as this is a beginner focused guide, it mostly focuses on what is built in to a distro, not what is possible with a distro.

## [POP!_OS] (https://pop.system76.com/)

This distribution is simple to use, has a nice DE, and generally doesn't get in your way. The breakage caused while installing linux in Linus' video is something that is trivial to fix. You can expect it to have been fixed very soon after this guide is published, and even if it is not, you can open the terminal in POP!_OS by clicking on the terminal icon in the dock and just run

```bash
sudo apt-get install steam
```

### The NVidia Problem
NVidia has proprietary graphics drivers for linux which are a pain to get working. For this reason, if you have an NVidia card, I recommend just going with [POP!_OS](https://pop.system76.com/) as it has an image with NVidia drivers preinstalled. The rest of this guide will be focused on AMD users, or NVidia users who are willing to install drivers manually. If you are not one of these, you should skip to 'What after the distro?'

## [Linux Mint] (https://linuxmint.com/)

This distribution is also simple to use, has a nice DE that mirrors Windows. There is very little difference between it and POP!_OS other than the latter having a seperate NVidia image. It is mostly just personal preference.

## What after the distro?

Wasn't that short! The reason I only covered these two distributions is that there is very little difference between most distributions, much more so when gaming is concerned. What is more important is what software you install on that distro, and for this reason, the bulk of this guide will be focusing on these.

### Wine and Proton

Simply put, these are softwares which make Windows games run on Linux. As an end user, you do not need to know more than this, just google instructions on how to install these for your distro, and you're good

### Lutris

Consider Lutris as an all-in-one game launcher. It can manage your steam and non steam games from a single interface. It is dead simple to use, and you should be able to just google instructions on how to install it and be good to go.

### Chimera

Chimera is a really nice tool for managing ROMs for, say, consoles. It is a bit involved to setup, but nothing you can't figure out by googling.

# Other Resources

* [A Gamer's guide for switching to Linux](https://youtube.com/watch?v=y8ii1qV2J6c)
* [Getting started with Lutris](https://youtube.com/watch?v=6S8zsfqsgfw)