teleren/devto huggingface dataset:
Port 5000 is in use by another program. Either identify and stop that program, or start the server with a different port.
Tags: python, flask, linux, webdev
Published: 2023-10-02 16:48:41

#Problems
I accidentally pressed `ctrl + z` on the terminal so that the previously running flask stopped abnormally and the port was still used

![problem](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qg1hm44wonar8zkx3p37.png)

I can't run flask again because the port is being used


![can't run flask](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2l11cov1v8rvlpgzolx5.png)



#Solution
Check what ports are being used

```
sudo ss -tulpn
```

![used port](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1s4fa9vqh2ql0m6j6v9.png)


Kill pid from the port being used
```
kill -9 4837
```

Try to run flask again
```
python3 app.py
```
upgrade old version
Tags: react, nextjs, reduxsaga, typescript
Published: 2023-10-02 16:29:52

I have a old version code with react  16.7.0 and next 6.0.3.
How can I upgrade below code to react 18.0 and next 13, I mean how can I treat :
componentDidMount(), componentDidUpdate(),
mapStateToProps , mapDispatchToProps ,withRedux, this.setState(), this.state

please give me example about old code like below
--------------------------------------------
class JobSearch extends Component {
  constructor(props) {
    //---------------
  }
  componentDidMount() {
    //-----------
  }

  componentDidUpdate(prevProps, prevState) {
     //-------------
  }
    return (
       <div></div>
    );
  }
}
const mapStateToProps = (state) => {
  const { app, posts } = state;

  return {
    location: app.location,
    keyword: posts.facets.keyword,
  };
};

const mapDispatchToProps = (dispatch) => ({
  storeKeyword: (keyword, isCompany) =>
    dispatch(setFilterKeyword(keyword, isCompany)),
});

export default withRedux(
  Store,
  mapStateToProps,
  mapDispatchToProps
)(withReduxSaga(JobSearch));
---------------------------------------------------
🚀 Unlocking the Power of AWS Lambda Layers 🚀
Tags: aws, serverless, lambda, webdev
Published: 2023-10-02 16:26:08

Hey Dev Community,

Let's dive into a game-changing AWS service that might just revolutionize the way you develop serverless applications: AWS Lambda Layers! 🚀

AWS Lambda Layers allow you to manage your in-development function code independently from the unchanging code and resources that it uses. Here's why it's a game-changer:

1️⃣ Code Separation: With Lambda Layers, you can keep your function code lean and focused while offloading common libraries, dependencies, or custom runtimes to layers. This means your deployment package is smaller, making deployments faster and reducing cold start times.

2️⃣ Version Control: You can version and manage your layers separately, ensuring that your function code always relies on the specific version of the layer it needs. No more unexpected breaking changes!

3️⃣ Reusability: Layers can be shared across multiple Lambda functions, making it easy to maintain consistent libraries and configurations across your serverless applications.

4️⃣ Cost-Efficiency: Since layers are cached, you only pay for the execution time of your function code, not the layers themselves, resulting in cost savings.

5️⃣ Easier Collaboration: When working with a team, Lambda Layers make it simpler to manage shared dependencies and resources, promoting collaboration and code consistency.

6️⃣ Custom Runtimes: You can even create custom runtimes using layers, giving you more flexibility in running your code.

If you're building serverless applications on AWS, Lambda Layers are a powerful tool that can streamline your development process and enhance performance.

Want to learn more? Check out the AWS documentation on Lambda Layers https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5iz2mn55zlosm8pu168i.png). 
Share your thoughts and experiences with Lambda Layers in the comments below. Let's unlock the true potential of serverless development together! 💡
ActiveRecord migrations
Published: 2023-10-02 16:10:31

## Models
Ruby classes that generate SQL to CRUD rows in tables

##Migrations
Ruby classes that generate SQL to create tables

Rails generator automatically writes most of our migrations. We tell it: 
- the name of the table 
- name of the columns
- datatypes

Run
`rails generate model movie title:string year:integer duration:integer description:text image:string director_id:integer
`
Two files were created
- A migration file located in `db/migrations` 
- A model file containing the schema information located in `app/models`

Run `rake db:migrate`

