teleren/devto huggingface dataset:
Debugging Vue Jest tests in a browser
Tags: vue, jest, unittests, javascript
Published: 2022-08-07 00:24:00

**Edit from the future:**

Okay, so this post is about `jest-preview` which is pretty dope, but unfortunately it currently only works with `@testing-library/vue`. I ran into issues with it almost immediately when testing anything beyond the simplest of components. I couldn't get any work done and had to revert back to `@vue/test-utils`.

I'm leaving this post up for documentation, but felt it equally important to leave it as a warning for people to avoid `testing-library`.

* * *

Below are the steps I did on one of my repos to get browser-based debugging of my Jest tests on Vue.js components. Specifically this is a Vue 3 repo created with Vue-CLI.

This is possible via the library `jest-preview`. I have not used it on a large comprehensive codebase yet, so there may be edge cases with it I haven't ran into, but as I do, I'll update this post.

1. `npm install --save-dev @testing-library/vue concurrently jest-preview wait-on`
1. `npm uninstall @vue/test-utils`
1. In `jest.config.js` add:
    ```js
    setupFilesAfterEnv: ['<rootDir>/tests/unit/setup.js'],
    transform: {
      '^.+\\.vue$': '@vue/vue3-jest',
      '^.+\\.css$': 'jest-preview/transforms/css',
      '^(?!.*\\.(js|css|json|vue)$)': 'jest-preview/transforms/file'
    }
    ```
1. In `tests/unit/setup.js` import any global CSS like so:
   * `import '../../public/global.css';`
   * `import 'bootstrap/dist/bootstrap.min.css';`
1. In `tests/unit/setup.js` add this:
   * `import { jestPreviewConfigure } from 'jest-preview';`
   * `jestPreviewConfigure({ autoPreview: true });`
1. In tests, change:
   * **from:** `import { shallowMount } from '@vue/test-utils';`
   * **to:** `import { render } from '@testing-library/vue';`
1. In tests change:
   * **from:** `const wrapper = shallowMount(MyComponent, options);`
   * **to:** `const wrapper = render(MyComponent, options);`
1. In tests change:
   * **from:** `const validator = wrapper.vm.$options.props.whatever.validator;`
   * **to:** `const validator = MyComponent.props.whatever.validator;`
1. Finally, in `package.json` add in this npm script:
   * `"jest": "concurrently \"jest-preview\" \"wait-on http://localhost:3336 && npm run unit\"",`
   * Change the `npm run unit` part to whatever script you use to run jest
1. Do `npm run jest`
Flutter Versiyon Düşürme
Tags: flutter, dart, version, downgrade
Published: 2022-08-07 00:14:00

**1. Yol**

`flutter downgrade <version-no>`

örneğin 2.10.3 versiyonuna geri dönmek isterseniz aşağıdaki kodu çalıştırmanız gerekir:

`flutter downgrade 2.10.3`


**2. Yol**

flutter/bin klasörünüzün bulunduğu yol'u terminalle açın:

örneğin: `cd /Users/your-username/Documents/flutter/bin`

daha sonra aşağıdalki komutu geçmek istediğiniz version  numarasıyla değiştirerek çalıştırın:

`git checkout <version-no>`

örneğin : `git checkout 2.0.5`

Daha sonra aşağıdaki komutu çalıştırın. Bu komut yeni ayarladığınız aktif flutter sürümünü belirleyecek ve onu indirmeye çalışacaktır.

`flutter --version`

Son olarak aşağıdaki komutu çalıştırın:
`flutter doctor`



