teleren/devto huggingface dataset:
How to mock FileList on Vitest
Tags: javascript, testing, vitest, webdev
Published: 2022-05-02 01:40:13

I need to mock [`FileList`](https://developer.mozilla.org/en-US/docs/Web/API/FileList) that `<input type="file" multiple />` provides. This article shows you how to mock it. I had a hard time mocking it.
The requirement to mock `FileList` is the following.

- [`Object.prototype.toString.call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) can return a string representing the `FileList` mock object.
- The function that will be tested can process each `File` using `for` statement.

# How to Mock `FileList`?

## Environment
Vitest v0.9.3

## Source Code

### The Source Code of The Tested Function

```js
export const filesProcess = (fileList) => {
  if (
    Object.prototype.toString.call(fileList).split(" ")[1].slice(0, -1) !=
    "FileList"
  )
    throw Error("Please input FileList type object as the argument.");

  for (let file of fileList) {
    console.log("File name: " + file.name);
  }
};
```

### Test Code

```js
    it("testing", () => {
      const file = new File(["foo"], "foo.txt", {
        type: "text/plain",
      });
      const file2 = new File(["this is test file"], "test.txt", {
        type: "text/plain",
      });
      const input = document.createElement("input");
      input.setAttribute("type", "file");
      input.setAttribute("name", "file-upload");
      input.multiple = true;
      let mockFileList = Object.create(input.files); 
      mockFileList[0] = file;
      mockFileList[1] = file2;
      Object.defineProperty(mockFileList, "length", { value: 2 });
      console.log(
        "The string representation the object: " +
          Object.prototype.toString.call(mockFileList)
      );
      filesProcess(mockFileList);
      expect(1).toBe(1); // Dummy assertion because I want to try only to mock FileList
    });
```

## Result
The result shows the result of testing using `console.log`.
![The result of running test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfcpaxq8dtmn1ppxogvl.png)

# Reference
{% embed https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create %}

# As An Aside
I make the browser displays all elements of `FileList` that I generated by inputting some files to `<input type="file" multiple />` using `console.log`. After that, I googled necessary elements making ways and making testing code.

---
The original article is the following. This article was translated from Japanese to English.
{% embed https://zenn.dev/akira_kashihara/articles/a1fc27dd2b2898 %}
Svelte: Labeled Statements
Tags: svelte, codenewbie, javascript, beginners
Published: 2022-05-02 01:01:10

What is the $: in Svelte? 

> Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the $: JS label syntax. 

Label statements can be seen in vanilla JavaScript in conjunction with loops and the break and continue keyword and attached.

What svelte does is it grabs this $: statement and we can add a dynamic calculation based on some other value.
`$: uppercaseName = name.toUpperCase();`

Here name.toUpperCase is a built in JavaScript Method and upperCaseName is a variable. 

Svelte will recalculate the value for us whenever the name changes.
Getting hired as a software engineer in Poland vs UK
Tags: career, beginners
Published: 2022-05-02 00:32:42

Before moving to London in August 2021, I had spent 3 years working as a software engineer at 3 different companies in Poland and interviewed at over a dozen. I then interviewed at several software companies in London and eventually got hired by [Intercom](https://www.intercom.com/).

In this video I share the top five differences I noticed between looking for a job in Poland and in the UK. The advice is generic enough to be relevant to other countries as well.

 {% embed https://youtu.be/Doi5Ilx1JuM %}

[Subscribe](https://www.youtube.com/channel/UCwkrS1KQCC9jlTriI6m9xuQ?sub_confirmation=1) to my channel if you don't want to miss upcoming videos about building a career in tech ❤️
How to make a static method accessible only in its class and subclasses in TypeScript?
Tags: typescript
Published: 2022-05-02 00:00:00

---
  title: How to make a static method accessible only in its class and subclasses in TypeScript?
  published: true
  tags: TypeScript
  date: Mon May 02 2022 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/make-static-methods-accessible-only-in-class-subclass-typescript
  cover_image: https://melvingeorge.me/_next/static/images/main-ae94d2aa7e50ed0a6801540535f68fa0.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/make-static-methods-accessible-only-in-class-subclass-typescript)
  
To make a static method accessible only in its class and subclasses, you need to make the static method into a protected static method using the `protected` keyword before the static method in TypeScript.

### TL;DR

```ts
// a simple class
class Person {
  name: string;
  age: number;

  // a protected static method
  protected static sayHi() {
    console.log("Hi, Person!");
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// the `sayHi` static method
// cannot be accessed from outside the class
Person.sayHi(); // This is not allowed now ❌
```

For example, let's say we have a class called `Person` with 2 fields, a constructor, and a static method like this,

```ts
// a simple class
class Person {
  name: string;
  age: number;

  // static method
  static sayHi() {
    console.log("Hi, Person!");
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// the `sayHi` static method
// can be accessed from outside the class
Person.sayHi(); // This is allowed now
```

Currently, in the above class, the `sayHi` static method is public and can be accessed from outside the class.

To make it only accessible within the `Person` class and any other classes that extend the `Person` class (subclasses), we need to add the `protected` keyword before the static method like this,

```ts
// a simple class
class Person {
  name: string;
  age: number;

  // a protected static method
  protected static sayHi() {
    console.log("Hi, Person!");
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// the `sayHi` static method
// cannot be accessed from outside the class
Person.sayHi(); // This is not allowed now ❌
```

As you can see from the above code that when we try to access the `protected static method` called `sayHi` from outside the class, the TypeScript compiler is showing an error saying `Property 'sayHi' is protected and only accessible within class 'Person' and its subclasses.`, which is what we want to happen.

We have successfully made the static method to be accessible within its class and subclasses only in TypeScript. Yay 🥳!

See the above code live in [codesandbox](https://codesandbox.io/s/make-static-methods-accessible-only-in-class-subclass-typescript-oc1dc9?file=/src/index.ts).

That's all 😃!

### Feel free to share if you found this useful 😃.

---
Coding partner
Tags: javascript, react, node, reactnative
Published: 2022-05-01 23:08:14

Just wondering if anyone have a same thought as me, or looking for same thing in other words. Coding partner || plural(partner) who with it would be more exciting && more engaging to learn code. Do code reviews, implement best practices, try to write as clean code as possible, try to implement intermediate and up level designs and so on. I guess it's really common among developers/programmers to be socially distinct, this is not exclusion to me unfortunately. My background: Started my self-taught coding journey couple of years ago, my personality did not let me to sleep at night if I didn't understood the concept clearly this led to wide and more than inch deep knowledge which I would love to apply in conditions such as coding with colleague. Why up to this point I haven't found someone? Simply because non of the people who are surrounding me are interested in such a things. 

Things I had the most interest in ( ordered for convenience ):
 
Javascript, Typescript ( just started ), NodeJS, Java, React, React-Native, MongoDB, PostgreSQL, GraphQL, REST API, HTTP, WebSockets, Docker, Unix, OS, Networking. 

At least to hear that I'm not alone in this world would be nice.

Best wishes
Day 23: Second article !
Published: 2022-05-01 22:23:57

Last 13 days I published my first article and here we are now the second article down! I think we are actually going somewhere. I was supposed to write on the paper but I ended up on the article that I kept pushing for the whole week and I was able to complete it for the next go so I think I'm going to get started on the next one that would be about `setting up tailwind`, `setting up redux`, `getting started with docker` or `setting continious integration with github actions` one in these 
tomorrow I don't have any plan but I hope it may be a good one at I least I should keep the good momentum 
we will see

signing off...
How to Utilize Vercel
Published: 2022-05-01 22:08:52

## What is Vercel
Simply put, Vercel is an easy to use and very powerful tool to build, launch deploy and maintain any kind of site you want. Vercel is a "Function as a Service" platform which is a type of cloud-computing service that allows the execution of code in response to triggers without having to go through all the steps associated with building and launching microservices. Of course, the service is "free" but a paid membership gives you access to more features, however, a free account should suffice for most users needs. 
## Get Started
To get started simply go to vercel.com and create an account. Since I primarily use github, I created an account with my github account. After you create your account, you'll be at the vercel dashboard.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ygddd24g1veq2relkc83.PNG)
Next simply click the New Project button. Immediately afterward you will be asked which repo you want to import.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onvsos3kcean8ga5ic9v.PNG)
Vercel will then present a page with configurations you can alter, this includes things such as the root directory, build and output settings and Environment variables. After setting the configurations the way you like, simply click the blue Deploy button and watch as Vercel deploys your website for you.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vivaclc8ny2oh1y660xs.PNG)
Just like that its done!
[Link](https://eleventy-base-blog-roan.vercel.app)

## My Experience with Vercel
My background in web development is very limited, I only started with Micro front end services a few months ago. That's my background, someone who never used a service like this before and never needed to. However, Vercel was like a dream to use. I simply imported my repo and clicked deploy and it worked! It was just simple and it worked. If I continue to need to deploy sites or test components, I will always use vercel before any other method.

## Why Vercel over other CI/CD Methods?
Simply put the answer is simplicity. Vercel allows you to skip multiple steps, which eliminates the chance that errors occur during that step. It allows developers to deploy and test web components in easiest way possible, and when deployment and testing is easier, development itself gets slightly easier as well. After all, isn't that what web developers want? Something to make their lives easier that actually works?
5 CSS properties you don't know
Tags: css, productivity, web3
Published: 2022-05-01 21:29:55

CSS has a large number of properties and you can create amazing things from it.

We are all aware of the basic properties, but do you not know about some of its hidden gems , that'll surely blow your mind?!
In this article, we'll cover some amazing properties which are not commonly used.


- Caret Color

The `caret-color` property specifies the color of the cursor(caret) in inputs, textareas, or any element that is editable.
The caret is typically a thin vertical line that flashes to help make it more noticeable.

```
input {
caret-color: red;
}
```

- Backface visibility

The `backface-visibility` defines whether or not the back face of an element should be visible when facing the user.
The default for `backface-visibility` is visible. Instead of it being visible, you can even hide it.

```
.box {
backface-visibility: hidden;
}
```

- Tab-size

The `tab-size` specifies the width of a tab character.
The default value for the `tab-size` property is 8 space characters, and it can accept any positive integer value.

```
pre {
tab-size: 16;
}
```

- Isolation

The `isolation` property defines whether an element must create a new stacking content.
Stacking content refers to how elements on a webpage appear to sit on top of other elements.

```
#element {
isolation: isolate;
}
```

- Resize

The `resize` property defines if and how an element is resizable by the user. You can simply resize the element by clicking and dragging the bottom right corner of the element.
*This property does not apply to inline elements or to block elements where overflow is set to visible.*

```
textarea {
resize: none; /* Disables resizability */
}
```

> We can do pretty much everything with CSS.
Tips to 5-hour small web apps / games
Tags: javascript, webdev, discuss
Published: 2022-05-01 21:38:34

Please, let me tell tips to develop small web app / game projects that I can build - based on:

- 5 hour without creating design
- without help by paid third party services
- it should do something interesting and understandable
- it should be original

I will design and specify these projects on stream in advance. Then I will plan a schedule for 100 days.
That means that I want to build 20 project in 100 days - 5 days on one project (1 day -> 1 hour)🤟🏽.

**GOAL**:

- to have documented how I created these 20 projects
- good for resume 😆

**IDEAS**:
_1/20_ | Aim trainer for FPS games with sensitivity adjusment
_2/20_ | Chatbot - chat with my cat
_3/20_ | The best bmw for me - questionnaire with result of what type of bmw is best for me
_4/20_ | crosswords
_5/20_ | Drift angle checker from photo with opportunity to change the photo from url

Please, let me tell if you have other ideas.
Performing Linux Quickly and Easily! :)
Tags: linux, tutorial, productivity, devops
Published: 2022-05-01 21:22:21

Tutorial with Settings and Tips to Improve Linux Performance
have you ever felt your linux slow or needed more performance? Your linux computer can be faster? Discover this and more in the post below!

This post on Medium is a set of settings, programs, and tips to improve Linux performance; use at your own risk, entirely at your own risk.

To learn more, visit:

https://jlgjosue.medium.com/performing-linux-quickly-and-easily-72643901fd06
Enabling hardware virtualization Fedora Linux
Tags: linux, fedora
Published: 2022-05-01 21:12:11

Run the following command
```
sudo dnf install @virtualization
```

After the packages install, start the libvirtd service
```
sudo systemctl start libvirtd
```

Run this command to start the service on boot
```
sudo systemctl enable libvirtd
```

---
## Reference
- [docs.fedoraproject.org](https://docs.fedoraproject.org/en-US/quick-docs/getting-started-with-virtualization/)
C++da Operators
Published: 2022-05-01 21:09:01


Operatorlar ikkiga turga bo'linib, ular quyidagilar:
**binary**(+,/,*,-)

**unary** 

## Arithmetic operators

- / amalini bajarayotganda, ma'lumotni turi muhim bo'lib, kasr son kasr songa, butun son butun songa bo'linayotganini bilish kerak, yo'qsa misolni javobida o'zgarish bo'ladi.

- *modulus* faqat butun sonlar ustida amallarni bajaradi.

- amallar matematika bn bir xildek ketma ketlikda bajariladi.

- **shortcuts**
 - a += 1
 - a *(/, -, %)= 4
 - faqat ushbu qiymatlar uchun shortcut mavjud:
   - * a += 1* --> **a++;**
   - * a -= 1* --> **a--;**

## **Danger**

`++x` --> increase x by 1 and do other operations
`x++` --> do other operations and increase by 1
`--x` --> decrease x by 1 and do other operations
`x--` --> do other operations and decrease by 1

- **sample** 
int x =5;
int y =x++;

cout << x << y << endl;

after running, the answer is---> 6 5

## **Relational operator**

- relationship between left and right sides
- result is always either True(1) or False(0)
- `operators`-- <, <=, ==, >=, >, !=

## **Logical operators**

- !=not
- &&=and--> hammasi to'g'ri bo'lishi shart.
- ||=or --> 1tasi to'g'ri bo'lsa ham, hisobga o'taveradi.
FAKE NEWS DETECTION WITH PYTHON
Published: 2022-05-01 20:51:17

Fake news is one of the biggest problems with online social platforms.We can using machine learning for fake news detection. In this article, I will walk you through the task of Fake News Detection with Machine Learning using Python.Here is the basic workflow.

```
#we're loading data into our notebook
#we load in the necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB

```
After importing the relevant libraries we have to load in our d

```
#importing our data through pandas
data=pd.read_csv('/content/drive/MyDrive/news.csv')
```
After loading the data, let us examine it. It is usually not recommended to throw all the data into a predictive model without first understanding the data. this would often help us improving our model.

```
#we check our first five rows and columns
data.head()
```
Missing data values can really mess our model. It's crucial to check whether there are some missing data and fill them. For our case we didnt have any missing values.
```
#To check whether our data have missing values
data.isnull().sum()

```
Machine learning algorithms cannot understand texts(categorical values)and thus we have to convert them to numeric data.

We will convert our 'label' into 1 and 0 using the lamda function.

```
data['label'] = data['label'].apply(lambda x: 1 if x == 'REAL' else 0)
```
For our other categorical features we will use function dummies from pandas library.

```
dummies=pd.get_dummies(data[['title','text']])
```
Afterwards we split our data into x and y variables.
```
#we split our data into x and y
x=data.drop('label',axis=1)
y=data['label']
```
Lastly we will fit our model using RandomForestClassifier.

```
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split

np.random.seed(42)
x_train,x_test,y_train,y_test=train_test_split(dummies,y,test_size=0.2)
model=MultinomialNB()
model.fit(x_train,y_train)
model.score(x_test,y_test)

```
So this is how we can train a machine learning model for the task of fake news detection by using the Python programming language.I hope you liked this article on the task of Fake News detection with machine learning using Python.
What if you lost everything tomorrow?
Tags: discuss, mentalhealth
Published: 2022-05-01 20:50:18

Would you still be spending 8+ hours a day on that work project instead of the dream business you always said you would build? Would you still be putting up with any half-efforts in any area of your life when you know you're putting in 1000%?

What would you do differently today if you knew nothing else mattered but you and yourself tomorrow? It changes a lot, doesn't it? So, why doesn't it today? What's holding you back?
Best books to read
Tags: leadership, books
Published: 2022-05-01 20:20:51

Traction by Gino Wickman

Entrepreneur Operating System (EOS)

Extreme Ownership by retired US Navy Seal Jocko Willink

“Start With Why” by Simon Sinek

 modern SaaS environments is "An Elegant Puzzle - Systems of Engineering Management" by Will Larson.

"Andy Grove's High Output Management”.

“Just Listen” by Mark Goulston
DETECTING FAKE NEWS WITH PYTHON AND MACHINE LEARNING
Published: 2022-05-01 20:11:29

## Fake news
 fake newsis a big issue in the internet and social media.
**machine learning** tend to stop the problem of spreadin of fake news to some point due to use of natural language processing.

## natural language processing
In-text preprocess we are cleaning our text by steaming, lemmatization(Converting the word or token in its Base form), remove stopwords, remove special symbols and numbers, etc. After cleaning the data we have to feed this text data into a vectorizer which will convert this text data into numerical features.
**cleaning data**
this is the removal of unusable words and special symbols
**vectorizer**
converts text data to numerical features which is then used in the news detection

## Machine learning classifiers
Classifier is an algorithm that is used to map the input data to a specific category.
machine learning classifiers are using for different purposes and these can also be used for detecting the fake news. The classifiers are first trained with a data set called training data set. After that, these classifiers can automatically detect fake news.
Logger Rate Limiter
Tags: leetcode, design, hashtable
Published: 2022-05-01 20:01:52

---
title: Logger Rate Limiter
published: true
description: 
tags: leetcode, design, hashtable
//cover_image: https://direct_url_to_image.jpg
---

###
Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t will prevent other identical messages from being printed until timestamp t + 10).

All messages will come in chronological order. Several messages may arrive at the same timestamp.

Implement the Logger class:
```
1. Logger() Initializes the logger object.
2. bool shouldPrintMessage(int timestamp, string message) Returns true if the message should be printed in the given timestamp, otherwise returns false.
```
---


```
var Logger = function() {
    this.map = new Map();
};

Logger.prototype.shouldPrintMessage = function(timestamp, message) {
   if(this.map.has(message)){
       const prevTime = this.map.get(message);
       if(timestamp < prevTime + 10) return false;
   }
   this.map.set(message, timestamp);
   return true;
};
```