Output will indicate movies table has been created. Verify in `/rails/db`

Run:

`rails generate model director name:string dob:date bio:text image:string`

`rails generate model actor name:string dob:date bio:text image:string`

`rails generate model character name:string actor_id:integer movie_id:integer`

`rake db:migrate` executes migrations that haven’t been executed

`rake sample_data` contains the iMDB Top 250 list
Day 6 Basics of Web application
Tags: javascript, beginners, tutorial, 100daysofcode
Published: 2023-10-02 16:07:59

## What is Javascript

Javascript is a programming language used to convert a static webpage to dynamic webpage
the browser understands the js code because every browser has js engine in chrome V8, Spider monkey in firefox ect

## Scope of Keyword let , const , var

let block scope can only be used inside the block
const block scope can only be used inside the block
var is functional scope can be used anywhere inside and outside the block

```
{
  var a=30
  const c=10
  let b=20
  console.log("inside block",a,b,c)
}


console.log("outside block a",a)
console.log("outside block b",b)
console.log("outside block c",c)
```
## Shadowing in JS
  process of declaring a new variable with the same name as an existing variable in an inner scope, effectively hiding or "shadowing" the outer variable within that scope

```
function shadowexe()
{
  let a=10
  
  if(true)
  {
    let a=20
    console.log(a)
  }
  console.log(a)  
}

shadowexe()

output
20
10
```
here when we use the var in inner scope it throws the error of illegal shadowing

## Decleration without intitialization

We can just declear a variable without initialization for let and var but should decleare and initialize for const

```
let a;
let b;
const a =10;
```

