teleren/devto huggingface dataset:
How To Convert PHP Array To JSON Object
Tags: php, javascript, programming, codenewbie
Published: 2021-10-01 03:10:33

In this example I will show you how to convert PHP array to JSON object, We will convert php array into json string using json_encode() function.The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.

Many times we require to convert PHP array into json array in php or laravel application. When you are working with ajax request at that time you need to send json response because we can get json data easily .

Here, I will 3 diffrent examples of how to convert php array to JSON object with output, Also we can force convert json object using "JSON_FORCE_OBJECT" parameter.


> Example 1 : 
 
```
<?php
  
  $colors = ['Red', 'Green', 'Blue'];
  
  $colorsJSON = json_encode($colors);
  
  echo $colorsJSON;
  
?>
```

Output :

```
["Red","Green","Blue"]
``` 

> Example 2 : 
 
```
<?php
  
  $colors = ['Red', 'Green', 'Blue'];
  
  $colorsJSONObject = json_encode($colors, JSON_FORCE_OBJECT);
  
  echo $colorsJSONObject;
  
?>
```

Output :  

```
{"0":"Red","1":"Green","2":"Blue"}
``` 

> Example 3 : 
 
```
<?php
  
  $address = ['city'=>'Delhi', 'place'=>'Red Fort'];
  
  $jsonData = json_encode($address);
  
  echo $jsonData;
     
?>
```

Output :

```
{"city":"Delhi","place":"Red Fort"}
```

I have added 3 examples for your references, you can use anyone as per your requirments. 

---

You might also like :

