teleren/devto huggingface dataset:
Django REST Framework warning: `UnorderedObjectListWarning`
Tags: drf, warning, pagination
Published: 2023-11-08 18:11:52

While creating a basic Django REST framework project with several models and the implementation of pagination, I faced this warning in terminal:

`UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list`

I used the implementation of the [DRF website](https://www.django-rest-framework.org/api-guide/pagination/) the point: PageNumberPagination

I copied this into my settings.py file inside my project:

```python
# settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 100
}
```
and the above warning was popping up in terminal.

The explanation on the [DRF website](https://www.django-rest-framework.org/api-guide/pagination/#details-and-limitations) is, you have to order the queryset. 

DRF expects an ordering of ["-created"]. 

The names of my attributes for the creation in my models where different, "created_time" and in the User model of Django the timestamp attribute is "date_joined". So, I had to come up with something. 

<hr>
**There are two possible solutions:**

1) add in the model class the ordering:

```python 
# models.py

from django.db import models

class Project(models.Model):
    created_time = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100)
    description = models.TextField()
    author = models.ForeignKey()

    class Meta:
        ordering = ["created_time"]
```

the important part is the **ordering = ["created_time"]**. With this line of code you order the entries in your database by the create date and time.


2) add the `.order_by()` method to the queryset in the view:

```python
# views.py

class ProjectViewSet(viewsets.ModelViewSet):
    
    def get_queryset(self):
        # use order_by to avoid the warning for the pagination
        return Project.objects.filter(author=self.request.user).order_by(
            "created_time"
        )
```
You order the queryset by the timestamp when the project was created **.order_by("created_time")**.
Dockerizing NuxtJS with Bun
Tags: docker, nuxt, bunjs
Published: 2023-11-08 18:11:28

---
title: Dockerizing NuxtJS with Bun
published: true
description: Dockerizing NuxtJS App with Bun
tags: docker, nuxt, bun
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-11-08 17:44 +0000
---

## Background 💬
Previously, I'm using the old way to deploy my NuxtJS app into AWS EC2. Building the production locally, and then uploading it through sftp. It's because I don't understand yet about building a custom docker image

## Learning by Doing ✍️
The best way to learn fast is by doing. Fortunately, I've a custom `Dockerfile` for my backend using AdonisJS. My friend who created it. Then I just read all the lines from that file and asked my friend what's the meaning of each line.

Thank god he understands well about docker, so he can explain it to me very well.

## Time to Cook 🔥
### Why Bun?
Bun is a fast JavaScript package manager. And previously I was using Yarn as my main package manager. But, Bun is faster.

### First stage - Base
The first stage will be our `base` layer which will later on be used for other steps.
```
ARG NODE_IMAGE=oven/bun:1-alpine

FROM --platform=linux/amd64 $NODE_IMAGE AS base
WORKDIR /usr/src/app
RUN apk --no-cache add openssh g++ make python3 git
```

### Second stage - Installing Dependencies
Our second stage will be used to install all dependencies, so we can build our app in later stages.
```
FROM base AS install
RUN mkdir -p /temp
COPY package.json bun.lockb /temp/
RUN cd /temp && bun install --frozen-lockfile
```
If you realize, I didn't use `--production`. It's because I still need to install `devDependencies` so I can run the `nuxt` command

### Third stage - Build
We have everything to start our build phase! This very simple and self-explanatory stage.
```
FROM install AS prerelease
COPY --from=install /temp/node_modules node_modules
COPY . .

ENV NODE_ENV=production
RUN bun run build
```

### Fourth stage - Production
Finally, we can create our last stage.
```
FROM base AS release
COPY --chown=bun:bun --from=install /temp/node_modules node_modules
COPY --chown=bun:bun --from=prerelease /usr/src/app/.output .

USER bun
ENV HOST 0.0.0.0
EXPOSE 3000
ENTRYPOINT [ "bun", "run", "server/index.mjs" ]
```

## Test Locally 🤖
After I successfully built the docker image in under 5 minutes. I just need to test the docker image by running a container on my local. And I'm using Docker Desktop by the way.

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

