teleren/devto huggingface dataset:
Run MongoDB sharded cluster in one Docker container
Tags: mongodb, docker
Published: 2022-08-13 03:35:02

---
title: Run MongoDB sharded cluster in one Docker container
published: true
description: 
tags: 
    - mongodb
    - docker
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

I created a docker image to run a MongoDB sharded cluster in one container. It's hosted on Docker Hub:
https://hub.docker.com/r/a2ikm/sharded-mongo

You can run it like the original `mongo` image:

```
$ docker run --rm --publish 27017:27017 a2ikm/sharded-mongo
```

It should be useful if you run an application on a sharded cluster and also want to run its CI on the same coodination.

Actually, I've introduced it to the CI of [mongo_mapper gem](https://github.com/mongomapper/mongomapper). It helps me test it against compatibility changes of MongoDB which affects only a sharded cluster.

If you are interested, please take a look it :smile:
Thanks!
Overcome CORS errors during development in Chrome
Tags: cors, webdev
Published: 2022-08-13 03:03:00

## What is a CORS error?
Cross-Origin Resource Sharing (CORS) allows the website of one URL request data from a different URL.
**CORS error** is a mechanism to restrict users from accessing shared resources.

The browser blocks this to fight one of the most common cyber attacks i.e. cross-site request forgery.
The browser, therefore, throws an error every time, the website tries to fetch data from a different base URL.

To overcome CORS errors in Google Chrome, we need to disable the web security of the browser.

Please follow the below-mentioned steps:
1. Open `Start` window
2. Search `Run` and open it or press `Window `+ `R`
3. Paste `chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security` and execute it

This will open a new browser with web security disabled. 
You can now access your project in this browser without worrying about the CORS errors.

**Note:** This is a temporary fix and should only be used during the development phase.

Happy Coding!

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

