teleren/devto huggingface dataset:
Cracking the Algorithm Interview
Tags: algorithms, interview, leetcode, datastructure
Published: 2022-12-11 02:46:13

Algorithm interview has become an essential part of pursuing a technical career in the IT world. Lots of beginners or even experienced engineers are struggling with it. In my opinion, they are doing it in the wrong way. I write this series to help people find the right learning path.

People solve algorithm problems in various styles. On one end, people rely on their instinct while on the other end, people reference classic algorithm textbooks. Both are wrong. The questions in the algorithm interview have certain patterns or implicit scopes. They are neither brain teasers nor rocket science.

At a high level, I categorize the required knowledge base in the following way.

1. Data structures: array, linked list, stack/queue, hash table, heap, tree, graph

2. Techniques: math, recursion, sort, search, divide & conquer, dynamic programming.

That is it! In this series, I will dive deep into each area. (Please click the link of each topic)

---

How to practice?

[Leetcode](https://leetcode.com/) is the most popular online coding platform with 1000+ algorithm problems and the number only increases. But remember, not all problems are good problems! In this series, I will talk about the classic ones with which you will be able to solve a number of similar problems or same-pattern problems. That is the whole point.
Virtual Environment (venv) สิ่งสำคัญสำหรับโปรเจค Python
Published: 2022-12-11 02:35:20

"สภาพแวดล้อม" หรือ Virtual environment คือชุดของ Python interpreter และ Package ต่างๆ ที่จำเป็นสำหรับแต่ละ Project นั่นเอง!
(ใน IDE แบบ Pycharm จะสร้าง virtual environment ให้เองทุกครั้งที่สร้างโปรเจคใหม่) และเพื่อให้เวลาที่เราแชร์ environment ให้คนอื่น จะได้ระบุแค่สิ่งที่ต้องใช้ไม่พ่วง libraryที่ไม่ต้องการไปด้วย

วิธีสร้าง venv

```
python3 -m venv <ชื่อ environment>
```
เมื่อเราสร้าง environment แล้วเราต้องทำการ activate ด้วยคำสั่ง

```
Source <ชื่อ environment>/bin/activate
```
เมื่อ activate เสร็จแล้ว สังเกตุใน Terminal จะมีชื่อ environment อยู่ใน(...)นำหน้าคำสั่งของเรา ตัวอย่างนี้ชื่อ evironment ก็คือ env

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/miwsnjahv9hvq1qipsu1.png)
เมื่อเราต้องการจะปิดเราก็สามารถทำได้ด้วยคำสั่ง

```
deactivate
```
เริ่มต้นสร้างโปรเจค Python ด้วย VS Code
Published: 2022-12-11 02:09:27

1. สร้าง โฟลเดอร์ใหม่ เปลี่ยนชื่อเป็นชื่อโปรเจคที่ต้องการ
2. เปิด VS Code
3. open folder เลือกโฟลเดอร์โปรเจคที่สร้างไว้
4. ในหน้าต่าง EXPLORER สร้าง New File เปลี่ยนชื่อ "Main.py"

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

5. ทดสอบ print("Hello World!")

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqbreemmcu8n2exfhsbj.png)
Setting up Laravel Cashier (Managing Subscriptions)
Tags: laravel, cashier, subscriptions, webdev
Published: 2022-12-11 01:58:04

1. Install the Laravel Cashier package by running `composer require laravel/cashier` in your terminal.

2. Add the `Laravel\Cashier\CashierServiceProvider::class` to the providers array in your `config/app.php` file.

3. Run the `php artisan vendor:publish --provider="Laravel\Cashier\CashierServiceProvider"` command to publish the package's configuration file to your application.

4. Add the `Billable` trait to your user model, which will give your users the ability to manage their subscriptions.

5. Add the necessary columns to your users table by running the `php artisan migrate` command.

6. In your user model, define a `plan` attribute that specifies the name of the subscription plan your users can subscribe to.

7. In your application's subscription logic, you can use Laravel Cashier's methods to create subscriptions, manage plans, and handle billing. For example, you can use the `subscription()` method to retrieve the user's current subscription, and the `newSubscription()` method to create a new subscription for the user.

