teleren/devto huggingface dataset:
styled-componentsでラップした複数の子要素に同じpropsを同時に渡す
Tags: webdev, react, styledcomponents
Published: 2022-11-02 15:18:58

タイトルの通りです。あるコンポーネント内で**配下にある全ての子要素**（styled-componentsでラップされたものであるとします）に共通したpropsを渡す場合のやり方の話です。愚直に書いていたらキリがなく最悪なコードが出来上がります。

## 結論
`styled-components/ThemeContext` を使おう。

```tsx
import { ThemeContext } from 'styled-components'
```

## 具体例

まずこんな感じの複雑なコンポーネント `Component` が存在しているとします。多くのコンポーネントやDOMを内包していますが、それらは全てstyled-componentsでラップされています。

```tsx
const A = styled.div`
  /* ... */
  ${props => props.value}
  /* ... */
`

const B = styled.div`
  /* ... */
  ${props => props.value}
  /* ... */
`

const C = styled.div`
  /* ... */
  ${props => props.value}
  /* ... */
`

// ...

const Z = styled.div`
  /* ... */
  ${props => props.value}
  /* ... */
`

const Component = () => {
  return (
    <Container>
      <A />
      <B />
      <C />
      {/* ... */}
      <Z />
    </Container>
  )
}
```

ここで、全ての（あるいは殆どの）内包したコンポーネントで `value` という共通した値を使いまわしたいとします。（この `value` は `useContext` などで更に上層から受け取ったものとします）

そんな時に、こんなこと↓なんてやていられません。

```tsx
const Component = () => {
  return (
    <Container>
      <A value={value} />
      <B value={value} />
      <C value={value} />
      {/* ... */}
      <Z value={value} />
    </Container>
  )
}
```

こういうときは `ThemeContext` を使いましょう、一発で解決します。

```tsx
const Component = () => {
  return (
    <ThemeContext.Provider value={/* 任意の値 */}>
      <Container>
        <A />
        <B />
        <C />
        {/* ... */}
        <Z />
      </Container>
    </ThemeContext.Provider>
  )
}
```

ただし、注意点として呼び出す際のpropsのプロパティが`theme`になるので、既に違うプロパティで定義してる場合は修正しましょう。

```diff
- ${props => props.value}
+ ${props => props.theme}
```

また当然ではありますが`theme`にオブジェクトを渡すことでpropsを一層ラップした状態でこれまで通りに値を扱えます。

```tsx
interface Attrs {
  // 渡したいpropsの型定義
}

const A = styled.div`
  /* ... */
  ${({ theme: props }: { theme: Attrs }) => props.aaa}
  ${({ theme: props }: { theme: Attrs }) => props.bbb}
  ${({ theme: props }: { theme: Attrs }) => props.ccc}
  /* ... */
`

const Component = () => {
  const attrs: Attrs = { /* ... */ }

  return (
    <ThemeContext.Provider value={attrs}>
      <Container>
        <A />
        <B />
        <C />
        ...
        <Z />
      </Container>
    </ThemeContext.Provider>
  )
}
```

以上です。
WordPress 6.1 “Misha” released today: efforts of more than 800 contributors from 60+ countries.
Tags: wordpress, linux, php
Published: 2022-11-02 15:16:28

WordPress 6.1 “Misha” was released today

This release is the culmination of a months-long effort to improve the design tooling consistency of WordPress’ core blocks. 
it has tons of new features and options. 

WordPress 6.1 expands the templates options available for site editing. It adds alot of new things regarding Full site Editing and new block design and template editing capabilities, 

the New Twenty Twenty-Three Default Theme with 10 Style Variations
is one of the most anticipated parts of this release is the new Twenty Twenty-Three (TT3) default theme. This is a new kind of default theme that bundles a curated set of style variations - that come from the global community. 

WordPress 6.1 includes more than 60 accessibility improvements and 25 tickets dedicated to performance. This release is the result of the tireless efforts of more than 800 contributors from 60+ countries. For a quick visual tour, check out the official WordPress 6.1 release article on Wordpress.org
Hacktoberfest - Part 4
Published: 2022-11-01 02:24:14