Follow us on [Instagram ](https://www.instagram.com/commitandpush/)
Full ES2022 Cheatsheet!
Tags: javascript, node, webdev, es2022
Published: 2022-08-13 00:46:00

PDF version here(High Quality): https://www.linkedin.com/posts/activity-6942202973657702401-ZX6Y


![Intro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9rsobaim9xhn4p5ttu9.jpg)

![hasOwn](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/km91kardxjmnknmf1t2s.jpg)
 
 
![private fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tyybhn4q2bo75x85a6g.jpg)


![Array.at](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxjdzmnff4fbxdb7m2dp.jpg)


![top level await](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7dxwg02hni2tlhx7kx7h.jpg)


![error cause](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/thhp7s8acrp9x3yhopqi.jpg)



![error cause example output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uj8zy5ccof085ekxr7g.jpg)



![regex match indices](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6a2snhmp93507kmboan.jpg)



![static fields and methods](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jtrcb8sit7dt5vh01vd3.jpg)



![class static init blocks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aaloqbqq50055i9wq4a6.jpg)


![brand checks for private fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmiptyoxa2nde06d23cp.jpg)



![Outro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e540oo49mwtuffmcjidg.jpg)
Add support for i18n in your nuxt3 application
Tags: nuxt3, i18n
Published: 2022-08-15 12:16:20

---
title: Add support for i18n in your nuxt3 application
published: true
date: 2022-08-13 00:00:00 UTC
tags: ['nuxt3','i18n']
canonical_url: https://www.codef.site//blog/nuxtjs/add-support-for-i18n-in-your-nuxt3-application
---
!["nuxt3 i18n support"](https://www.codef.site/img/nuxtjs/nuxt3-i18n.png)
<alert><template v-slot:title=""></template><p>The time i am writing this article, latest nuxt version is -&gt; v3.0.0-rc.8</p></alert>

If you have already a nuxt3 project, then skip this section.

## Installation
```bash
 npx nuxi init nuxt-i18n
```

Install dependencies with <code-inline>npm i</code-inline>.

## Adding @intlify/nuxt3

Run below command to install @intlify/nuxt3 as dev dependency, then add <code-inline>@intlify/nuxt3</code-inline> in modules section of <code-inline>nuxt.config.ts</code-inline>.

```bash
 npm install --save-dev @intlify/nuxt3
```

```js
modules: ["@intlify/nuxt3"];
```

Now add the options for <code-inline>@intlify/nuxt3</code-inline> below of modules, you can also provide <code-inline>vueI18n</code-inline> options as this package is built on top of vueI18n.

```js
 intlify: {
        localeDir: 'locales', // this the path for languages json files
        vueI18n: {
            // you can add vueI18n option here
        }
    }
```

## Create languages files

Create new directory inside your project's root folder named <code-inline>locales</code-inline>, Note: this name should have to be same as provided in <code-inline>intlify:'locales'</code-inline>. Since this is the directory that this package will look for json files.

Inside those two json files add the languages key and value you want to change.

```json
//en.json
{
    "hello": "Hello {name}!",
    "language": "Language"
}
```
```json
//fr.json
{
    "hello": "Bonjour, {name}!",
    "language": "Langue"
}
```
## Ready to Test

There is global function that is provided by this package named `$t(<key>,{<param>})`.

```vue
<template>
    <div>
        <h1>{{ $t("hello", { name: "Fazail" }) }}</h1>
        <form>
            <label for="locale-select">{{ $t("language") }} </label>
            <select id="locale-select" v-model="$i18n.locale">
                <option value="en">en</option>
                <option value="fr">fr</option>
            </select>
        </form>
    </div>
</template>
```

In the above code <code-inline>"hello"</code-inline> is the key, and name is the parameter that will be replaced by the same keyword used inside `"{keyword}"` [Check here more details](https://vue-i18n.intlify.dev/). Notice we have binded the global <code-inline>$i18n.locale</code-inline> variable with v-model. So whenever we select a new value language will change. Note: select's option value should be same name of the corresponding language file.
Use Page Object Pattern in React Component Tests
Published: 2024-05-25 13:26:23

---
title: Use Page Object Pattern in React Component Tests
published: true
date: 2022-08-13 00:00:00 UTC
tags: 
canonical_url: https://blog.tomoyukikashiro.me/post/page-object-pattern-in-react-component-tests
---

My understanding is that readability and maintainability are domains which should be put high priority in software tests. To achieve this, using `Page Object Pattern` might be a good help not only in E2E tests but also React Component tests.

## What is the Page Object Pattern

[https://webdriver.io/docs/pageobjects/](https://webdriver.io/docs/pageobjects/)

Page Object Pattern is one of the software programming principle which encapsulate page manipulation logic that tend to harm readability and maintainability in software tests.

Software test involves two kinds of cods below.

- test code : e.g. Shows error messages when invalid email is typed in form.
- manipulation code to reproduce test situation : e.g. Shows page then type email

Page Object Pattern aims to move the latter codes to page class, which is called Page Object, to help software engineers read and write the former codes easily.

## The example of Page Object Pattern

Let’s see [https://webdriver.io/docs/pageobjects/](https://webdriver.io/docs/pageobjects/)

```
// Page class has E2E test instance which comes from test library such as selenium.
import Page from './page'

class LoginPage extends Page {

    // Defines some functions to manipulate page to reproduce test situation.
    get username () { return $('#username') }
    get password () { return $('#password') }
    get submitBtn () { return $('form button[type="submit"]') }
    get flash () { return $('#flash') }
    get headerLinks () { return $$('#header a') }

    async open () {
        await super.open('login')
    }

    async submit () {
        await this.submitBtn.click()
    }

}

export default new LoginPage()

```

By using this page instance to prepare test cases, we can make test codes simple.

```
it('should deny access with wrong creds', async () => {
    await LoginPage.open()
    await LoginPage.username.setValue('foo')
    await LoginPage.password.setValue('bar')
    await LoginPage.submit()

    await expect(LoginPage.flash).toHaveText('Your username is invalid!')
})

```

## How to use Page Object Pattern in React Component tests

```
import type { ComponentProps } from "react";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import LoginForm from "./LoginForm";

type Props = ComponentProps<typeof LoginForm>

const setup = (props): Props => {
  const { getByRole, getByLabelText, getByText } = render(<LoginForm {...props} />);
  return {
    typeEmail: (email: string) => userEvent.type(getByLabelText("email"), email),
    getByText,
    submit: () => userEvent.click(getByRole("button"))
  };
};

it("When email typed is invalid, shows error message.", () => {
  const utils = setup();
  utils.typeEmail("invalidemail");
  utils.submit();

  expect(utils.getByText("Email is not correct.")). toBeInTheDocument();
});

```
How to change ownership of a file in Nodejs?
Tags: node, nodejstip, javascript
Published: 2022-08-12 23:36:00

As for our last permissions and access related methods, today we talk about the 𝗰𝗵𝗼𝘄𝗻 method.

It lets you change the ownership of a file. Just like you're used to on your terminal:

𝗰𝗵𝗼𝘄𝗻 <𝗨𝘀𝗲𝗿><:><𝗚𝗿𝗼𝘂𝗽> <𝗙𝗶𝗹𝗲>

𝗡𝗼𝗱𝗲𝗷𝘀 provides support for it natively; so you won't have to spawn a process to access this API.

You can check the updated values with this basic list command:

𝗹𝘀 -𝗹 <𝗙𝗜𝗟𝗘>

![change ownership](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlwn6vek60tsv1e61d6z.png)

----------------------

Did you learn something new today?

Like and share this post, and follow me for more!
linux command: apt-get
Tags: linux, opensource, command, beginners
Published: 2022-08-12 23:22:58

apt-get
apt 2.2.4 (amd64)
Usage: apt-get [options] command
       apt-get [options] install|remove pkg1 [pkg2 ...]
       apt-get [options] source pkg1 [pkg2 ...]

apt-get is a command line interface for retrieval of packages
and information about them from authenticated sources and
for installation, upgrade and removal of packages together
with their dependencies.

Most used commands:
- update - Retrieve new lists of packages
- upgrade - Perform an upgrade
- install - Install new packages (pkg is libc6 not libc6.deb)
- reinstall - Reinstall packages (pkg is libc6 not libc6.deb)
- remove - Remove packages
- purge - Remove packages and config files
- autoremove - Remove automatically all unused packages
- dist-upgrade - Distribution upgrade, see apt-get(8)
- dselect-upgrade - Follow dselect selections
- build-dep - Configure build-dependencies for source 
  packages
- satisfy - Satisfy dependency strings
- clean - Erase downloaded archive files
- autoclean - Erase old downloaded archive files
- check - Verify that there are no broken dependencies
- source - Download source archives
- download - Download the binary package into the current 
  directory
- changelog - Download and display the changelog for the 
  given package

See apt-get(8) for more information about the available commands.
Configuration options and syntax is detailed in apt.conf(5).
Information about how to configure sources can be found in sources.list(5).
Package and version choices can be expressed via apt_preferences(5).
Security details are available in apt-secure(8).
                               This APT has Super Cow Powers.
How to secure pages with HTTP Basic Auth using SvelteKit
Tags: svelte, sveltekit, javascript, typescript
Published: 2022-08-12 23:22:31

_Originally [posted on my blog](https://danawoodman.com/writing/sveltekit-http-basic-auth)._

---

Want to add simple authentication to a page, say an admin section or a demo app, in SvelteKit? Well, [HTTP Basic Auth](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication) might be what you're looking for.

But before we start, you should be aware that HTTP Basic Auth is not considered very secure since you're sending the username/password as base64 encoded, [amongst other concerns](https://security.stackexchange.com/a/990). If you use HTTPS (which you should be doing!), then this particular attack vector is less of a concern, but you should still consider these factors and you should **absolutely not use it with customer/user facing logins**. I see HTTP Basic as a useful and quick way to (somewhat) secure a page or section on your site. If you choose HTTP Basic, just be aware that the pages you're securing may not be as secure as you might think.

Ok, moving on!

In order to accomplish this, we will need to intercept all server-side requests using the [`handle` hook](https://kit.svelte.dev/docs/hooks#handle) which gets called on every request.

We will then check the URL pathname to see if it starts with `/admin` so that any page under and including `/admin` will get secured behind HTTP Basic Auth (e.g. `/admin`, `/admin/reports`).

Then we check for an `Authorization` header to see if the user has attempted logged in (or if they cancel the login dialog) and we check it against a username:password combo (base64 encoded). If it doesn't match, then they are not logged in so we indicate they're not authorized with a `401` error.

If they succeed with login by typing in the correct username:password combo, then they will be directed to the admin page they wanted.

```ts
import type { Handle } from "@sveltejs/kit";
import { ADMIN_LOGIN } from "$env/static/private";

export const handle: Handle = async ({ event }) => {
	const url = new URL(event.request.url);

	if (url.pathname.startsWith("/admin")) {
		const auth = event.request.headers.get("Authorization");

		if (auth !== `Basic ${btoa(ADMIN_LOGIN)}`) {
			return new Response("Not authorized", {
				status: 401,
				headers: {
					"WWW-Authenticate":
						'Basic realm="User Visible Realm", charset="UTF-8"',
				},
			});
		}
	}

	return resolve(event);
};
```

Then, in your `.env` file (as well as set in your hosting provider's environment variable management system), set your username/password combo:

```shell
ADMIN_LOGIN="admin:sekret"
```

And now make sure to create a page at `/admin` or somewhere else and attempt to load it. You should see the login prompt and on inputting `admin` for the username and `sekret` for the password, you should see the admin Svelte page.


---

_Follow me on [Dev.to](https://dev.to/danawoodman), [Twitter](https://twitter.com/DanaWoodman) and [Github](https://github.com/danawoodman) for more web dev and startup related content_
MVC-What is it?
Tags: mvc, react, ruby, beginners
Published: 2022-08-12 22:39:04

MVC is a software design pattern that separates the data, layout, and routes. This creates a division of labor or "separation of concerns" that allows for easier maintenance.

#Model
The model decides what data the app should hold. If data changes then the model will tell the view.
In a rails/react application the models would be located within the app folder and they would be written in ruby.

#View
The view is the screen of the app the decides which data to display.
In a rails/react application this would be the react portion. The front-end which displays the data to the end-user.

#Controller
The controller possesses logic with the ability to update the models and/or view in response to actions from the end-user.
In a rails/react application the controllers would be located within the app folder and they would be written in ruby.



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

sources: https://developer.mozilla.org/en-US/docs/Glossary/MVC
Day 613 : Back of My Mind
Tags: hiphop, code, coding, lifelongdev
Published: 2022-08-12 22:19:36

_liner notes_:
- Professional : So the company has been doing these Refreshed Fridays where we get off early. I got the final form I needed for my visa so I put together the package and got it shipped out. Fingers crossed I get it back soon. A video I made got posted today so I made a social media promo and got that posted. Did some interaction on Twitter. Next thing I know, it was time to call it a day.

- Personal : Last night, I did some review of the Japanese I've been studying. I forgot so much. haha Most of the time, I almost had it. I know what the characters mean, I just don't know how to say them. Getting there. I need to be more consistent. Now that the major part of the new feature for my site is live, I can get back to studying more. I also went through some tracks for the radio show.

![View from a rainforest looking at at cloud covered mountain in the distance in El Castillo, Costa Rica](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/io901lvavlc352u5e3kl.jpg)

Once I finished up with work, I went straight to working on the radio show. There was something in the back of my mind that I knew I forgot. It wasn't until just know that I was like, "oh yeah, my blog post!" haha. Got to stay consistent. Good news is I basically figured out the tracks I want to start the show off with. Just need to make sure everything is clean and put it on my player, put it in order, update the playlist and get all the social media stuff done. I also did a quick proof of concept for a new thing I need to add to my website that broke because the site I was paying to get data from changed how they are serving the data. I think I may have found a work around and it gives me an opportunity to make the dashboard I've been meaning to make. So yeah, radio show stuff then review my Japanese lessons.

Have a great weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube p3PtCyPmoCg %}
Golang perk series : structs – pass_by_reference #7 | (pointers-again)
Tags: webdev, javascript, node, go
Published: 2022-08-12 22:12:07

In earlier we get know with pointers & later structs, now we use both : yes, pointers again , folks !

> Before digging into code worth to underline one more time – **Golang is pass-by-value language**, so pointers enables us to pass-by-reference so modifying original value, struct, etc.

> **TIP** : REPLIT IDE named "structs" was updated with extra couple of files :

- pass-by-reference--before.go (pass-by-value)

- pass-by-reference--after.go (pass-by-reference)

{% replit @projektorius96/structs %}

> **NOTE** : All explained in the code : refer to comments, pay extra attention at steps 1/2) & 2/2)

---

Interfaces coming shortly, stay tuned !
Golang perk series : structs & partial inheritance with embedded structs #6.1
Tags: webdev, javascript, node, go
Published: 2022-08-12 22:03:00

> TL;DR : Sructs in Go enables us to define custom types , yes I said type**S** (in plural!), upon which is passed type checking on build (compile-time) can instantiate "object-like" blueprint of data : hereby I mentioned "object-like" as we going to compared "non-comparable" with JavaScript objects mocking struct-like behaviour, whilst utilising a small extendible utility [called – _is](https://github.com/projektorius96/_is) I've recently written for this purpose (the later example) :

<u>In Golang</u> :

> TIP : refer to structs_factory.go on REPLIT IDE in File Explorer

{% replit @projektorius96/structs %}

<u>Meanwhile in JavaScript</u> :

> TIP : refer to structs_factory.js on REPLIT IDE in File Explorer

{% replit @projektorius96/is-currentv2 %}
Golang perk series : *pointers in Go – basics #5
Tags: webdev, javascript, node, go
Published: 2022-08-12 21:59:00

### <u>Pointers in Go := pass-by-reference</u> :

> Please refer to the sample by the name of `pointers.go` on REPLIT IDE

Before getting into pointers I want to examine this pseudo_code:
```go
var pointer_variable *T = &another_variable // <= herein we defined a "pointer-to-memory" pair
/* 
such pair could either:
a) be referenced using ampersand (&), subsequently getting memory address
b) be DE-referenced using asterisk (*), subsequently getting UNDERLYING VALUE of memory address
*/
```

{% replit @projektorius96/funcsgo %}

JavaScript has some pass-by-reference -like behaviour with (outermost) object reference[s] but definitely none of native pointers specification [ – if you still fascinated by the idea of JS pointers, have a look at `others/ifJS_pointers.go` on REPLIT IDE ; also – [pass by reference in JavaScript, stack overflow discussion](https://stackoverflow.com/questions/2326072/javascript-function-pointer-assignment)]

> We will see advanced pointers utilisation in structs & relevant fields, stay tuned for updates !

---

### <u>Articles</u> :

- Pointer basics on [Golangdocs](https://golangdocs.com/pointers-in-golang)
Recommendation system #2 - Business objectives
Tags: webdev, programming, algorithms, redishackathon
Published: 2022-08-12 21:58:00

In the previous post, I mentioned my plan to write a recommendation system using Redis and Nodejs. In this article, we look closer at the most important business objectives.

The recommendation system I'm creating will be used in the product-based application, similar to e-commerce apps. Will be difficult to measure direct leads as it's integrated with various partners and websites and it may vary from one to another. So recommendations will be calculated based on events with different weights. 
For now, I think about something like opening product page +1 score, give a like to product +2, comment +2, go to the details +5 and so on. For each tag associated with the product composite key with the event will be created.

Back to high-level requirements, the number of products will be relatively low when compared to full feature e-commerce and up to about ~10k items. Cold start which means a situation when the user didn't make any interaction before should be solved by choosing products popular among the overall audience of users. 

The needs and tastes of the user may change so the composite of user-tag-event should expire, this can be done in Redis by setting TTL or in the more general database by WHERE clause plus maintenance worker or trigger for periodical cleanup.

In the next post, we will look more closely at the implementation. My initial thoughts are to use Redis TimeSeries to gather events and then use aggregation per composite for each user tag in a certain time span. However, it may be different as I need to dive deeper into Redis structures. If you have any advices or comments, you are welcome.