Boom, it can run smoothly without any errors.
"Freelancing While Homeschooling": CodeNewbie Podcast S26E2
Tags: podcast, codenewbie, career
Published: 2023-11-08 18:07:27

In our second episode of Season 26 of the CodeNewbie Podcast, @saronyitbarek talks about managing the world of motherhood with a passion for coding with [Sarah Greer](https://github.com/Codegreer), Lead Web Developer at Data Driven Marketers.

{% embed https://www.codenewbie.org/podcast/freelancing-while-homeschooling %}

Sarah was a freelance developer for 9 years, working mostly at night while homeschooling her kids. She’s now working in her dream job as the lead web developer for a growing marketing company.

- [Listen on Apple Podcasts](https://podcasts.apple.com/us/podcast/codenewbie/id919219256?i=1000634112512)

- [Listen on Spotify](https://open.spotify.com/episode/2sO9BRCh7emiJFjmBNQfcd?si=05d8cf29f01b461f)

Or, listen wherever you normally get your podcasts!

***

### We will see you next week, happy coding

PS: Make sure to subscribe to the CodeNewbie podcast if you haven't yet + review us on your chosen platform!
How to build Single Sign-On for your Web App
Tags: webdev, security, tutorial, javascript
Published: 2023-11-08 18:03:07

Single sign-in (SSO) is a popular enterprise feature for web applications. It permits users to log in to multiple applications with one set of login credentials, resulting in improved user experience and increased security. 

What are the considerations to take into account when building an authentication model with SSO? What are the different components needed to implement SSO on your web app?

I wrote [an article](https://www.dolthub.com/blog/2023-11-08-building-sso-for-your-web-app/) that answers these questions and goes through the steps to build SAML SSO for your web app. Check it out and let me know what you think!

https://www.dolthub.com/blog/2023-11-08-building-sso-for-your-web-app/
several ways to create a simple url
Published: 2023-11-08 17:59:54

## 1. example: to create a simple url with a BASE_URL veriable

```python
# settings.py

BASE_URL = 'http://127.0.0.1:8000'
```

```python
# views.py

from django.conf import settings

class CommentViewSet(SerializerClassMixin, ModelViewSet):

    def perform_create(self, serializer):
        project_pk = self.kwargs["project_pk"]
        issue_pk = self.kwargs["issue_pk"]

        issue_url = f"{settings.BASE_URL}/api/projects/{project_pk}/issues/{issue_pk}/"
```

<hr>

## 2. example: create BASE_URL in your operating system

Define the base URL as an environment variable in your operating system. The process for this varies depending on your operating system. For example, in a Unix-based system like Linux or MacOS, you can add the following line to your shell profile file (like `~/.bashrc` or `~/.bash_profile` for Bash shell, `~/.zshrc` for Zsh shell).

```bash
export BASE_URL="http://127.0.0.1:8000"
```

Then, source the profile file or restart your terminal to apply the changes:

```bash
source ~/.bashrc
```

In your Python script, use the os module to access the environment variable.

```python 
# views.py

import os

class CommentViewSet(SerializerClassMixin, ModelViewSet):
    BASE_URL = os.getenv("BASE_URL")

    def perform_create(self, serializer):
        project_pk = self.kwargs["project_pk"]
        issue_pk = self.kwargs["issue_pk"]

        issue_url = f"{BASE_URL}/api/projects/{project_pk}/issues/{issue_pk}/"
```

<hr>

## 3. example: save the BASE_URL in an `.env` file

First, you need to install the `python-dotenv` module. You can do this using pip, which is a package manager for Python. Run the following command in your terminal.

```bash
pip install python-dotenv
```
This command installs the `python-dotenv` module, which allows you to specify environment variables in a `.env` file in your project directory.

Next, create a `.env` file in the root directory of your project. This file will contain your environment variables. Each variable should be defined on a new line in the format `KEY=VALUE`. In your case, you would add the following line to your `.env` file.

```python
# .env

BASE_URL=http://127.0.0.1:8000
```

n your Python script, you can now use the `load_dotenv` function from the `dotenv` module to load the environment variables from the `.env` file. Then, you can use the `os.getenv` function to retrieve the value of the BASE_URL environment variable.

```python
# views.py

import os
from dotenv import load_dotenv

class CommentViewSet(SerializerClassMixin, ModelViewSet):
    BASE_URL = os.getenv("BASE_URL")

    def perform_create(self, serializer):
        project_pk = self.kwargs["project_pk"]
        issue_pk = self.kwargs["issue_pk"]

        issue_url = f"{BASE_URL}/api/projects/{project_pk}/issues/{issue_pk}/"
```
Palestra de Roberto Ierusalimschy sobre os 30 anos de Lua
Tags: lua, lualang
Published: 2023-11-08 17:51:01

A palestra [começa aos 16 minutos da transmissão](https://www.youtube.com/watch?v=Va6i3zh4_Io&t=960s)

{% youtube Va6i3zh4_Io %}

Destaque a esta parte:

Cartas dos renomados pesquisadores recebidas em apoio à sua titularidade:

- o Professor Luiz Henrique de Figueiredo, pesquisador titular do IMPA, destaca que "essa combinação de pesquisa e inovação é o que há de melhor numa universidade de excelência"
- o professor Fábio Kon, Professor Titular do IME USP, destaca que o professor Roberto é o Cientista da Computação brasileiro cuja obra causou o maior impacto na indústria de software mundial 
- o professor Paulo Borba, Professor Titular da UFPE, diz que "Roberto é hoje amplamente reconhecido como o pesquisador brasileiro de maior destaque nacional e internacional na área de linguagens de programação".

Para os professores Matthias Felleisen, da Northeastern University, e Shriram Krishnamurthi, da Brown University, Roberto obteve uma sólida visibilidade com seus trabalhos, projetando a PUC-Rio como um centro de pesquisa de excelência internacional.
Angular @switch
Tags: angular, angular17, typescript, ngswitch
Published: 2023-11-08 17:47:47

## Angular has released the new '@switch' block syntax similar to Javascript
## 
 _How does this work?_
![Angular ngSwitch Alternative](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9w9429iezeav3wy0dft8.png)

- The `@switch` blocks displays content selected by one of the cases matching against the conditional expression

- The `@default` block is optional and can be omitted. If no `@case` matches the expression and there is no `@default` block, nothing is shown

- `@switch` does not have fallthrough, so you do not need an equivalent to a break or return statement.

[Angular docs](https://angular.dev/api/core/@switch)
¿Por qué el Deep Learning ha ganado tanto terreno en los últimos años?
Tags: machinelearning, spanish
Published: 2023-11-08 17:44:20

Una de las razones principales por la cual el Deep Learning (DL) esta siendo tan ocupado porque puede resolver problemas mucho mas complejos que lo podrían hacer otros algoritmos de Machine Learning, el algoritmo predilecto del DL son las redes neuronales, están pensadas para tener un funcionamiento al de una neurona real, en donde el resultado de una sirve como entrada de la siguiente. Además en cuanto al ámbito del hardware también ha sido un factor que ha contribuido para la proliferación de esta técnica, porque ahora se puede hacer muchos mas cálculos y reducir el tiempo de entrenamiento gracias al uso de GPU en vez de CPU.

Podemos enumerar las siguientes ventajas y desventajas de las redes neuronales.
Ventajas:
- El proceso de extracción de características ya no se hace de manera manual sino de forma automática.
- Se puede resolver problemas de regresión, clasificación binaria y multiclase. 
- El entrenamiento se puede hacer en bloques (batch), ya que normalmente se ocupa una gran cantidad de datos para esta fase.

Desventajas:
- Se necesita una gran cantidad de datos (millones) para que las redes neuronales tengan un buen desempeño en cuanto al problema que se quiere resolver.
- El costo computacional es muy alto en comparación con otros algoritmos de aprendizaje computacional mas tradicionales.
- El entrenamiento puede conllevar una cantidad de tiempo considerablemente mas grande que los algoritmos tradicionales.
Moropo - Mobile app testing made simple
Tags: testing, qa
Published: 2023-11-08 17:13:55

Moropo is a next-gen platform to create, run and maintain automated mobile app tests. It works completely in the browser with no local installation required.

Users can build tests using two modes: steps and script. Steps mode is aimed at non-tech users and has a drag-and-drop editor where users build each step (for example, Tap On or Input Text) in their test flow.

Tests can be scheduled manually, using CI or calendar-based to align best with each team's app development workflow. The tool includes dozens of iOS and Android devices.

https://www.moropo.com
Find Your Perfect Product and Supplier in Minutes!
Published: 2023-11-08 17:12:48

SaleHoo Directory is the ideal product for customers who sell on eBay/Amazon, online stores and small businesses that are looking for trusted dropship and wholesale suppliers. The Directory contains 8,000 suppliers and 1.6 million products.
**_Read More Click Here:_** https://tinyurl.com/55ebr9au
Git Work Flow and Divergence
Published: 2023-11-08 17:07:01

I started my first github repo this week, connected with visual studio, committing changes to feature branches, and merging pull requests into 'main'.

I'm bad at seeing code typos immediately after I do a pull request, correcting them too quickly, and inadvertently editing the code in main without pulling it current first. Then I stumble through how to resolve the terminal errors. It's scary to mess that up and then have github automatically edit (delete!) my local code. Whenever that happens, I'm using "git merge origin/main" to clear out the errors. Is that reasonable?

I'm also bad at naming my commits and pull requests in a useful way. The naming seems tedious. Does anyone use automation to auto-generate names and descriptions?
Angular @if
Tags: angular, angular17, typesccript
Published: 2023-11-08 17:04:20


## Angular has released the new '@if' block syntax inspired by Javascript
## 

 _How does this work?_

`@if`
> Similar to JavaScript's if statement, Angular uses `@if` to conditionally hide and show part of a template and its contents

![Angular ngIf alternative](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5duqas69hiou74nkdyam.png)
`@else`

> When you need a fallback, similar to JavaScript's `else` clause, add an `@else` block to accomplish the same effect

![Angular ngIf else alternative](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3tyrysiuf2jexdvdmun.png)

[Angular docs](https://angular.dev/essentials/conditionals-and-loops)
React Higher Order Component
Tags: hoc, react, javascript
Published: 2023-11-08 17:01:43

## Definition

If a component takes another component as an argument and returns completely new component is called a higher-order component. Higher-order components are mainly wrapper components.

## Example details:
suppose 2 component named **ClickCounter **and **HoverCounter** shares the same kind of state in there component. We can separate states from both counter and put them in Higher-order component and wrap them with **ClickCounter **and **HoverCounter **to share their state.

_ClickCounter.js_

```javascript
import React from 'react';
import withCounter from './withCounter';

function ClickCounter({ count, incrementCount }) {
        return (
          <div className="w-full flex justify-center ">
            <button
              onClick={incrementCount}
              type="button"
              className="px-6 py-2 bg-green-500 rounded-lg text-white"
            >
              Clicked
              {' '}
              {count}
              {' '}
              times
            </button>
          </div>
        );
}

export default withCounter(ClickCounter);
```
_HoverCounter.js_

```javascript
import React from 'react';
import withCounter from './withCounter';

function HoverCounter({ count, incrementCount }) {
        return (
          <div className="w-full flex justify-center mt-8">
            <h1
              onMouseOver={incrementCount}
              className="text-green-600 tex-2xl font-bold border-2 border-solid border-gray-600 p-2"
            >
              Hover
              {' '}
              {count}
              {' '}
              times
            </h1>
          </div>
        );
}

export default withCounter(HoverCounter);
```

## Higher Order Function: withCounter.js

```javascript
import React, { Component } from 'react';

const withCounter = (OrginalComponent) => {
    class NewCounter extends Component {
        state = { count: 0 };

        incrementCount = () => {
            this.setState((prevState) => ({ count: prevState.count + 1 }));
        };

        render() {
            const { count } = this.state;
            return (
              <OrginalComponent count={count} incrementCount={this.incrementCount} />
            );
        }
    }
    return NewCounter;
};

export default withCounter;
```
Understanding of CommonJS(Basics Node.js Series)
Tags: javascript, node, programming, webdev
Published: 2023-11-08 16:27:46



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


Hope you all are doing well, 

**In this micro article**, we can understand what **synchronous loading** is, it's a basics concept of Node.js, which it's uses the Commons module systems.

So, before that, let's talk about CommonJs module systems.

**CommonJS module systems**

CommonJS modules are the module system for javascript programming language which is used in server-side and non-browser environments such as Node.js

CommonJs modules allow us to organize our code, make it reusable by its characteristics of encapsulation which is where we can make easier to manage and maintain large codebases.

**Characteristics of CommonJs modules**

**Encapsulation**

- One of the key characteristics of CommonJs modules are it's encapsulation units
- it's encapsulating the code and data, preventing them to interfere with other modules
- This encapsulation is achieved by using of closures, which isolates the module scope 

**Exports and Require**

Modules can export specific values, functions or objects so this way it can be available to other modules, by `exports` or `module.exports` object.

**Synchronous Loading**

CommonJS modules are loaded synchronously, to explain if a module required then, the entire modules and it's dependencies are loaded and executed before the program continues.

So, in this way programs executes by in order, order of execution

**Conclusion**

So, Thats its guys for now, Commons modules have more characteristics but for now we are cover some main characteristics, later we explore deep dive into their characteristics with examples to understand better.

> Stay tuned for more advanced articles where we'll explore the depths of Node.js
> If you have any queries or just want to share your Node.js anecdotes, and command below

happy coding! 🚀🐉💻
What I Learned Today
Published: 2023-11-08 16:56:09

What I learned today
With ruby you can combine more than one method together. This idea helped me pass a test to encode. I used the substitute method .gsub I was able to call the gsub method more than once on a variable secret. I was also able to use .to_s method to turn my number codes into strings. For example I used secret.gsub("a", 1.to_s).gsub(ect.) this form was legal for me to do. I was surprised it worked but I have found that ruby is a user friendly lang. that is thought with programmers in mind. I am really happy to have learned lots of things with Ruby and I am sure I will continue to learn more about this amazing programming lang.
A Simple Way to Check if a Word is Palindrome in Java
Tags: palindrome, java, programming
Published: 2023-11-08 16:54:52

_Racecar_, _Civic_, _Radar_, _Level_, _Kayak_. 

What do all these words have in common? 
Try to read them backwards... did you notice anything? Of course you did!

_A palindrome word is a word that reads the same backwards as forwards_.

The scope of this article is to illustrate you a very simple yet effective way to recognize a palindrome word, using **Java**.

Let's first create a Palindrome class with a main method and an input string from above:


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


What we want now is to pass our input string to a method that will return a **boolean**: true if the word is palindrome, false otherwise.
We'll make this method static:


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


The logic we are going to use is very straightforward: we will divide the length of the input string by 2, and iterate over the string both forwards and backwards to compare, at each iteration, the couple of characters that we find. We will do that as many times as the number we obtained from the previous division. 
What if the length is odd? We will round it down!

Let's pick for example the word _kayak_:
the length is 5. Dividing 5 by 2 will give us 2.5, namely 2 (we always round it down).
Since the result of the division is 2, we will do 2 iterations. At each iteration, we compare the two characters to the left and to the right of our string. If the two characters are not the same, it means the word is not a palindrome and we return false.
If the whole loop terminates without returning false, then we return true: the word is a palindrome.

Here is the code:


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

Note: in the case of a string with an odd length, just as in our example, the middle character will not be compared to anything, since there is no need to do so.
In our example, the code executed two iterations:
- in the first iteration, character at index 0 ("k") was compared with character at index 4 ("k")
- in the second (and last) iteration, character at index 1 ("a"), was compared with character at index 3 ("a").

An additional iteration would have compared the character at index 2 with itself, which is not needed. Therefore, the code we wrote makes the loop stop before this unnecessary computation.

Please remember to pay attention to case and word separators (in case of sentences). If we used _Kayak_ as our input string, then the method would have returned false as "K" and "k" are different. The same applies when using sentences with whitespaces and punctuation, as they will affect the result. In these cases you need to take into account such additional elements, depending on the specific requirements.

Hope you found this article useful! 
See you soon, and keep coding!