Reference link :[](https://youtu.be/oUWRxJ19gfE?si=_xdtR4m-rUH1qw1C)
pepemit frog nft || pepestrat frosk nft
Published: 2023-10-02 16:05:00

Bermuda Unicorn is the pepemit frog nft for nft. With a wide variety of to choose from, including sports cards, trading card games, and collectible cards, there's something for everyone on Bermuda Unicorn.

**[pepemit frog nft](https://bermudaunicorn.com/token/Pepemit-Frog-680/)** || **[pepestrat frosk nft](https://bermudaunicorn.com/token/Pepestrat-Frosk-780/)**

Follow Us More Links :-

Follow Us On Facebook :- **[https://www.facebook.com/bermudaunicorn](https://www.facebook.com/bermudaunicorn)**
Follow Us On Instagram :- **[https://www.instagram.com/bermudaunicorn/](https://www.instagram.com/bermudaunicorn/)**
Follow Us On Twitter :- **[https://twitter.com/buofficialus](https://twitter.com/buofficialus)**
Follow Us On YouTube :- **[https://www.youtube.com/@Bermuniverse](https://www.youtube.com/@Bermuniverse)**
Follow Us On Pinterest :-**[https://in.pinterest.com/bermudaunicorn/](https://in.pinterest.com/bermudaunicorn/)**
Email Us :- care@bermudaunicorn.com
How to convert text to image free using AI
Tags: ai, design
Published: 2023-10-02 16:01:48

If you looking for crearing a design **free with AI** and with zero exprience in design, i will advice you to start using [microsoft desingner](https://xn--ainexu-1jb.com/ai_tools/microsoft-designer/)

START DESIGN AND SHARE WITH ME THE RESULT

[This video](https://youtu.be/-xpWJL3X4ms?si=GXnGJrsgagHasiDZ) will help you to learn how to use microsoft designer

I create this desin for an invitation card in 1 second

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

So share with me your opinion about this great AI tool
Creating a react component
Tags: typescript, react, tutorial
Published: 2023-10-02 16:00:40

Note: we use .ts for plain typescript file and .tsx for react component

There are two ways to create REACT component : JavaScript class or function , these days function based component  are widely used because of they are concise and easier to write.

## So the below code is under your .tsx file (mine is : Message.tsx) 

```
function Message() {
  return <h1>Hello World</h1>;
}

export default Message; // this helps to import Message file in other files
```

## The below code is under App.tsx file , in order to use the Message.tsx file under the App.tsx file you need to import the Message.tsx file.

```
import Message from './Message'; //here period(.)means the current folder

function App(){
  return <div><Message></Message></div>;//you can also use <Message/> instead of <Message></Message>

export default App; //export App component to use it somewhere else

  
}
```


![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hj7r2lmstcvtrl11qcfv.png)
Interacting with Postgres from within a Rails app
Published: 2023-10-02 15:55:54

## config/database.yml
`config/database.yml` tells Rails which database to connect to.

Change the default `rails_template_development` to
`database: my_contact_book`.

## rails dbconsole
Run `rails dbconsole` to launch `psql` and connect to the table specified in `config/database.yml`. `\dt` shows what tables are in the database.

## Rails DB Gem
Start the web server with `bin/dev`. Navigate to the URL `/rails/db` for the database developer GUI.

## ActiveRecord
A gem that automates the heavy lifting of connecting to a database and performing CRUD operations.

## Models
For each table:

1. Create a Ruby class to generate SQL
2. Send it to the database
3. Transform the data sent back into Ruby objects.

These classes are called “models” located in the `app/models` folder.

``` ruby
# app/models/contact.rb

class Contact
end
```

- Put a Ruby class in `app/models`.
- Name the file the same as the class (snake_cased version). - Rails automatically requires that class in every other file in our app. This reduces require statements.
- Name the class singularly. Each instance of this class represents one row from the contacts table.  

## Rails Console

- In a new terminal tab, run `rails console` (`rails c`).
- Rails console is similar to IRB, but it automatically requires all of the files and gems in the Rails app.
- Instead of using `irb`, use `rails c` for a quick way of executing one line of Ruby at a time.

## Inheriting from ActiveRecord::Base
``` ruby
# app/models/contact.rb

class Contact < ActiveRecord::Base
end
```

The Contact class has inherited many methods that will help us CRUD data in the contacts table. Restart rails console to use the edits. Run `Contact.new` and `Contact.count` to explore. 

## Creating a new record

- Create a new instance of the `Contact` class with `Contact.new`.
- Assign that instance to a variable
- ActiveRecord automatically adds attribute accessor methods for each column in the underlying table
- Assign values to each column
- Call `.save` to insert the row into the underlying table

## Custom rake tasks

Store Ruby scripts in the `lib/tasks` folder

Within `.rake` files, use the `task` method.

The argument to task is a Symbol. Run the task from the bash prompt with `rake <task name>`. 

## Creating sample data
Write a task called “sample_contacts” to populate the contacts table.

## Faker gem
Add a loop to our code to create a bunch of records all at once

The Faker gem includes a lot of methods for generating various kinds of values. 

To “reset” the table by deleting all of the records before creating new, randomized records use the somewhat dangerous `destroy_all` method.

`destroy_all` will delete all of the records from a table. Be careful!

## Retrieving existing records
Open a rails console session and work with our records using our model.

## Attribute accessor methods
Open Source ABCs: Upstream
Tags: opensource, discuss, 100daysofoss
Published: 2023-10-02 15:51:58

---
title: Open Source ABCs: Upstream
published: true
description: Join our #100DaysOfOSS blog series as we explore the world of Open Source Software (OSS) from A to Z! Every week, we'll discuss two new letters of the English alphabet. Share your thoughts, ideas, and favorite OSS projects for each letter. Let's celebrate the power of open source together! 
tags: opensource, discuss, 100DaysOfOSS
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fxwg4ygmybnni1tpwdx3.png
# Use a ratio of 100:42 for best results.
series: 100DaysOfOSS
canonical_url: https://opensauced.pizza/docs/community-resources/open-source-abcs-upstream/
---

Welcome to our [#100DaysOfOSS series](https://dev.to/opensauced/100daysofoss-growing-skills-and-real-world-experience-3o5k). Until October 31, we'll be doing  Open Source Software (OSS) terms from A to Z. We'll be diving into a different letter of the English alphabet, uncovering OSS concepts, and sharing our thoughts on them.

Today, we're covering the letter "U" for Upstream.

**Upstream**: The original project or source from which a particular fork is taken. Contributing back to the upstream project is often considered a best practice.

Now, we want to hear from you! What other OSS terms can you think of that start with the letter "U"? 

Remember to use the hashtag #100DaysOfOSS if you share on social media, and don't forget to tag us [@saucedopen](https://twitter.com/saucedopen) so we can follow along.
Filamentphp 3 : Input Group with Filament Field
Tags: php, laravel, filamentphp, tips
Published: 2023-10-02 15:45:09

# Introduction
I know that filamentphp currently not support InputGroup, so i write this. Hope you helped with it.

## Installation

You can install the package via composer:

```bash
composer require rupadana/filament-custom-forms
```

## Showing Group Label

```php
InputGroup::make(3)
    ->label('Input Group')
    ->schema([
        TextInput::make('first'),
        Select::make('second'),
        ColorPicker::make('third'),
    ])
```


## Hide Group Label & Show Child Label

```php
InputGroup::make(3)
    ->showChildLabel()
    ->schema([
        TextInput::make('first'),
        Select::make('second'),
        ColorPicker::make('third'),
    ])
```
When globals are appropriate
Tags: softwareengineering, programming, architecture
Published: 2023-10-02 15:43:14

There are times when globals make sense. A lot of people talk about the dangers of global variables and I agree that they should be used sparingly. It's a discussion that's been had over and over again. But let's see if we can decide a rule for when we are willing to allow ourselves to use a global.

So what is a "global"?

A global is a shared resource that can be accessed at any time, from anywhere. Since this type of access breaks many conventional notions of good software engineering, they are usually dismissed as bad. The mere existence of a global indicates an elevated sense of importance. In a way, the only way to express this criticality is in the form of a global.

Globals must align with the essence of the software. Such that when removed or rendered impossible, you would abandon the project, or it would become a different project entirely.

Let's talk about ruby. There are a few standard integrations that are essential to the functionality of the software and they are elevated to the status of global. If you use the fantastic [Sequel gem](http://sequel.jeremyevans.net/), the README literally recommends you assign the connection to the database as a global. This communicates that database interop is so essential to what you're working on that there's no point in abstracting it away behind any other layers. If somehow it became forever impossible to access the database, there's a reasonable chance you would abandon or pivot the entire project. When you have a concept THAT important, you are allowed to make it global. If you use Rails, there is already [built-in support] (https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html)

Integrations can be a special case

There's a lot of code that exists simply to integrate into other services. If you are making a salesforce app integration, your salesforce client can be global. Why? You can build your plugin with standard techniques, but by its very nature, it will always depend on Salesforce or be obsolete. If you accept that as part of the essence of what you're working on, you can sidestep a ton of extra architecture and design and just be productive.

I haven't seen any other justifiable uses of globals, and I still tend to steer clear of them, however, I hope this gives you a different perspective on the subject.

If you like these ideas and would like to work with me, drop me an email at contact@gofrias.com
Как работает функция print в Python
Tags: beginners, programming, tutorial, python
Published: 2023-10-02 15:35:39

Функция print() в Python используется для вывода текстовой информации на экран или в консоль. Эта функция может принимать один или несколько аргументов. Одним из обязательных аргументов является строка или объект, который будет выведен. 

Вы наверняка знакомы с этой функцией. С неё начинается любой урок по программированию на Python. 

```
print("Hello, World!")
```

В данном случае функция выведет в консоль сообщение:

```
Hello, World!
```
При этом обязательно использовать скобки, иначе возникнет синтаксическая ошибка. В Python 2 скобки можно было не указывать, но в Python 3 скобки необходимы. Всё потому, что в третьей версии print() — это функция, а не инструкция.

Как и ожидалось, приведенный выше код отобразил в консоли текст «Hello, World!». Теперь введем следующий код:

```
print(Good morning)
```
Результат: SyntaxError: неверный синтаксис.
На этот раз Доброе утро! вместо текста вылезло сообщение Syntax Error (ошибка в синтаксисе). Где ошибка?

Как мы говорили ранее, функция print() выводит на консоль текст или выражения. Но для того, чтобы эта функция работала корректно, необходимо соблюдать несколько правил. Например, если мы хотим вывести текст на консоль, наш текст должен быть записан в кавычках (" ") или одинарных кавычках (' '). Итак, доброе утро! Правильный код для вывода слова на консоль:

```
print("Good morning!")
```
или

```
print('Good morning!')
```
REST API - Version Your API
Tags: restapi, programming, tutorial, webdev
Published: 2023-10-02 15:30:00

When designing a RESTful API, including a version number in your API's URL is a good practice. This allows you to make changes and improvements to the API without breaking existing clients that rely on the older version.

Here's an example of how to version your API:

```plaintext
https://api.example.com/v1/resource
```

In this URL, "v1" represents the first version of the API. If you later need to make breaking changes or introduce new features, you can create a new version by incrementing the version number like this:

```plaintext
https://api.example.com/v2/resource
```

This versioning approach provides several benefits:

1. **Backward Compatibility**: Existing clients can continue using the old API version without disruption. They can migrate to the new version when they are ready.

2. **Easy Deprecation**: When you need to deprecate an old version, you can clearly communicate the deprecation timeline to your API users.

3. **Testing and Rollout**: You can test and roll out new API versions independently without affecting the stability of existing clients.

4. **Documentation**: It's easier to maintain documentation for different API versions, making it clear which endpoints and features are available in each version.

5. **Future-Proofing**: Versioning helps ensure your API can evolve and adapt to changing requirements.

Remember to provide clear documentation for each API version, including details about changes, improvements, and any deprecated endpoints. This will help developers understand how to use the API effectively and transition to newer versions when necessary.
PHP Match Expression - Match vs Switch
Tags: php8, php
Published: 2023-10-02 15:30:00

The **Match** expression is essentially the same as the Switch statement and was introduced in PHP 8.

The keyword is match, so let's recreate the switch statement below: 

```php
$paymentStatus = 1;

switch ($paymentStatus) {
  case 1:
    echo 'Paid';
    break;
  case 2:
  case 3:
    echo 'Payment Declined';
    break;
  case 0:
    echo 'Pending Payment';
    break;
  default:
    echo 'Unknown Payment Status';
    break;
}
```

Inside the curly braces, we form pairs of values where the key is the individual conditional expression, and the value is the return expression. 

```php
$paymentStatusDisplay = match ($paymentStatus) {
  1 => 'Paid',
  2,3 => 'Payment Declined',
  0 => 'Pending Payment',
  default => 'Unknown Payment Status',
};
echo $paymentStatusDisplay;
```

### Let's talk about the differences

The first difference is that the `match` expression is actually an expression and evaluates to a value, so it can be assigned to a variable. It can be practically any type of expression; for example, we could use a function that returns a value.

The second difference is that `switch` requires the use of `break` to avoid some unexpected outcomes, such as the evaluation of other `case` statements, while the `match` statement returns a value once a match is found.

The third difference is that in the `switch` statement, the `default` value is not required, whereas a fatal error is generated in `match` if a corresponding match is not found in any of the listed cases and the default value is not specified.

The fourth difference is that the `match` expression performs a strict comparison while the `switch` statement performs loose comparison. Both sides are expressions, and we could have complex expressions, function calls, logical operators used within a conditional expression.

```php
$paymentStatus = false;
// switch print 'Pending Payment'
// match print 'Unknown Payment Status'
```

One thing to note is that the `match` expression does not deprecate the `switch` statement as it still has its use cases. For example, `match` returns a value once a match is found, whereas with `switch`, you can execute multiple statements.

> Good work 👨‍💻
Streamline Your Passport Process with Expert Passport Agents in Noida
Tags: passport, passportagentsinnoida, passportconsultantinnoida, passportservices
Published: 2023-10-02 15:26:27

Navigating the intricacies of obtaining a passport in Noida just got easier with the assistance of professional passport agents. These experts are well-versed in the nuances of the application process, ensuring accuracy and efficiency in every step. Whether you're applying for a new passport or renewing an existing one, Noida's passport agents have the knowledge and experience to make the process seamless. With their guidance, you can eliminate the stress and uncertainty often associated with passport applications. Trust in the expertise of [passport agents in Noida](https://shriharienterprisespassport.business.site/) to streamline your passport journey and prepare for your global adventures with confidence.