For Part 4, I decided to work on a bug in the Seneca telescope project. [The issue](https://github.com/Seneca-CDOT/telescope/issues/3687) was related to the sign-up process. When users sign up, they have to input their blog URL. Upon entering this, they will be shown possible feed URLs. However, in case there is only one feed URL, it should get auto selected and the sign-up process should move to the next step.

I knew what this was about since I had experience it myself while signing up. And since I already had setup the project locally before to work on [another issue](https://github.com/Seneca-CDOT/telescope/issues/3535), I did not think any setup would be needed. However, I had not looked at how login or sign up worked. On the released version of the app, the signup process requires the user to login with their Seneca email using SSO. So, I looked up the environment setup documentation and found instructions on how to set up a local test SAML SSO provider to get login working and a list of test users that I could use to replicate the signup process.

I followed the instructions and got login working locally. However, my local database was not seeded properly since the login process using the local test SAML SSO provider would work but the app could not find the relevant users in the database. So, finally after seeding the local database properly, I was able to start working on the issue.

I found it fairly simple to get the auto select functionality working as it involved checking if the field URLs array only had one element, and then selecting that. Though, I found that currently, the user had to select another checkbox to declare that they own and maintain the blog at the blog URL. This checkbox had to be checked for the sign up to move to the next step. So, I decided to not skip this checkbox and keep the changes to just auto selecting the feed URL for now. I mentioned this in a comment in the original issue and created a [draft PR](https://github.com/Seneca-CDOT/telescope/pull/3751) for my changes.
Slider Components just Released! 🎉
Tags: react, html, tailwindcss, news
Published: 2022-11-02 15:02:21

Howdy guys, 

Check out our newest release, Slider Components with 7 spinning variations!

[https://wind-ui.com/components/sliders](https://wind-ui.com/components/sliders)

As always looking forward to your feedback! 👀
Hashcat cracking pwnagotchi pcap files
Tags: pwnagotchi, hashcat, security, linux
Published: 2022-11-02 14:53:43

Once you've collected enough crackable WPA material with your [pwnagotchi](https://pwnagotchi.ai/), it's time to attack it with hashcat.

Pwnagotchi stores the handshakes as `.pcap` files, while modern versions of hashcat use hash mode 22000. No problem, it's easy to convert between the two. On Kali or Ubuntu or Mint, install the `hcxtools` as follows:
```
sudo apt-get install hcxtools
```

Now, in the directory with all the `.pcap` files you have permission to attack, run the following command:
```
hcxpcapngtool *.pcap -o candidates.hc22000 -E essid.wordlist
```

This converts all the `.pcap` files into a single output file, `candidates.hc22000`. We also extract the list of essids (network name), as these might be useful in your cracking attempt.

Now we need hashcat. If you are running Kali, hashcat is probably already installed. If not, or if you are running Ubuntu or Mint, you can install it with the following command:
```
sudo apt-get install hashcat hashcat-data
# If you have an nvidia graphics card:
sudo apt-get install hashcat-nvidia
# Check if the install worked, run a benchmark
hashcat -m 22000 --benchmark
```

Right. Let's attack the handshakes.
```
hashcat -m 22000 candidates.hc22000 /usr/share/doc/hashcat-data/examples/example.dict
```

This tells hashcat to run in [hash mode 22000](https://hashcat.net/wiki/doku.php?id=cracking_wpawpa2), for cracking the WPA pre-shared key. We attack `candidates.hc22000` and we use the example wordlist in `/usr/share/doc/hashcat-data/examples/example.dict`.

You can see if hashcat was successful with the following command:
```
hashcat -m 22000 candidates.hc22000 --show
```

No successes? Don't worry, here are some other attacks to try:
```
# Try all telephone numbers in your area code:
hashcat -m 22000 candidates.hc22000 -a 3 780?d?d?d?d?d?d?d
# Try the essids:
hashcat -m 22000 candidates.hc22000 essid.wordlist
# Permutate the example wordlist and the essids with a ruleset
hashcat -m 22000 candidates.hc22000 /usr/share/doc/hashcat-data/examples/example.dict essid.wordlist -r /usr/share/hashcat/rules/best64.rule
```

If that was not successful, you may want to try other wordlists. In Kali, there are a few in `/usr/share/wordlists`. Alternatively, there are plenty available online. A good list to start with is the rockyou wordlist, though it is rather large.

Remember, hashcat runs much faster if you throw a GPU (or three) at it. A modern nVidia Geforce RTX 4090 may crack 2500 kH/sec. A 3080 might get 900 kH/sec. Running just on the CPU without any GPU may only net you 25 kH/sec, though. That's fine for quick checks and small wordlists but much too slow for anything more significant.

What's next? Hashcat is a powerful tool, allowing significant control over the attacks. The [hashcat wiki](https://hashcat.net/wiki/) has lots of helpful information.

Happy cracking!
Answer.dev 0.2.0 is now available!
Tags: programming, go, community, opensource
Published: 2022-11-02 14:31:20

Thanks to our contributors! **Answer.dev 0.2.0 is now available, which contains some bug fixes, optimizations, and improvements.** Let's together see more details.

### New Features
- [Gravatar](https://gravatar.com/) profile image support
- Thumbnail generation
- Change email before account activated

### Bug Fixes
- Important: fixed panic issues when linking the wrong version of SQLite library [#28](https://github.com/answerdev/answer/issues/28)

### Performance Improvements
- Optimized: the docker images size has decreased almost by 50% which from 200 MB to 100 MB

### Other Changes
- The docker container image has changed from Debian to alpine
- Use SQLite as the default database.
- You can just use the Docker Quick Start project for the experience. (Previous using Docker-compose with MySQL was heavy.)

-----

Being highly scalable and modern, **Answer.dev is an open-source knowledge-based community software with which you can efficiently build various Q&A communities**, ranging from customer support to user communication.

For more information on past and future versions of Answer.dev, please see: [https://github.com/answerdev/answer](https://github.com/answerdev/answer)
Phalcon 5.1.0 Released
Tags: phalcon, phalcon5, release
Published: 2022-11-02 13:50:05

---
title: Phalcon 5.1.0 Released
published: true
date: 2022-11-02 13:31:42 UTC
tags: phalcon,phalcon5,release
canonical_url: 
---

Phalcon 5.1.0 is now available.

This release contains some bug fixes and new functionality for request PATCH methods.

As always, a huge thank you to our community for identifying these issues and suggesting the new features.

## Changelog

### Fixed

- Fixed `Phalcon\Mvc\View\Engine\Volt\Compiler::isTagFactory` to correctly detect a `TagFactory` object without throwing an error [#16097](https://github.com/phalcon/cphalcon/issues/16097)
- Fixed default values for `Phalcon\Cli`, `Phalcon\Dispatcher` and `Phalcon\Application` components to ensure not `null` values are passed to methods [#16186](https://github.com/phalcon/cphalcon/issues/16186)
- Fixed `Phalcon\Form::clear` to correctly clear the elements and not recurse [#15956](https://github.com/phalcon/cphalcon/issues/15956)

### Added

- Added `Phalcon\Http\Request::getPatch()` to get a value from a PATCH request [#16188](https://github.com/phalcon/cphalcon/issues/16188)
- Added `Phalcon\Http\Request::getFilteredPatch()` to get a value filtered from a PATCH request [#16188](https://github.com/phalcon/cphalcon/issues/16188)
- Added `Phalcon\Http\Request::hasPatch()` to check if a value exist in a PATCH request [#16188](https://github.com/phalcon/cphalcon/issues/16188)
Customizing nushell prompt
Tags: nushell, programming, tutorial, opensource
Published: 2022-11-02 13:28:50

By default, [nushell](https://www.nushell.sh/)'s prompt shows your working directory on the left, and the date & time on the right. It looks like this:

![nushell default prompt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/icsj0787zf7syday98nx.png)

As someone who was trying nu after using zsh for a long time, I wanted to replicate my old prompt, which showed me my working directory, current kubernetes cluster, and current k8s namespace:

![zsh prompt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0tbii5o21cb4r2m34f2m.png)

Nushell configures your prompt in its environment script (`$nu.env-path`). If you open this file you will see two functions at the very top, `create_left_prompt` and `create_right_prompt`. you can see the default implementation for the date 

```nu
def create_right_prompt [] {
    let time_segment = ([
        (date now | date format '%m/%d/%Y %r')
    ] | str join)

    $time_segment
}
```

I created a new function for my k8s prompt. I liked having the time on the prompt, so I left that (thought I didn't feel like I needed the date).

```nu
def kube_prompt [] {
    let k_prompt =  ([(kubectl ctx -c), (kubectl ns -c)] | str trim | str join '/')
    let d_prompt = ([(date now | date format '%r')] | str join)
    $"\(($k_prompt)\) ($d_prompt)"
}
```

Just below, we can edit the `let-env PROMPT_COMMAND_RIGHT` to look like:

```
let-env PROMPT_COMMAND_RIGHT = { kube_prompt }
```

Restarting your shell and you will see the new prompt


![nushell with k8s prompt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/63s6q2ff2udw853ekb77.png)
Only 3As to writing your first test!
Tags: beginners, webdev, testing, react
Published: 2022-11-02 13:25:57

I've been developing web applications for so long but I always looked back when it came to testing and this has many reasons. 
And let me elaborate:

**My Code works why bother test?**
I usually couldn't wrap my head around why I needed to write code to test something that I am using and is working perfectly fine. And I'm sure many of other junior developers also have the same thinking but we'll explore why we need to test.

**Testing is very hard and is for Senior Developers**

Well this is a real case and I too, used to think like that and this is because I saw many job postings requiring testers to be highly experienced individuals. Well testing sometimes does require core understanding of the tools you are using to test and the app you are testing with the libraries used to develop it but in the end I just found out it's not that hard and is very easy to implement the tests.

There exist many other reasons to why I avoided testing but the above are one of the main.

**So what is testing all about?**

Testing in software development refers to the process of writing code to test either some parts of the software , their integration or the software as a whole or using the software directly and testing every feature to see if it works following the flow.

With testing React Apps testing is very very simple just the **3As** 

**3As**

- Arrange : here you just render components and provide the props required using code. (Mainly libraries are there to help with you).
- Act     : Acting is the most important step in testing because this is where you mimic the user's action using code to then expect certain things to happen or not. 
- Assert  : The last and mainly the intended part of testing is assertion , here you expect something to happen given the actions you deployed in the second step like the button being disabled the state changing etc...

So far What I've seen is that testing is not actually about coding but setting the right **priorities** and trying to perfectly **mimic** the user's action and then writing codes just depend on the library being used and doesn't matter that much as long as you understand the concepts and patterns.

This was part one of this series next time time I'll be talking about types of testing and how to get started. Like and follow for more!
LeetCode: Greatest Sum Divisible by 3
Published: 2022-11-02 13:23:59

[LeetCode Discussion](https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/431077/JavaC%2B%2BPython-One-Pass-O(1)-space)


```
class Solution {
    public int maxSumDivThree(int[] nums) {
        int res = 0, leftOne = 20000, leftTwo = 20000;
        for(int n:nums){
            res+=n;
            if(n%3==1){
                leftTwo = Math.min(leftTwo,leftOne+n);
                leftOne = Math.min(leftOne,n);
            }
            if(n%3==2) {
                leftOne = Math.min(leftOne,leftTwo+n);
                leftTwo = Math.min(leftTwo,n);
            }
        }
        if(res%3==0) return res;
        if(res%3==1) return res-leftOne;
        return res - leftTwo;
        
    }
}
Dp solution for K problem:

class Solution {
    public int maxSumDivThree(int[] nums) {
        return maxSumDivK(nums,3);
    }
    public int maxSumDivK(int[] nums, int k){
        if(k==0) return -1;
        int[] dp = new int[k];
        for(int num : nums){
            int tmp[] = Arrays.copyOf(dp,k);
            for(int i=0;i<k;i++){
                dp[(num+tmp[i])%k] = Math.max(dp[(num+tmp[i])%k],num+tmp[i]);
            }
        }
        return dp[0];
    }
}

```
Want to Lose Weight Fast? These Science-Backed Tips Can Help You Lose Weight Sustainably
Published: 2022-11-02 13:21:50

Achieving healthy [weight](https://bit.ly/3SOKFAW) loss isn’t about a “diet” or “program” but a lifestyle with healthy eating patterns, regular physical activity, and stress management. Medications taken for other conditions may also make it harder to lose weight. If you are concerned about your weight or have questions about your medications, talk with your health care provider.

When you’re trying to lose weight, it’s natural to want it to happen very quickly. But people with gradual and steady weight loss (about 1 to 2 pounds per week) are more likely to keep the weight off.

Once you’ve achieved a healthy weight, rely on healthy eating and physical activity to help maintain health over the long term.

[Losing](https://bit.ly/3SOKFAW) weight isn’t easy, and it takes commitment. But if you’re ready to get started, we’ve got a step-by-step guide to help get you on the road to weight loss and better health. Before starting on the guide, it’s important to approach the changes with self-compassion and to understand your readiness and motivation. Creating a supportive environment, both physically and with the people in your life, can help you achieve your goals.

Even modest weight loss can mean big benefits
Even a modest weight loss of 5% to 10% of your total body weight is likely to produce health benefits, such as improvements in blood pressure, blood cholesterol, and blood sugars.1

For example, if you weigh 200 pounds, a 5% weight loss is 10 pounds, bringing your weight down to 190 pounds. While this weight may still be in the “overweight” or “obesity” range, this modest weight loss can decrease your risk for chronic diseases related to obesity.

So even if the overall goal seems large, see it as a journey rather than a final destination. You’ll learn new eating and physical activity habits that will help you live a healthier lifestyle. These habits can help you maintain your weight loss over time.
Unpack Like A Pythonista
Tags: python, destructuring
Published: 2022-11-02 13:16:08

---
title: Unpack Like A Pythonista
published: true
description: 
tags: python, destructuring
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2022-11-02 11:25 +0000
---

> A Pythonista's ways of data unpacking.

_To index_ or _to unpack_, that is the question. During a code review, I came across unpleasant-looking code. For me, coding is an art. It tells stories about us. I love beautiful, creative and artistic stories. Thus, I love beautiful and creative code.

Back to the code review. The unpleasant "looking" code emerged from an index accessing of data. 

```python
# task A: get jack and the rest
friends_data = ["jane", "john", "jill", "jack", ]

# the usual indexing
jack = friends_data[-1] # -1 the last element in data | data[3] index 3, 4th element
rest = friends_data[:-1] # all but the last element

print(f"👋 hello, {jack!r} out of the {rest=}!")
# "👋 hello, 'jack' out of the rest=['jane', 'john', 'jill']!"
```

As data become more complex, unpleasant-looking index accessing emerges.

```python
# task B: get jack and his value (23)
data = [("jane", 21), ("john", 32), ("jill", 45), ("jack", 23), ]

# the usual indexing
jack = data[-1][0]
jacks_value[-1][1]

print(f"This is {jack!r} with the value {jacks_value}!")
# "This is 'jack' with the value 23!"
```

 A prettier solution could be **pattern matching**. For example in Rust 🦀, we could perform destructuring assignments with _match_.

```rust
// task A: get jack and the rest

// unpacking/destructuring assignment
fn main() {
    let friends_data = ["jane", "john", "jill", "jack", ];
    let data = [("jane", 21), ("john", 32), ("jill", 45), ("jack", 23),];

    match friends_data {
    
        [.., jack] =>
            println!("👋 Hey, rust, this is {jack}!"),   
    }

    match data {
        [.., (jack, jacks_value)] =>
            println!("Oh, rust, this is {jack} with the values {jacks_value}!")
    }
}

// cargo run
// >> 👋 Hey, rust, this is jack!
// >> Oh, rust, this is jack with the values 23!
```

Python 🐍 offers destructuring assignments too. It brings beauty back to data accessing.

```rust
# task A: get jack and the rest

*rest, jack = friends_data
print(f"👋 hello, {jack!r} out of the {rest=}!")
# "👋 hello, 'jack' out of the rest=['jane', 'john', 'jill']!"

# task B: get jack and his value (23)

*_, (jack, jacks_value) = data # *_ since we dont need the rest we throw them away
print(f"This is {jack!r} with the value {jacks_value}!")
# "This is 'jack' with the value 23!"
```

It's even prettier when you unpack nested weird data.

```python
weird_data = [("jack", 23),]
[(jack, jacks_value), ] = weird_data 
print(f"This is still {jack!r} with the value {jacks_value}!")
# "This is still 'jack' with the value 23!"
```


_To index_ or _to unpack_? I hope the answer is less unclear. Until then, keep on unpacking ...