- [Read Also : How To Create Dependent Dropdown In Laravel](https://techsolutionstuff.com/post/how-to-create-dependent-dropdown-in-laravel)
- [Read Also : Laravel AJAX CRUD Example Tutorial](https://techsolutionstuff.com/post/laravel-ajax-crud-example-tutorial)
- [Read Also : How To Add Summernote Editor In Laravel 8](https://techsolutionstuff.com/post/how-to-add-summernote-editor-in-laravel-8)
- [Read Also : Laravel 8 Google Recaptcha Example](https://techsolutionstuff.com/post/laravel-8-google-recaptcha-example)
September 30th, 2021: What did you learn this week?
Tags: weeklylearn, discuss, weeklyretro
Published: 2021-10-01 02:45:15

It's that time of the week again. So wonderful devs, what did you learn this week? It could be programming tips, career advice etc.

<center>

![Yoda wooping someone's butt](https://media.giphy.com/media/yDYAHbqe5DfyM/giphy.gif)
</center>

Feel free to comment with what you learnt and/or reference your TIL post to give it some more exposure.

{%tag todayilearned %}

<!--
And remember, if something you learnt was a big win for you, then you know where to drop it as well.👇👇🏻👇🏼👇🏽👇🏾👇🏿

{%link https://dev.to/devteam/what-was-your-win-last-week-4f0n %}

<center>

![Little kid making a fist as if to say "Yes!"](https://media.giphy.com/media/6brH8dM3zeMyA/giphy.gif)
</center>
-->
EduRecordApp Lesson 1 (Database Design And Starting WASM App Generation)
Tags: blazor, webassembly, appgeneration
Published: 2021-10-01 02:21:22

BLAZOR WASM guided lesson/instruction provided to one of my proteges.

Source code for this lesson can be downloaded from  {% github benjaminsqlserver/GodsWillEduRecord %}

Watch Lesson Video Here {% youtube gTqCW8GSwro %}
How to send message to specific discord channel from your server application?
Tags: node, discord, webhook
Published: 2021-10-01 02:07:34

---
title: How to send message to specific discord channel from your server application?
published: true
description: Send message from your app to discord
tags: nodejs, discord, webhook
---

#### How to send message to specific discord's channel from your server application?

Had you wonder how to send the log / messages from the server application to discord channel? In my personal poject I use `NodeJs` for the server side, each of the important details from the server will be sent to my discord's channel. For instance, each time my user made a payment or register for my app. I am about to demonstrate how exactly I did it.

I use the ES6 dicipline for my application.

Packages I will be using are `axios`, and `nodemon`.

1. Initiate a project by `npm init -y`.
2. get the webhok url by going to your channel's settings -> integration -> create webhook.
3. start coding.

In this case I will use the method of HTTP POST request to the webhook.
As in `bash` you can simply do :

```bash
#!/bin/sh
url = "thewebhookurl"

curl -H "Content-Type: application/json" -X POST -d '{"content":"'"YOUR WHAT EVER MESSAGE "'"}' $url

```

but in `nodejs`,

```javascript

 log(msg) {
        let webhook_url = 'thewebhoooklink';

        let params = {
            username: 'ABC',
            content: msg,
        };

        return axios({
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: JSON.stringify(params),
            url: webhook_url,
        });
    }
```

and it should work but calling the function `log('something something');`

or YOu can user my package here https://www.npmjs.com/package/discord-logger-js

HAPPY CODING!

{% youtube IDTNZdo-fqU %}
Branches and merges
Tags: opensource, git
Published: 2021-10-01 02:01:02

## Introduction

This week on my journey through open-source, I continued to dive deeper into Git by practising creating branches and merging them back to `main`.

## New features

In my [static site generator, MINI](https://github.com/mqnguyen5/mini-ssg), I decided to implement 2 new features and created different branches for each of them:

- Add [extra support for markdown](https://github.com/mqnguyen5/mini-ssg/issues/11)
- Add [`--lang`](https://github.com/mqnguyen5/mini-ssg/issues/10) to the list of available command-line options

## Implementation

Coding the new features were quite simple. For the `lang` flag, I just added an additional `option` object with the following properties:

```js
l: {
    alias: "language",
    desc: "Language used when generating HTML",
    type: "string",
},
```

The value of the newly added option would then be passed to each of the `processInput` and `generateHTMLFile` function to specify the language of the generated HTML file(s).

As for supporting Markdown's inline code `` ` `` syntax, I used regex to check for any instance of text enclosed with back-ticks and rendered them into HTML `<code>` blocks: 

```js
.replace(/`(.*?)`/gim, "<code>$1</code>") // replaces single backtick-enclosed text -> <code>content</code>
```

## Resolving issues

While I had no trouble merging [issue #11](https://github.com/mqnguyen5/mini-ssg/commit/70f498bda3d6092dbb1ca09098e7991e83d545e7) as it was simply a fast-forward merge, I ran into some problems when it comes to [issue #10](https://github.com/mqnguyen5/mini-ssg/commit/17156c7ecd3b8eb20717a902a1802e2e771d56b2).

As it turns out, I mistakenly updated the content of `mini-ssg.js` in both my `main` and `issue-10` branch, resulting in a conflict when I tried to perform the merge. I had to backtrack to find out where I made the changes and modified one of them to match the other.

## Final thoughts

Through this experience, I had got a better grasp of how `branches` and `commits` connect to one another and the importance of checking for conflicts before merging. I also discover that while using `git diff` in the command line allows you to quickly review changes, in the case when the programmer modifies a large amount of content, using a text editor like VSCode will make the process much simpler as you can see the differences side by side.

Cover image by [Yancy Min](https://unsplash.com/@yancymin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/git?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
django-environ with Lists Environment Varibles in .env Files
Tags: django, python, environment, config
Published: 2021-11-17 10:00:49

---
title: django-environ with Lists Environment Varibles in .env Files
published: true
date: 2021-10-01 00:00:00 UTC
tags: django, python, environment, config

canonical_url: https://tech.serhatteker.com/post/2021-10/django-environ-list/
---

## Issue

[django-environ] is the Python package that allows you to use [Twelve-factor methodology] to configure your Django application with environment variables.

It is very usefull package although there are some missing things in the documentation like how we use `list` as an environment variable?

They got doc for `nested list` but not for `normal/raw list`.

One of the main case for using `list` would be `ALLOWED_HOSTS`.

Let's assume we have hosts in our `settings.py`:

```python
# settings.py
...

ALLOWED_HOSTS = [
    "example.com",
    "awesomedomain.com",
    "stagingdomain.com",
    "10.0.0.2",
    "198.162.44.72",
]
```

How can we move this hardcoded `list/array` to an `.env` file and use it with `django-environ`?

## Solution

First add `env.list` to your `settings`:

```python
# settings.py
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")

```

Then add your hosts with comma separated into `.env` which located in the *root* of your project or a proper location;

```env
# .env
...

ALLOWED_HOSTS=example.com,awesomedomain.com,stagingdomain.com,10.0.0.2,198.162.44.72
```

### Extra

Your environment variables file —`.env`, can be anything and anywhere —`.envs/.local`, `.env.prod`, as long as you configure it properly in your settings:

```python
# settings.py
import os

import environ

# Set the project base directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Initiate related env class
env = environ.Env()
# Take environment variables from .env.dev file
environ.Env.read_env(os.path.join(BASE_DIR, '.env.dev')

...
```


All done!




[django-environ]: https://django-environ.readthedocs.io/en/latest/index.html
[Twelve-factor methodology]: https://www.12factor.net/
Serverless API with Java and Redis
Tags: serverless, java, redis, aws
Published: 2021-09-30 23:48:42



In this tutorial, we will build a stateful serverless API using Java and Redis on AWS Lambda. The API will simply count the page views and return it as http response.


### Prerequisites



* Install node and npm
* Install the Serverless Framework installed with an AWS account set up.
* Install JDK and not Java JRE. Set your JAVA_HOME.
* Install Apache Maven.
* Create a free Serverless Redis database from [Upstash](https://console.upstash.com) as described [here](https://docs.upstash.com/).


### Project Setup



* Create the project:

serverless create --template aws-java-maven --name serverless-api-java-redis -p serverless-api-java-redis



* Add jedis as dependency to the pom.xml:

    ```xml
    <dependency>
       <groupId>redis.clients</groupId>
       <artifactId>jedis</artifactId>
       <version>3.6.0</version>
    </dependency>
    ```


* Update serverless.yml adding an http endpoint as below:

```
functions:
 hello:
   handler: com.serverless.Handler
   events:
     - httpApi:
         path: /hello
         method: get
```



### The Code

Update Handler.java as below:


```java
package com.serverless;

import java.util.Map;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import redis.clients.jedis.Jedis;

public class Handler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
  @Override
  public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
     Jedis jedis = new Jedis("us1-lasting-lion-32618.upstash.io", 32618, true);
     jedis.auth("d5033b46dfbgheb6718f9dbbd2925");
     Long value = jedis.incr("counter");
     String message = "Hello World, Count:" + value;
     return ApiGatewayResponse.builder()
           .setStatusCode(200)
           .setObjectBody(message)
           .build();
  }
}
```




In the above code, you need to replace your Redis endpoint and password. You can copy Jedis connection code from the [Upstash console](https://console.upstash.com).


### Deploy and Run

First build your project with `mvn clean install`. Then deploy to AWS with `serverless deploy`. The last command will output the endpoint URL as below:

```shell

Serverless: Stack update finished...

Service Information

service: serverless-api-java-redis

stage: dev

region: us-east-1

stack: serverless-api-java-redis-dev

resources: 11

api keys:

  None

endpoints:

  GET - https://60tinzba0a.execute-api.us-east-1.amazonaws.com/hello

functions:

  hello: serverless-api-java-redis-dev-hello

layers:

  None

```
TDD Conference 2021 - How TDD sensitized me to speed as a regular workplace habit? - Ragunath Jawahar
Tags: oop, tdd, opensource, programming
Published: 2021-09-30 23:05:02

First International Test Driven Development took place on July 10th. 

In this series, I will include every talk together with my notes and further reading.

Hopefully, a lot of readers will watch and rewatch the talks, as they are worth several reviews.

Let's continue...

## Bio 

Ragunath has consulted organizations like Gojek, Dunzo, Tiffany & Co., Mizuno, etc., for a decade. He stabilizes fast-growing teams and reclaims codebases that teams are afraid to change. He is a fan of fast feedback cycles and also believes that you are only as good as the team you build.
 
> TL;DR: Short feedback loops should fail fast, grab attention and suggest corrective actions

## Talk

{% youtube q_7JDwZY8II %}

# My Personal notes

-  On a good feedback loop, the system tells you when something is not right.
- They help us catch mistakes early on.
- Good feedback loops are not as good as feedback loops telling you something is wrong.
- Negative Feedback loops help experiment much faster and figure out small solutions
- IDEs shorten feedback loops
- We must shorten the latency between the action and the consequence
- IDEs with excellent feedback guide through available options
- We classify stimulus under (Latency, Attention and Response)
- Grammar.ly works in the same way, shortening feedback loops
- UIs are very difficult to unit test
- Excellent feedback loops should fail fast, grab attention and suggest a corrective action
- improve feedback cycles measuring cost-benefits

>  The only way to go fast is to go well

_Robert Martin_

# Speaker Links

- Twitter [@ragunathjawahar](https://twitter.com/ragunathjawahar) 
- LinkedIn [@ragunathjawahar](https://www.linkedin.com/in/ragunathjawahar//) 
- Site [https://www.ragunath.xyz/]https://www.ragunath.xyz/) 
 
* * *

Please follow TDD Conference on:

- [YouTube](https://www.youtube.com/channel/UCKn-DadPoyYssfAOMk1LSew)
- [Twitter](https://twitter.com/tddconf)
You MUST use the useCallback hook!
Published: 2021-09-30 16:52:15

Hi everyone! My name is Itay and I’m a fullstack developer who specializes in back-of-the-frontend React.js code.

In this shot, I’ll show you the usages of the `useCallback` hook for better performance of your application, and explain why you should use it.

For a start, let’s look at this code:
```jsx
export function MyComponent () {
    const [numericState, setNumber] = useState(0);
    const handleClick = () => {
        setNumber(x => x%2 +1);
    }
    return (
        <>
        <button onClick={handleClick}>Click Me</button>
        {numbericState}
        </>
    )
}
```

What’s wrong with this code? It’s not completely optimized. The handle click function is changing on every render!

That would be the equivalent of writing the following class based component:

```jsx
export default class MyComponent extends React.Component {
  state: {
    numericState: 0
  }
  render() {
    const handleClick = () => {
        this.setState(({ numericState }) => ({ numericState: numericState%2 +1 }));
    }
    return (
        <>
          <button onClick={handleClick}>Click Me</button>
          {this.state.numbericState}
        </>
    )
  }
}
```

This, of course, is ridiculous. A better practice would be to write your class-based component in the following way:


```jsx
export default class MyComponent extends React.Component {
  state: {
    numericState: 0
  }
  handleClick = () => {
    this.setState(({ numericState }) => ({ numericState: numericState%2 +1 }));
  }
  render() {
    return (
        <>
          <button onClick={this.handleClick}>Click Me</button>
          {this.state.numbericState}
        </>
    )
  }
}
```

The question is, how to you write it in a functional approach? This is what hooks are made for. Let’s see how we can write the functional component in an optimized way:

```jsx
export function MyComponent () {
    const [numericState, setNumber] = useState(0);
    const handleClick = useCallback(() => {
        setNumber(x => x%2 +1);
    }, []); // works exactly like useEffect
    return (
        <>
        <button onClick={handleClick}>Click Me</button>
        {numbericState}
        </>
    )
}
```

REMEMBER: Not using the useCallback hook = writing everything in you render function!

You can see a complex back-of-the-frontend React.js app I've recently built [here](https://github.com/itays123/partydeck/tree/main/game/src)
I'm mergin here
Tags: opensource
Published: 2021-09-30 22:49:45

This week's lab was a good one, very functional learning regarding git merges which cleared up some things I hadn't worked out about github. 

Last week when merging [my partner's repo](https://github.com/joshuali7536/LennahSSG) we encountered an issue where several files were in conflict. We opted to delete the conflicting files on his end to allow the merge, rather than going through line by line and seeing what was different and he kept backups so as to reintroduce any code that was cut if he so chose. 

This week was a good way to see what the process of doing proper line by line comparison looks like, with two branches being merged one after the other. First, I logged issues for [more relevant return codes](https://github.com/gusmccallum/GAS-ssg/issues/17) and [markdown horizontal rule syntax.](https://github.com/gusmccallum/GAS-ssg/issues/18)

I then created branches for the respective issues, and wrote out the code for each change. One by one, I merged the branches to the main branch, with the second of course causing issues. I use github desktop and it made it very intuitive to open up an IDE and get line by line highlights with breakdowns of what was from each branch. I sorted out which changes were going through, saved, and merged. First the [return code branch](https://github.com/gusmccallum/GAS-ssg/commit/36925e8b21f48e02696b0bfd5e4728c7943e454f) and then the [horizontal rule branch.](https://github.com/gusmccallum/GAS-ssg/commit/b83b76851e61379f185db46a580dcd6f5a3f8519)

It all went very smoothly, although I didn't test before I merged the branches and ended up having to push [a fix](https://github.com/gusmccallum/GAS-ssg/commit/161adf057479efcfee98a50ad7a8815b73c5cc99) to the main branch to get everything working afterward, but that was unrelated to this week's changes.
WebdriverIO Automation Protocol State of Confusion
Tags: webdriverio, testing, chrome, edge
Published: 2021-09-30 21:58:13

I'm still somewhat of a WebdriverIO noob and I learned an important lesson this week. WebdriverIO supports two different automation protocols, Webdriver and Devtools and they can behave differently! Here's a [link](https://webdriver.io/docs/automationProtocols) to the WebdriverIO doc for more details.

1) Using Webdriver. [Webdriver](https://w3c.github.io/webdriver/) is the older Selenium protocol and uses a middle man browser specific driver to drive the browser. It's very good for cross browser testing support. 

**How to use it in WebdriverIO:** If you specify to use a service that updates browser drivers in your wdio.conf.js file you are most likely using Webdriver. For example:

```
  // Test runner services
  // Services take over a specific job you don't want to take care of. They enhance
  // your test setup with almost no effort. Unlike plugins, they don't add new
  // commands. Instead, they hook themselves up into the test process.

  services: ['chromedriver', 'edgedriver'],

```
These services are all added via NPM packages. 'Selenium-Standalone' is another driver service. 

2) Using Devtools: [Devtools](https://github.com/WICG/devtools-protocol/) was developed with Chrome as an API to drive a browser directly without a specific driver. It also uses Puppeteer to drive the browser. 

**How to use it in WebdriverIO:** If you don't specify to use a service in wdio.conf.js than you will default to using Devtools. Yes this confused the heck out of me because I was using the *chromedriver* service (aka Webdriver) for running Chrome and just specifying 'MicrosoftEdge' for a browser Capability which defaulted to using Devtools. If you look at the runtime logs you can see what WebdriverIO is using:

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

**So what protocol do you want to use?** Well I found out that Devtools doesn't support all WebdriverIO commands including *browser.maximizeWindow( )*. To keep the peace on my automation team I used Webdriver for all browsers. Also Devtools might not have the best cross browser support. But it does seem to be the future of browser automation and supports some pretty advanced dev features including network inspection so it might be worth a revisit in the future now that I'm less confused :)
Open frontend roles
Tags: javascript, react, webdev, hiring
Published: 2021-09-30 21:44:27

Recruiting #frontend developers / engineers at @Edvora 


#Fulltime https://www.edvora.com/careers/E01
#Internship https://www.edvora.com/careers/E04

Send your applications on careers@edvora.com

Skills and Experience
- 2+ years of experience in frontend development and service integration
- Fluency in Javascript
- Prior experience with NEXT.js and ChakraUI or Tailwind CSS.
- A keen eye for discerning small visual discrepancies
- Familiarity in Agile development environments
- Able to write unit test for own code

The following skills are preferred but not a hard requirement:
- Fluency in Python
- Experience with FastAPI
- Knowledge of CI/CD pipelines and common DevOps workflows

In a nutshell, you will be working with an extension of the *Product Team* where your day-to-day tasks will include *Frontend Development, Service Integration and Product Creation. Most, if not all of these tasks will be using **NEXT.js/ChakraUI/TailwindCSS/Javascript*.
Adding Language Support and More! - The Great Site Generator
Tags: opensource, cpp
Published: 2021-09-30 21:36:19

Along with support for html headers in markdown, the `--lang` flag for [specifying a language](https://github.com/drew5494/the-great-site-generator/issues/12) is now supported! 

Three language tags including English Canada `en-CA`, French `fr` and Brazilian Portuguese `pt-BR` are currently supported with more coming in the near future! 

Other features, such as [more accurate error detection and prevention](https://github.com/drew5494/the-great-site-generator/issues/13) has also been improved. If there are no errors, the program will exit with 0. Otherwise, it will exit with 1 as per C++ standards. 

This was the first time I worked on issues using Feature Branches. I usually just work on my main branch, but I'm aware a lot can go wrong that way!  

I will be working on adding more features soon. If you'd like to contribute, you can fork it on [Github](https://github.com/drew5494/the-great-site-generator)