I hope this helps! Let me know if you have any other questions.
Advent of Code Day 10
Tags: adventofcode, elixir
Published: 2022-12-11 01:53:39

### Links

- [Intro](https://dev.to/sethcalebweeks/advent-of-code-2022-in-elixir-34i8)
- [Problem Statement](https://adventofcode.com/2022/day/10)
- [Code](https://github.com/sethcalebweeks/advent-of-code-2022/blob/main/lib/Day10.ex)

### Highlights

- I had a lot of fun with today's puzzle. The CRT idea was brilliant, and it was awesome to be able to play with something visual.
- The code was also relatively straightforward. After parsing all the register instructions, we just needed to play with the output to calculate/reveal the answer.
- The function guard does all the heavy lifting for the second part. It checks to make sure the register value puts the sprite within the index that is currently being drawn using a modulus and a range check.

```elixir
defmodule Day10 do
  use AOC

  def execute("noop", {cycles, register}), do: {cycles ++ [register], register}
  def execute("addx " <> value, {cycles, register}) do
    updated_register = register + String.to_integer(value)
    {cycles ++ [register, updated_register], updated_register}
  end

  def part1 do
    input(10)
    |> String.split("\n", trim: true)
    |> Enum.reduce({[1], 1}, &execute/2)
    |> elem(0)
    |> (&Enum.slice(&1, 19..length(&1))).()
    |> Enum.take_every(40)
    |> Enum.zip(20..220//40)
    |> Enum.reduce(0, fn {register, cycle}, signal -> signal + register * cycle end)
  end

  def part2 do
    input(10)
    |> String.trim
    |> String.split("\n", trim: true)
    |> Enum.reduce({[1], 1}, &execute/2)
    |> elem(0)
    |> Enum.with_index
    |> Enum.map(fn
      {register, position} when register - rem(position, 40) in -1..1 -> "#"
      _ -> "."
    end)
    |> Enum.chunk_every(40)
    |> Enum.map(&Enum.join/1)
  end

end

```
Learning Go
Tags: learning, resources, go
Published: 2022-12-11 01:33:27

Go-lang was created at Google in 2007, at the time of writing this post Go is at version 1.19. I have been learning to program with Go to create AWS Lambdas to offload some admin tasks. 

As I am from a Performance Testing background and have used Loadrunner which uses a C variant compiler I am familiar with some programming practices. However, Go was a whole new world for me.

The following resources I am currently using to aid my learning. This article is aimed at those looking to get into Go programming.

---

Podcast: [Go Time](https://changelog.com/gotime/239) 

"Your source for diverse discussions from around the Go community. This show records LIVE every Tuesday at 3 pm US Eastern. Join the Golang community and chat with us during the show on the #gotimefm channel of Gophers slack. Panellists include Mat Ryer, Jon Calhoun, Natalie Pistunovich, Johnny Boursiquot, Angelica Hill, Kris Brandow, and Ian Lopshire. We discuss cloud infrastructure, distributed systems, microservices, Kubernetes, Docker… oh and also Go! Some people search for GoTime or GoTimeFM and can’t find the show, so now the strings GoTime and GoTimeFM are in our description too."

 I googled learning go and the "Go Times" Go for Beginners episode appeared on the list. The guests on the show highlighted several resources across the web and provided general advice.    

---

Linkedin Learning

A friend advised me earlier this year that you can access Linked Learning for free at the local library. So if your library offers you access to LinkedIn Learning I would recommend [Go Essential Training](Go Essential Training). This is aimed at a beginner level and will teach you how to set up your development environment. Thank you Claire for the tip.

---

[**Exercism**](https://exercism.org/)  

I wanted to use this site as it was recommended by the Go Time podcast. It was above my level at the time. I found the interface confusing but after the first couple of challenges, I started to get into a rhythm. I found it easier to complete the challenges when I pulled the examples of git into my local VScode IDE. 

---

[**Learn Go with Tests**](https://quii.gitbook.io/learn-go-with-tests/) 

As I have a background in testing I found this course to be the most straightforward. It walks you through the TDD process. This involves writing your tests first and then your code. As I had completed the previous courses this course reinforced my learning.  

---

[**Learn X in Y minutes**](https://learnxinyminutes.com/docs/go/)

If you have completed the above courses or you have a knowledge of programming this class is very beneficial for revision. It is nicely laid out on a single page and uses comments to guide you through the various go practices.

---

So hopefully the above suggestions will assist you on your journey. If you are brand new to coding I would recommend looking at a beginner course on git. This will make it easier to manage all the files that you create.

If you know of other materials that could be helpful can you please leave a comment with a link? 

Thank you.

Best of luck 

Is mise

Gallau
Calculating the Exponential Moving Average (EMA) with JavaScript
Tags: javascript, algorithmic, trading, algorithmictrading
Published: 2022-12-11 01:28:27

To calculate the Exponential Moving Average (EMA) with JavaScript, you can use the following formula:

```
EMA = (price(t) * k) + (EMA(y) * (1 – k))

```
where price(t) is the most recent closing price, EMA(y) is the previous period's EMA, k is the weighting factor, and t and y are the current and previous periods, respectively.

Here's an example of how you can implement this formula to calculate the EMA for a given array of closing prices:

```
function calculateEMA(closingPrices, period) {
  const k = 2 / (period + 1);
  let ema = closingPrices[0];
  for (let i = 1; i < closingPrices.length; i++) {
    ema = (closingPrices[i] * k) + (ema * (1 - k));
  }

  return ema;
}

// Example usage
const closingPrices = [100, 110, 105, 115, 120, 130, 140, 150, 145, 155];
const ema = calculateEMA(closingPrices, 12);
console.log(ema); // Output: 119.53

```
This code calculates the EMA for a given array of closing prices by applying the EMA formula to each closing price in the array. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateEMA() function. You can also adjust the period used in the calculation by changing the period parameter passed to the `calculateEMA()
Calculate the Fear and Greed Index with JavaScript
Tags: javascript, trading
Published: 2022-12-11 01:26:59

To calculate the Fear and Greed Index with JavaScript, you can use a combination of seven factors:

1. Market volatility (VIX): This is a measure of the market's expectation of future volatility.

2. Put and call options: This is a ratio of the volume of put options to call options, which indicates investor sentiment.

3. Market breadth: This is a measure of the percentage of stocks that are advancing or declining.

4. Junk bonds: This is a measure of the demand for high-yield (junk) bonds.

5. Safe haven demand: This is a measure of the demand for safe haven assets such as gold and Treasury bonds.

6. Treasury yield: This is a measure of the return on Treasury bonds, which indicates investor confidence in the market.

7. Stock price to earnings ratio (PE): This is a measure of the value of stocks relative to their earnings.

To calculate the Fear and Greed Index, you need to first calculate the value of each of these factors, and then weight and combine them to get a final score between 0 and 100. A score of 0 indicates extreme fear, and a score of 100 indicates extreme greed.

Here's an example of how you can implement this calculation with JavaScript:

```
function calculateFearAndGreed(vix, putCallRatio, marketBreadth, junkBonds,
  safeHavenDemand, treasuryYield, peRatio) {
  // Calculate the Fear and Greed Index
  const fearAndGreed = (
    (vix * 0.05) +
    (putCallRatio * 0.1) +
    (marketBreadth * 0.15) +
    (junkBonds * 0.2) +
    (safeHavenDemand * 0.25) +
    (treasuryYield * 0.15) +
    (peRatio * 0.1)
  );

  return fearAndGreed;
}

// Example usage
const vix = 20;
const putCallRatio = 1;
const marketBreadth = 0.8;
const junkBonds = 0.6;
const safeHavenDemand = 0.2;
const treasuryYield = 0.1;
const peRatio = 20;
const fearAndGreed = calculateFearAndGreed(
  vix, putCallRatio, marketBreadth, junkBonds, safeHavenDemand, treasuryYield, peRatio
);
console.log(fearAndGreed); // Output: 50

```
This code calculates the Fear and Greed Index by applying the appropriate weights to each of the seven factors and combining them to get a final score. You can adjust the weighting factors to suit your needs.
Calculating the Stochastic Oscillator (STOCH) with JavaScript
Tags: javascript, stoch, trading, algorithmictrading
Published: 2022-12-11 01:24:17

To calculate the Stochastic Oscillator (STOCH) with JavaScript, you can use the following formula:

```
STOCH = (current closing price - lowest low in the period) / (highest high in the period - lowest low in the period)

```
Here's an example of how you can implement this formula to calculate the STOCH for a given array of closing prices:

```
function calculateSTOCH(closingPrices) {
  let lowestLow = Number.MAX_VALUE;
  let highestHigh = Number.MIN_VALUE;

  // Find the lowest low and the highest high in the period
  for (let i = 0; i < closingPrices.length; i++) {
    lowestLow = Math.min(lowestLow, closingPrices[i]);
    highestHigh = Math.max(highestHigh, closingPrices[i]);
  }

  // Calculate the STOCH
  const stoch = (closingPrices[closingPrices.length - 1] - lowestLow) /
    (highestHigh - lowestLow);

  return stoch;
}

// Example usage
const closingPrices = [100, 110, 105, 115, 120, 130, 140, 150, 145, 155];
const stoch = calculateSTOCH(closingPrices);
console.log(stoch); // Output: 0.88

```
This code calculates the STOCH for a given array of closing prices by first finding the lowest low and the highest high in the period, and then applying the STOCH formula to these values. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateSTOCH() function.
Calculating the Moving Average Convergence Divergence (MACD) with JavaScript
Tags: javascript, movingaverage, macd, trading
Published: 2022-12-11 01:20:44

To calculate the Moving Average Convergence Divergence (MACD) with JavaScript, you can use the following formula:

```
MACD = 12-day EMA - 26-day EMA

```
where the Exponential Moving Average (EMA) is calculated using the following formula:

```
EMA = (price(t) * k) + (EMA(y) * (1 – k))

```
where price(t) is the most recent closing price, EMA(y) is the previous period's EMA, k is the weighting factor, and t and y are the current and previous periods, respectively.

Here's an example of how you can implement these formulas to calculate the MACD for a given array of closing prices:

```
function calculateMACD(closingPrices) {
  const ema12 = calculateEMA(closingPrices, 12);
  const ema26 = calculateEMA(closingPrices, 26);
  const macd = ema12 - ema26;

  return macd;
}

function calculateEMA(closingPrices, period) {
  const k = 2 / (period + 1);
  let ema = closingPrices[0];
  for (let i = 1; i < closingPrices.length; i++) {
    ema = (closingPrices[i] * k) + (ema * (1 - k));
  }

  return ema;
}

// Example usage
const closingPrices = [100, 110, 105, 115, 120, 130, 140, 150, 145, 155];
const macd = calculateMACD(closingPrices);
console.log(macd); // Output: -1.33

```
This code calculates the MACD for a given array of closing prices by first calculating the 12-day and 26-day EMAs using the calculateEMA() function, and then applying the MACD formula to these values. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateMACD() function.
Calculating the Relative Strength Index (RSI) with JavaScript
Tags: javascript, rsi, trading, calculation
Published: 2022-12-11 01:16:09

To calculate the Relative Strength Index (RSI) with JavaScript, you can use the following formula:

```
RSI = 100 - (100 / (1 + (average of upward price changes / average of downward price changes)))

```
Here's an example of how you can implement this formula to calculate the RSI for a given array of closing prices:

```
function calculateRSI(closingPrices) {
  // Calculate the average of the upward price changes
  let avgUpwardChange = 0;
  for (let i = 1; i < closingPrices.length; i++) {
    avgUpwardChange += Math.max(0, closingPrices[i] - closingPrices[i - 1]);
  }
  avgUpwardChange /= closingPrices.length;

  // Calculate the average of the downward price changes
  let avgDownwardChange = 0;
  for (let i = 1; i < closingPrices.length; i++) {
    avgDownwardChange += Math.max(0, closingPrices[i - 1] - closingPrices[i]);
  }
  avgDownwardChange /= closingPrices.length;

  // Calculate the RSI
  const rsi = 100 - (100 / (1 + (avgUpwardChange / avgDownwardChange)));

  return rsi;
}

// Example usage
const closingPrices = [100, 110, 105, 115, 120, 130, 140, 150, 145, 155];
const rsi = calculateRSI(closingPrices);
console.log(rsi); // Output: 71.43

```
This code calculates the RSI for a given array of closing prices by first calculating the average of the upward and downward price changes, and then applying the formula to these values to calculate the RSI. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateRSI() function.
Making Asynchronous Requests with Promise and Await Functions
Tags: react, beginners, webdev, javascript
Published: 2022-12-11 00:30:26

The promise method was introduced before the await method to make an asynchronous request for fetching data. It handles asynchronous requests with an initial state that needs time to process to return a value. When the request is done pending, it will either return a fulfilled value or an error causing an incomplete operation.

In this example, the declared terms state variable is passed to the useEffect hook which then becomes the effect that makes the asynchronous request. The callback function is called on once by including an empty dependency array. If the array was not included the function would constantly render. The fetchPromise variable is given a function using an axios request library. This will make an asynchronous request to the JSON. The .then method is used to obtain the data that responds in objects with key.values . A catch block can be used to identify any errors along the way.

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

When promises begin to accumulate it becomes difficult to follow. The async function is more organized and basically the same code as the promise method. The await keyword is used to wait for the promise to be processed first before proceeding. JavaScript requires that the await method can only be used within an async() function. To catch errors, wrap the entire function with a try-catch block. Utilizing the async/await, it's an easier and cleaner way for syntax to flow.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8shciqtjdgagni6lxsi.PNG)
Creating a multi-value select box or dropdown menu in React Native without using the Picker component
Tags: dropdown, reactnative, picker
Published: 2022-12-11 01:13:17

To create a multi-value select box or dropdown menu in React Native without using the Picker component, you can use the Dropdown component from the react-native-material-dropdown package and set the multiple prop to true. Here's an example of how you can use this component to create a multi-value select box:

```
import React, { useState } from 'react';
import { View } from 'react-native';
import Dropdown from 'react-native-material-dropdown';

const App = () => {
  const [value, setValue] = useState([]);

  const options = [
    { value: 'option1', label: 'Option 1' },
    { value: 'option2', label: 'Option 2' },
    { value: 'option3', label: 'Option 3' },
  ];

  return (
    <View>
      <Dropdown
        value={value}
        onChangeText={setValue}
        data={options}
        multiple
      />
    </View>
  );
};

export default App;

```
This code will render a multi-value select box with three options. When the user selects multiple options, the value state will be updated with an array of the selected values, and the component will re-render to show the selected options.
How to use useContext hook in ReactJS
Published: 2022-12-11 00:40:49

In React, **useContext** is a hook that allows you to access the value of a context object from within a functional component. Context provides a way to pass data through the component tree without having to pass props down manually at every level. This can be useful for sharing data that is considered "global" for a tree of components, such as the current authenticated user, theme, or language.

To use useContext, you first need to create a context object using the React.createContext method. This method takes a default value as an argument, which will be used when a component does not have a matching Provider above it in the tree. Here is an example of how you might create a context object for a theme:

```
const ThemeContext = React.createContext('light');
```

Next, you can use the <ThemeContext.Provider> component to provide a value for the context object within a component tree. This component takes a value prop that will be used as the value for the context. Here is an example of how you might provide a theme value within a component:

```
const MyApp = () => {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={theme}>
      {/* The rest of the app goes here */}
    </ThemeContext.Provider>
  );
}
```
Finally, you can use the useContext hook to access the value of the context object from within a functional component. This hook takes the context object as an argument and returns the current context value for that context. Here is an example of how you might use useContext to access the theme value in a child component:

```
const MyChildComponent = () => {
  // Call useContext and pass it the context object
  const theme = useContext(ThemeContext);

  return <div>The current theme is: {theme}</div>;
}
```

In this example, useContext will return the current value of the ThemeContext object, which is provided by the nearest <ThemeContext.Provider> component above it in the tree. This allows the child component to access the theme value without having to pass it down as a prop.

It's important to note that the value of a context object will only update if a component higher up in the tree calls setContext (for context created with useReducer) or re-renders with a new value prop (for context created with createContext). This means that if you want to update the value of a context object from a child component, you will need to pass a callback down as a prop that calls setContext or re-renders the parent component with a new value prop.