[Kaynak](
https://vincenttechblog.com/how-to-downgrade-flutter-version-fixed/)
React Versiyon Düşürme
Tags: react, javascript, version, webdev
Published: 2022-08-07 00:13:00

`npm install --save --save-exact react@versiyonNo`
`npm install --save --save-exact react-dom@versiyonNo`

Module not found: Error: Can't resolve 'react-dom/client' hatası alırsanız index.js dosyasını aşağıdaki kod'la değiştirin.

index.js:

```
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
```


kaynak: https://stackoverflow.com/questions/71913692/module-not-found-error-cant-resolve-react-dom-client
Day 119: Hello Figjam!
Published: 2022-08-06 21:32:25

Hi!
Today was not that different from the rest of past days but at least today I was introduced to Figjam and something I have always wanted to find in Ui/ UX design which is presenting a project professionally with user personas architechure and everything and this is actually easier to do using figjam so I guess today was better.
Tomorrow I expect less time for coding as I will be travelling a lot but it will be the end of this lazy week I hope the next one will be better.

Signing off...
Web workers, Service Worker and PWA
Tags: webdev, javascript
Published: 2022-08-06 20:59:21

## What is web Worker?

Javascript is a single-threaded processing model. Web Workers makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

A web worker is a tool for multithreading in natively single-threaded Javascript programs. Web workers run in the background and communicate with the main thread via messages.

**Web Worker Applications:**

1. Real time text formatting, spell checking, and syntax highlighting
2. Filtering images in a canvas
3. Processing large JSON datasets
4. Processing multimedia (audio and video)

## What is Service Worker?
Basically service workers are event-driven workers. They are JavaScript assets that act as proxies between web browsers and web servers. It is helpful in time of creating offline experience and network interrupt by caching certain assets of your application.

There is 3 important part in service worker:
**Download :** This includes registering worker. It will install service worker in background. Using this will cache most of the assets. You check it in Application section of Dev tool.

**Installing & Activation :** If it is the first time that assets has been cached then it will be installed and activated after that.
And if there is another version of service worker available then it will be installed but not activated. Activation happens soon after the use of old service worker has completed.

## PWA (Progressive Web App)

It is a new software development methodology. Progressive web app are hybrid of native apps and web apps. It includes both capability of native apps and reachability of web apps. PWA promises mobile like features in web apps.

**Application of PWA**

1. Offline usability
2. Page loading speed
3. Platform independence
4. Better SEO
5. No need of platform specific native app development


[Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
[Service worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)
[PWA](https://web.dev/what-are-pwas/)
[PWA](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps)
VSCode...
Tags: vscode
Published: 2022-08-06 20:28:13

For me, vscode is the go to lightweight like~ code editor, which provides numerous extensions that give it an IDE feeling. Github features are what sell it to me, the built in, effortless version manager is such a life saver that boosts my productivity. It is highly customizable also, and thats what I like about vscode. Please share your opinions 😊
Hello World
Tags: dummy, dummy2
Published: 2022-08-06 19:49:00

**This is a dummy post just for dev.**

 Lorem ipsum dolor sit, amet consectetur adipisicing elit. Harum eius quaerat veritatis, tempora quibusdam ullam et molestias ad! Quia debitis officiis reprehenderit illo veniam, accusantium aspernatur saepe nemo ab sit?

 Lorem ipsum dolor sit, amet consectetur adipisicing elit. Harum eius quaerat veritatis, tempora quibusdam ullam et molestias ad! Quia debitis officiis reprehenderit illo veniam, accusantium aspernatur saepe nemo ab sit?


```js
console.log('hello world')
```

---

```tsx
const Component = ({name, age}) => {
return <h1>{name}, {age}</h1>
}
```
Python pytest tutorial
Tags: python, testing, tutorial, programming
Published: 2022-08-06 19:44:52

---
title: Python pytest tutorial
published: true
description: 
tags: #python #testing #tutorial #programming
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

What is Python pytest?
Install pytest for Python
How to use pytest?
Run pytest with specific Python version
Pytest fixtures
Pytest Conftest
Pass pytest arguments when invoked via Command line
Skip a method using pytest marker
Pytest failures
Generate HTML report
Common pytest Plugins
Pytest vs. Unittest
Conclusion

https://likegeeks.com/python-pytest/
Sequence Transformers for Polish language
Tags: nlp, python
Published: 2022-08-06 19:06:00

In this tutorial, I'll show you how to generate embeddings for sequences in polish using Sequence Transformers. I won't explain how they work, there are many great articles:
- [Measuring Text Similarity Using BERT
](https://www.analyticsvidhya.com/blog/2021/05/measuring-text-similarity-using-bert/)
- [Bert 101](https://huggingface.co/blog/bert-101)

What we'll need is a Sequence Transformers library from Huggingface:
```sh
pip install sequence_transformers
```

The code is simple, we import library, create model and ask it for embeddings. 
```python
from sentence_transformers import SentenceTransformer

model = SentenceTransformer('Voicelab/sbert-base-cased-pl')
embeddings = model.encode(["Ten tekst zostanie zakodowany"])
print(embeddings)
```
And that's it. This is the output of the model:
```
[[ 7.74895132e-01  7.00104088e-02 -5.02209544e-01 -2.06187874e-01
  -1.28363922e-01  1.18705399e-01 -1.88303709e-01 -9.09971595e-02
...
```

If you wanted to change the model change `Voicelab/sbert-base-cased-pl` to a model from [this](https://huggingface.co/models?language=pl&pipeline_tag=sentence-similarity&sort=downloads) list, it's pre-filtered for Polish language. 

Those embeddings can be pretty useful, as we could use them for classification, similarity search etc.

## Example of usage

I have a list of sentences. I want to know which ones are the most similar. How could I do that? As you can guess – with embeddings. We'll calculate a distance matrix for each sentence and look which are the most similar.

```python
sentences = [
"Pożar w mieście. Zgnięło 10 osób."
,"Wypadek pod wiaduktem kolejowym."
,"W Poniedziałek odbędzie się konferencja naukowa"
,"Magia potrafi wzniecać pożary"]

embeddings = model.encode(sentences)
```

I'll use cosine distance as measure of similarity.

```
from sklearn.metrics import pairwise

sns.heatmap(pairwise.cosine_similarity(embeddings, embeddings))
```
![Heatmap of distance matrix](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8rdn3mhl8b2reftklsj.png)

From this heatmap we can deduce that our model works, it found similarity between sentences with `pożar` and `wypadek` which both refer to an accident. 
 
_Pracę przygotowano w ramach realizacji projektu pt.: „Hackathon Open Gov Data oraz stworzenie innowacyjnych aplikacji, z wykorzystaniem technologii GPU”, dofinansowanego przez Ministra Edukacji i Nauki ze środków z budżetu państwa 
w ramach programu „Studenckie koła naukowe tworzą innowacje”._

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89b9olhqzqty9moz6kzg.png)
Updating from @sveltejs/kit@1.0.0-next.350 to @sveltejs/kit@1.0.0-next.403
Tags: webdev, svelte, javascript
Published: 2022-08-06 18:36:19

TLDR: [Here's the commit that I made all code changes in](https://github.com/AndrewUsher/qr-gen/commit/612b7c76710e662f8c9adab22f3753f459f2edb5)

I recently updated the version of sveltekit I'm using for [qr-gen](https://qr-gen-murex.vercel.app/), and it was quite the experience :). There's not much documentation out there (at least that I could find), so I'm documenting what I needed to change here.

## Update dependencies

```sh
yarn add @sveltejs/kit@latest @sveltejs/adapter-auto@latest --exact
```

Note: if you're using any other packages under the `@sveltejs` org, you'll likely need to update those as well.

## Add vite.config.js

Next, I needed to create `vite.config.js` in the root of the repo and add the svelte-kit plugin to the config:

```js
import {sveltekit} from '@sveltejs/kit/vite'

/** @type {import('vite').UserConfig} */
const config = {
  plugins: [sveltekit()]
}

export default config
```

You'll also need to remove any configuration you have under the `kit.vite` property in `svelte.config.js`. [Consulting the vite configuration docs](https://vitejs.dev/config/) should be helpful here.

## Update API Routes to Use Uppercase Method Names

Updating `export const post` to `export const POST` (and so forth for other request methods)
Do Fantasy Stars Equal Wins
Published: 2022-08-06 18:20:32

(https://github.com/Kmulla19/Blog/tree/main/Blog2)

How much of an impact do high performing offensive fantasy players make on their team winning?

It's easy to quickly conclude that the top NFL teams would have more fantasy players right? After all, you get points for doing things that are good for your offense.

But what if the defense scores a touchdown? That helps the team win but harms their offensive fantasy players as the other team now has the ball again. In addition, usually when a team is behind, they are forced to pass in an attempt to score quicker. This can lead to some big fantasy numbers for the quarterback of the team that ultimately loses the game.

Well today we are going to explore the correlation of the number of wins a team has, and the number of players that team has in the top 100 PPR ranks for that season (PPR is a type of fantasy football point counting style). We will also begin building a simple linear regression model that we can we expand onto in the future.

First we need to get two different sources of data. One is the NFL standings for last season. The second is the top fantasy players for the NFL last year.

Now we need to filter down to the top 100 PPR players, see which team they are on, and compare the count of top players on each team, with the number of wins they had.

The correlation between these two variables is .66, which is pretty strong.

A simple linear regression model between these two variables is .42(.40 adjusted). This means that the number of players in the top 100 PPR for each team explains 40% of the variance in that teams wins.

Now what else could we explore to better understand the connection between these two?

We could look at the total fantasy points scored by each team's players in the top 100. Two teams that each have 3 players in the top 100 could have drastically different total fantasy points scored by those 3 players.

Also, how does the position of your top fantasy players affect the win total? As I mentioned earlier, having a quarterback with a lot of fantasy points isn't always a good thing. Are top performing running backs a sign that your team was in control and didn't need to pass as much?

It's interesting to note that the top fantasy player in the league last year just so happened to be on the Super Bowl winning Rams. However, the Rams only had 12 regular season wins while two other teams had 13 wins.

Here are some other things I noticed or want to further explore:
1. Every team with 10 wins had at least 3 top fantasy players

2. The bottom two teams had 3 fantasy wins, but the next 5 had 1 or less.

3. "Points For", a team's total points scored throughout the season has a 87% correlation with win %.
Code Smell 156 - Implicit Else
Tags: javascript, webdev, beginners, programming
Published: 2022-08-06 17:50:55

*We learn if/else on our first programming day. Then we forget the else*

> TL;DR: Be explicit. Even with Else.

# Problems

- Readability

- Cognitive Load

- Unforeseen conditions

- [Fail Fast Principle violation](https://dev.to/mcsee/fail-fast-48dm)

# Solutions

1. Write the explicit else

# Context

If we early return on an IF sentence we can omit the else part. 

Afterward, we [Remove the IF](https://dev.to/mcsee/how-to-get-rid-of-annoying-ifs-forever-1jfg) and use polymorphism.

That is when we miss the real cases.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/8d2eb5957180d324326e2c30a72166f6)
```javascript
function carBrandImplicit(model) {
  if (model === 'A4') {
    return 'audi';
  }
  return 'Mercedes-Benz';
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/34f2e6cc97fb6ef9cb77f8998aaa790e)
```javascript
function carBrandExplicit(model) {
  if (model === 'A4') {
    return 'audi';
  }
  if (model === 'AMG') {
    return 'Mercedes-Benz';
  }
  
  // Fail Fast
  throw new Exception('Model not found);
}
```

# Detection

[X] Automatic 

We can check syntax trees and parse them and warn for missing else.

We can also rewrite them and perform mutation testing.

# Tags

- Conditionals

# Conclusion

This kind of smell brings a lot of public debate, *and hate*.

We must exchange opinions and value each pros and cons.

# Relations

{% post https://dev.to/mcsee/code-smell-102-arrow-code-4kfk %}

{% post https://dev.to/mcsee/code-smell-36-switch-case-elseif-else-if-statements-h6c %}

# More Info

[Stop Using Implicit Else](https://javascript.plainenglish.io/advice-from-a-senior-dev-stop-using-the-implicit-else-2a2ecf0a3583)

[When To Use Implicit Else](https://medium.com/lost-but-coding/when-to-use-implicit-else-e891cdcfe1bd)

{% post https://dev.to/mcsee/fail-fast-48dm %}

{% post https://dev.to/mcsee/how-to-get-rid-of-annoying-ifs-forever-1jfg %}

# Credits

Photo by [Elena Mozhvilo](https://unsplash.com/es/@miracleday) on [Unsplash](https://unsplash.com/s/photos/invisible)
  
* * *

> The biggest issue on software teams is making sure everyone understands what everyone else is doing.

_Martin Fowler_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Multiple server with Nginx
Tags: nginx, node, server, ubuntu
Published: 2022-08-06 17:39:00

## Part 1 - Get server instance

- Create a Ubuntu server with any provider like AWS, Linode, DigitalOcean, etc.

- Add a ssh key.

---

## Part 2 - Get domain name

- Get a domain name from any provider like BigRock, Google, etc.

- Add an **A record** with the ipv4 address of the server.

- You can add multiple **A records** with different subdomains with the same ipv4 address.

> Add the records in your domain provider DNS only. Don't create new domain in the server provider. 

---

## Part 3 - Server connection from local machine

- Login via ssh.

- Run the following commands,

```
sudo apt update

sudo apt upgrade -y
```

- Reboot your instance.

- Login again via ssh.

- Install Node.js via,

```
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

sudo apt install nodejs

node --version
```

- Create the folder(s) of your server and write the code for it.

- Sample server code is,

```
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
```

---

## Part 4 - Install pm2

```
sudo npm i pm2 -g

pm2 start <server-file-name> --name "<process name>"
```

---

## Part 5 - Setup ufw firewall

```
sudo ufw enable

sudo ufw status

sudo ufw allow ssh (Port 22)

sudo ufw allow http (Port 80)

sudo ufw allow https (Port 443)
```

---

## Part 6 - Install NGINX and configure

```
sudo apt install nginx

sudo nano /etc/nginx/sites-available/default
```

- Sample server block looks like,

```
server {
    server_name <domain-name>;

    location / {
        proxy_pass http://localhost:<port of server>;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    listen 80;
}
```

- Add this to show default page for all the other URLs,

```
server {
    server_name <IPV4 address of the server>;
    root /var/www/html;
    index  index.nginx-debian.html;
    listen 80 default_server; 
}
```

- Check nginx config via,

```
sudo nginx -t
```

- Restart nginx via,

```
sudo service nginx restart
```

---

## Part 7 - Add SSL with Certbot

- Follow the instructions at [Offical website of certbot](https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal).
A helpful dashboard with tools, resources and more, for developers.
Tags: opensource, typescript, react, javascript
Published: 2022-08-06 17:35:00

I wanted to have a place for some of my tools I need during the day. So I made a little dashboard for just that. I would LOVE to see others in the community use it and build on top of it. 

So I figured what's a better way to show it off, then talk about it on dev.to. 

Dev.to has been such a great community and I've really appreciated all of you who have provided feed back on my thoughts and writings. 

I hope you like the project, it's my first real open source project and I'm excited and nervous to share. 

https://coex.dev

Questions for the community.
- What am I missing for an open source project? 
- Will it be taken serious if I'm hosting the repo on gitlab vs github? I love gitlab but I see everyones repo on github.
- What tools can I add for you? 
- What do I need to add to make it feel more welcoming to contribute?
Kotlin 基礎 Part 1 -- !! や ?: と ?.let で Nullable な値を処理する
Tags: kotlin, null
Published: 2022-08-06 17:27:44


## why

Kotlin には様々な null の扱いの演算子があるのでまとめてみた

https://play.kotlinlang.org/

ここで実行して試しました

---

## 通常の実行

```kotlin
    val maybeNullValue = null
    println(maybeNullValue)
// null
```

普通に print すると null が返ってくる

---

## nullableValue!! で null が返ってくるくらいなら ぬるぽ のエラーを返す

https://engawapg.net/kotlin/116/what-is-kotlin-exclamation-mark/

```kotlin
    val nullableValue = null
    println(nullableValue!!)
// Overload resolution ambiguity
// 多分ぬるぽ
```

null が入っている値に使うとぶっ壊れる演算子
エラーになるけど、null が渡るよりマシな場面に使えると推測。

Nullable な型に Null 不可で突っ込みたい時に使える

---

## nullableValue?:"" で null だった場合は空の文字列を返す

```kotlin
    val maybeNullValue = null
    println(maybeNullValue?:"empty")
// empty
```

?: を使えば、それが null だった時に次の値を入れられる。

多くの場合は空の文字列を入れるだろう。
わかりやすいようにサンプルでは"empty"の文字列を入れている

こうすれば安全だし書きやすい。

---

## nullableValue?.let {  } の中に処理を書いて null な時は実行されないようにする

https://www.tutorialspoint.com/best-way-to-null-check-in-kotlin#:~:text=let%22%20operator,a%20non%2DNULL%20able%20value.

nullableValue?.let { // execute(nullableValue) }

こうすれば null がないときにはスキップされる

```kotlin
    val nullableValue = "text"
    nullableValue ?.let {
      println(nullableValue)
    }
    println("executed")

//text
//executed
```

text を入れてみると print されるが

```kotlin
    val nullableValue = null
    nullableValue ?.let {
      println(nullableValue)
    }
    println("executed")
//
//executed
```

null が入っているとスキップされる。
ワンライナーで書きやすい。
Zombie Process in Operating Systems
Tags: webdev, beginners, computerscience, operatingsystem
Published: 2022-08-06 16:54:07

## Zombie process in Operating Systems 
When a Parent process creates child process, at the time of termination it calls a system call wait();

If a parent process terminates itself without calling wait();
This means the OS deallocated the resources to the child process but it's entry in the process table remains.
So, this is a **Orphan process** and it's called **Zombie process**.

[How does HTTPS work?](https://codinghindi.in/how-does-https-work/)

## Solution of Zombie Process
Linux & UNIX OS address this process by assigning the _init_ process as new parent to the child process.
And this invokes wait(); for it.
The entry table releases the entry of that zombie process.

**Init** - root process in UNIX & Linux hierarchy

[What is Operating System and its 5 Structures?](https://codinghindi.in/what-is-operating-system-and-its-5-structures/)