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,900,613 | Foundations of Logical Thinking in Programming | One of the main concepts in programming is learning conditional logic or control flow logic. Many... | 0 | 2024-06-25T21:06:39 | https://dev.to/ivansing/foundations-of-logical-thinking-in-programming-2g6b | logic, math, propositions, program |
One of the main concepts in programming is learning conditional logic or control flow logic.
Many programming tutorials often cover only the basics of this concept, focusing on the surface level.
In the following tutorial, you will explore essential mathematical concepts crucial for a deeper understanding of control flow logic.
You will become a much better programmer once you understand these concepts, whether a beginner or an expert.
## Introduction to Logic Proposition
### Logic
Humans' natural ability to think coherently and structure fully enables us to determine whether our reasoning is correct or incorrect.
* i.e., If you don't know how to ride a bicycle, it's better not to ride it.
### Math Logic
The study of the methods and essential principles used to distinguish between correct and incorrect reasoning.
* i.e., If you got me flowers and candies, you only gave me candies.
### Propositions
It's a logical proposition or statement that can be true or false.
* Six is greater than 2. The statement is true or false; in this case, it is false.
Or it can be a question. Is six greater than 2? Those are the two ways to say that, which is a proposition we ask ourselves.
* Colombia is on the American Continent. --- Statement: True or as a question: Is Colombia in the American Continent?
* Number 8 is an even number --- Statement: True or as a question: Is eight an even number?
Those previous examples show that they were prepositions because we can tell that those statements have a test case to say True or False.
Now, if we take the following phrases, it can be said that:
* What's your name? This is not a proposition because we can support it as True or False; it's just a question asking without further information.
* Call your mother. This is a simple sentence, but it's not a proposition because we can't tell whether it's True or False; it's a sentence.
* Wait for me. It's just a sentence telling something to a third person, but it is not a proposition because we don't know True or False.
How can we represent propositions more abstractly instead of telling long sentences then:
Those are the following lowercase letters to denote propositional variables:
* p, q, and r… we can use as many as you can letters to represent propositional variables.
* i.e.,
* p: 2 is an integer
* q: 3 x 2 = 2 x 3
* r: All horses are black
In those previous cases, we assigned just the letters as propositional variables that we could use to perform logical operations.
## Logical Connectors
It's two or more statements connected by denominated connectors. We called two or more statements connected as Compound Propositions.
Following are the logical connector symbols:
* ¬, ~ No, or Negation
* Ʌ Conjunction "AND"
* V Disjunction "OR"
* → Conditional "If/Then"
As we follow this tutorial, we will work with the following examples to understand better:
### Negation “NO”
For negation, we will use ¬
Propositions:
* p: I will go to a party.
* q: I will play basketball.
* r: I give you gift cards.
* s: I give you candies.
If we want to negate a sentence, so we join the negation symbol with the letter variable like this case:
* I won’t go to a party ¬ p
* I won’t play basketball ¬ q
* I don’t give you gift cards ¬ r
* I don’t give you candies ¬ s
### Conjunction Ʌ “AND”
* I am going to a party, and then I will play basketball.
* p Ʌ q
* I give you gift cards and candies.
* r Ʌ s
### Disjunction V “OR”
* I will go to a party or play basketball.
* p V q
* I give you gift cards or candies.
* r V s
### Conditional → If/Then
* If I go to a party, then I will play basketball.
* p → q
* If I give you gift cards, then I will provide you with candies.
* r → s
### Practice
How do you read the following propositions:
1. ¬ p Ʌ q
* Solution: I won’t go to a party, and I will play basketball.
2. p → ¬ q
* Solution: If I go to the party, then I won’t play basketball.
## Summary
In this first part, we introduced the basic logic, symbols, and formulas for writing propositions. You learned about logical propositions, their truth values, and how to represent them using logical connectors.
## Conclusion
Understanding logical propositions and their applications in programming is fundamental for improving your problem-solving skills and mastering control flow logic. With a solid grasp of these concepts, you will be able to tackle more complex programming challenges. In the next part, we will delve into truth tables for the logical connectors, providing a practical foundation for applying these principles in your coding projects.
| ivansing |
1,900,612 | Programming Volunteer Opportunity!!! | Hi, My name is Ralph, and I am working with Autrs, a 501c3 nonprofit organization dedicated to... | 0 | 2024-06-25T21:05:53 | https://dev.to/autrs/programming-volunteer-opportunity-3o23 | ai, opensource, node, sql | Hi,
My name is Ralph, and I am working with Autrs, a 501c3 nonprofit organization dedicated to creating new technologies to increase the effectiveness of special education classrooms to help with teacher shortages and improve personalization in curriculum media.
We are currently looking for volunteer software engineers to help us with the backend of our AI curriculum augmentation application, SEAL. This is a great opportunity to contribute to a meaningful cause and gain experience in machine learning, react native, node.js and/or sql.
**Project Details:**
Project Name: SEAL
Technologies Used: SQL, computer vision, react native, node.js, selection algorithms
Project Description: The application gauges a student's responsiveness to different curriculum media and then modifies how future curriculum is presented using the experimental responsiveness data derived. It does so using computer vision and input analyzing AI models.
Time Commitment: How much you are willing to contribute, would appreciate at least 5 hours a week to keep the project moving steadily.
How to Get Involved: Email me at Inquiries@autrs.com
Learn More: https://www.autrs.com/
If you are interested in contributing or would like more information, please feel free to reach out to me at Inquiries@autrs.com or reply to this post.
Thank you for considering this opportunity to make a difference!
| autrs |
1,900,611 | The Terms for a Meeting with Me | I just came out of a disaster of a sales meeting. The client was hostile, and I can actually... | 0 | 2024-06-25T20:55:50 | https://ainiro.io/blog/terms-for-becoming-a-client | I just came out of a disaster of a sales meeting. The client was hostile, and I can actually understand why. My vertical is filled with 99.9% thieves and thugs, and the stigma of working with AI is real. It's a gold rush, and like always it attracts all the wrong people.
If you don't believe me, then please log in to LinkedIn and try to find _one_ of your contacts **not** being an alleged _"AI expert"_ these days.
## My Credentials
My credentials was one of the things the client was asking me about. I don't like bragging about myself face to face with clients, so I tried to tell him how long I've been working with software development and AI. The guy then asked why I could deliver images in our [AI chatbot](https://ainiro.io/ai-chatbot) while nobody else could. I tried to explain, but was met with scepticism and hostility. However, if you must know, I wrote the following article 7 years ago - It was the 5th most popular article Microsoft had _ever_ published throughout their entire history when it was published.
* [Thomas Hansen on Hyperlambda](https://learn.microsoft.com/en-us/archive/msdn-magazine/2017/june/csharp-make-csharp-more-dynamic-with-hyperlambda)
The above was published 7 years ago. How many of your _"LinkedIn AI Experts"_ do you think were even _thinking_ about AI and software development back in 2017?
The above article is the foundation for our [Magic Cloud](https://ainiro.io/magic-cloud) technology, allowing us to serve images in the AI chatbot. I could explain exactly why in details, but that would require weeks of your time to simply listen to me and understand my explanation. I assume you've got better things to do than to listen to me talk about our technology for weeks.
I started coding when I was 8 years old. I'm 50 now. This implies I've got 42 years of experience, 30 as a professional. I still code 60 hours per week. This implies I've got some roughly 90,000 hours of software development experience in total.
In the island of Cyprus, I'm the by far most productive GitHub developer with some roughly 12,000 commits. If you check out my username which is _"polterguy"_, you will only see me on 4th place or something - However, this is because GitHub resets commits back to zero if you change your email address, and I really don't give a sjit, so I've not bothered to fix it. If you want to know _"my credentials"_, then look at [my work](https://ainiro.io/).
However, if you sum up all the commits I've had in this period, including those I had before I changed my email address (twice!), I've got more than twice as many commits as the guy who is now on 1st place. Implying, I'm a 200% more productive software developer amongst 18,000 software developers than the guy who's number 2 on that same list.
There are roughly 18,000 developers in the Island of Cyprus, and GitHub started measuring commits about 5 years ago. This implies that even at the age of 50, I am still the by far most productive software developer in existence amongst 18,000 other software developers. Don't ask me why, my only answer to why would be as follows ...
> Maybe they're lazy ...?
If you've got issues with this, don't bring it up with me. Go ask the 18,000 other guys instead. They're the ones having a problem, not me ...
## Zero Bullshit Tolerance
Sorry guys, my bullshitometer is zero. If you're more interested in finding holes in my explanations, and ask sceptical questions, instead of trying to find a common ground for how I can help you deliver [AI solutions](https://ainiro.io/) to your problem - Then I simply have better things to do.
I've got more than enough clients to have a comfortable life and income, clients who knows what I'm capable of doing, and trusts me to deliver AI solutions to them, having experienced it over and over again. I really don't have the time to defend myself against subtle accusations.
This is why I _only_ take on projects I for some reasons think are interesting projects, and I ignore all the others. This week alone, I've turned down _two_ clients who had already started a subscription with me, because I didn't want to work with them.
I'm not a scammer, and I'm just as sorry as you are that 95% of every single Fortune 500 company ipso facto is, in addition to 99.9% of all AI chatbot companies - It's really quite intolerable for me, and I hope you can understand my predicament here. However, it is what it is, and I don't know what to tell you, besides the following ...
> I can deliver images in my AI chatbot because contrary to SalesForce, HubSpot, ZenDesk, and Five9, I'm **not** a scam artist, and I actually take great pride in my work - Where the others are simply lying in their quarterly reports due to FOMO, to artificially inflate their stock evaluations, such that their lying CEOs can quadruple their annual bonus. Don't like it, then don't bring it up with me, bring it up with SalesForce! The fact that SalesForce, HubSpot, Zendesk, Five9, and literally 99.9% of every single AI chatbot vendor out there happens to be a hot smoking pile of garbage is literally _not my problem_, and I don't intend to make it mine either.
If you got a link to this article, it implies we're set for a meeting some time soon - At which point I want you to read this article very, very, very carefully - Because my time is simply too valuable to have to spend it to defend myself against other peoples' scams.
Sorry, it's nothing personal, but these are the terms for getting to spend time with me. Don't like it? Chose another AI chatbot vendor. I refuse to apologise for having a kick ass product - If you want an apology, go ask Marc Benioff for one ...
## How I deal with people questioning my integrity
Today I had a meeting with a client. My integrity was questioned, which results in me becoming grumpy and angry. My anger spills on to my wife, which again becomes angry because I'm angry. This results in me getting a shitty life, and I simply don't need it. I therefore cancelled the client's subscription. They had already started a professional plan, but I'm in the fortunate situation where I can choose my clients, and I simply don't want clients in my life questioning my integrity.
You can scream at me to implement a feature, fix a bug, or create a new theme, and I won't care because it's something I can fix - But if you question my integrity, it's bye, bye. AINIRO is a single employee company, and when you're in a meeting with me, you're looking at literally 100% of the employees in the company.
I used to have a VC dude a couple of years ago. He was a billionaire and claimed to be having 15,000 employees. Still he'd spend 2 hours on the phone with me, every single day, questioning my integrity, 7 days per week, 52 weeks per year, for 18 months - And I'm done with it. After a couple of years trying to defend my integrity, I basically told him to go føkk himself.
Below you can see the end result of the meeting I had today. If you've got doubts about my integrity, then please go find somebody else, because I will not spend my time defending it, I'll simply cancel your subscription, and wish you good luck ...

Nothing personal, I simply don't want to spend my time defending my integrity. If you're wondering about my integrity, you can check out my work. If my work don't speak for itself, then go find somebody else to deliver your AI solution, because I simply won't do it!
> My work speaks for itself. If you need my _"credentials"_, my only answer from now on will be _"go føkk yourself"_! If you can't see _"my credentials"_ from my work, I suggest you go find an _"AI expert"_ on LinkedIn. They've got amazing credentials I've heard 😊 | polterguy | |
1,900,610 | Emotional Intelligence: The Key to Professional Success | In today’s fast-paced and competitive professional world, technical skills alone are not enough to... | 0 | 2024-06-25T20:53:31 | https://dev.to/devmercy/emotional-intelligence-the-key-to-professional-success-eec | webdev, productivity, opensource, interview | In today’s fast-paced and competitive professional world, technical skills alone are not enough to ensure success. **Emotional intelligence (EI)** has emerged as a critical factor that can significantly impact our personal and professional lives. But what exactly is emotional intelligence, and why is it so important?
## **What is Emotional Intelligence?**

**Emotional intelligence** refers to the ability to recognize, understand, manage, and influence our own emotions and the emotions of others.
**“Emotional Intelligence”** by @Daniel Goleman is a groundbreaking book that highlights the importance of emotional intelligence **(EQ)** over traditional intelligence **(IQ)** in achieving success and well-being. Goleman explores how understanding and managing our emotions can lead to better personal and professional outcomes.
**Here are ten key lessons from the book:**
**• Self-Awareness** The first lesson is the importance of self-awareness. Understanding your own emotions, strengths, and weaknesses is crucial for personal growth and effective decision-making. It helps you recognize how your feelings influence your thoughts and actions.
**• Self-Regulation** @Goleman emphasizes the need for self-regulation. This means managing your emotions, especially in stressful situations, and maintaining control over your impulses. Self-regulation helps in staying calm and making thoughtful decisions.
**• Motivation** Having intrinsic motivation is a key component of emotional intelligence. People with high EQ are driven by internal rewards like personal growth, curiosity, and a passion for their work, rather than external rewards such as money or status.
**• Empathy Empathy,** the ability to understand and share the feelings of others, is essential for building strong relationships. It allows you to connect with others on a deeper level and respond to their needs more effectively.
**• Social Skills** Goleman points out that strong social skills are vital for successful interactions. Being able to communicate effectively, resolve conflicts, and work well in teams are all aspects of high emotional intelligence.
**• Managing Relationships** EQ involves the ability to manage relationships effectively. This includes being a good listener, showing genuine interest in others, and being able to inspire and influence people positively.
**• Handling Stress** People with high EQ are better at handling stress. They use strategies like mindfulness, positive thinking, and relaxation techniques to cope with pressure and maintain their well-being.
**• Conflict Resolution** The book explains that high emotional intelligence helps in resolving conflicts. By understanding different perspectives and finding common ground, individuals can navigate disagreements and find solutions that benefit everyone.
**• Adaptability** Adaptability is another crucial aspect of emotional intelligence. Being flexible and open to change allows you to adjust your strategies and approaches in response to new situations and challenges.

**• The Importance of Emotional Literacy** Lastly, @Goleman highlights the importance of emotional literacy – the ability to recognize, understand, and appropriately express emotions. This skill is fundamental for personal well-being and effective communication.
**“Emotional Intelligence”** by @Daniel provides valuable insights into how understanding and managing our emotions can lead to greater success and fulfillment in life. By cultivating self-awareness, empathy, and social skills, individuals can enhance their personal and professional relationships, handle stress more effectively, and navigate conflicts with greater ease. Goleman’s lessons on emotional intelligence offer a powerful framework for improving our overall quality of life and achieving our goals.
**Now, let’s talk about the ways I found that may help you develop emotional intelligence (How to Develop Emotional Intelligence)**

**Practice Self-Reflection:** Regularly take time to reflect on your own emotions and how they impact your actions and decisions.
**Seek Feedback:** Ask for feedback from colleagues and mentors to gain insight into how your emotional responses affect others.
**Manage Stress:** Develop strategies to manage stress, such as mindfulness, exercise, and healthy work-life balance.
**Improve Communication Skills:** Focus on active listening, clear expression, and non-verbal communication.
**Cultivate Empathy:** Make an effort to understand the perspectives and emotions of others, fostering empathy and compassion.
**Emotional intelligence** is not a fixed trait; it can be developed and enhanced over time with intentional practice and effort. By prioritizing #EI, we can not only achieve greater professional success but also lead more fulfilling and harmonious lives. | devmercy |
1,900,609 | What are Gas Fees on Blockchain? | In the blockchain technology, “gas fees” are a fundamental element. They function similarly to fuel... | 0 | 2024-06-25T20:49:47 | https://dev.to/tsolutionsx/what-are-gas-fees-on-blockchain-2nh2 | In the blockchain technology, “gas fees” are a fundamental element. They function similarly to fuel for a vehicle, necessary for processing transactions and executing smart contracts on platforms like Ethereum.
## Understanding Gas Fees
[**Gas fees**](https://metla.com/blog/what-are-gas-fees) are payments users make to cover the computational energy needed to process and validate transactions on a blockchain. Whether transferring cryptocurrencies or executing intricate contracts, each transaction demands computational effort, priced in gas units.
The Necessity of Gas Fees
**Network Security**: Gas fees motivate validators (miners or stakers) to utilize their computational power to secure and maintain the blockchain network.
**Prevent Network Spam**: By imposing a cost on transactions, gas fees discourage users from flooding the network with excessive or malicious transactions.
## How Gas Fees Function
Blockchain transactions require specific computational work, measured in gas units. The total gas cost of a transaction is influenced by two main factors:
**1. Gas Limit**: The maximum amount of gas a user is willing to spend on a transaction.
**2. Gas Price**: The amount of ether a user is prepared to pay per gas unit, typically measured in “gwei.”
**Calculating Gas Fees**
The formula to determine the total gas fee is straightforward:
**_Total Gas Fee=(Base Fee+Priority Fee)×Gas Used_**
**Base Fee**: A compulsory fee that adjusts dynamically with network congestion to ensure smooth operation.
**Priority Fee**: An optional tip users can offer to validators to prioritize their transactions.
## Factors Influencing Gas Fees
**Network Traffic**: Similar to rush hour traffic, higher blockchain activity raises gas prices.
**Transaction Complexity**: More complex transactions need more computational power, thus consuming more gas.
**Blockchain Protocol Design**: Different blockchains have distinct fee structures affecting gas fee applications.
## Managing Gas Fees
Users can implement several strategies to control their gas fee expenses:
**Transact During Off-Peak Hours**: Conducting transactions during periods of low network activity can reduce fees.
**Optimize Gas Settings**: Advanced users can adjust gas price and limit settings to balance cost and transaction speed.
## Case Study: Ethereum Gas Fees
Ethereum, a leading blockchain platform, handles not only cryptocurrency transfers but also a variety of decentralized applications and smart contracts. This versatility leads to variable gas fees based on transaction complexity and volume.
## Comparing Ethereum with Polygon
Ethereum’s gas fees are generally higher than those on Polygon, a Layer 2 scaling solution. Polygon boosts transaction speed and affordability by processing transactions off Ethereum’s main chain, reducing load and cost on Ethereum.
## The Challenge of High Gas Fees
While necessary for network functionality, high gas fees present certain obstacles:
**Cost Barrier**: High fees can deter average users, especially during peak periods.
**Limited Accessibility**: High gas fees can hinder broader adoption of blockchain technology.
## Innovations to Reduce Gas Fees
The blockchain community continuously explores innovations like Layer 2 scaling solutions to lower high gas fees. These technologies shift transactions off the main blockchain, reducing costs and enhancing scalability.
## Conclusion
Gas fees are essential to blockchain architecture, compensating validators and securing the network. Despite the challenges they pose, ongoing innovations promise to lower these costs and improve user experiences across blockchain platforms.
Learn more about blockchain and Crypto — [Metla Blog](https://metla.com/blog) | tsolutionsx | |
1,900,607 | Making a Wack-A-Molee with AnalogJs - Part 1 | 📚The Idea The search for inspiration: After some time without writing, I was kind of... | 0 | 2024-06-25T20:47:25 | https://dev.to/luishcastroc/making-a-wack-a-molee-with-analogjs-part-1-3lf6 | angular, analogjs, typescript, frontend | ## 📚The Idea
**The search for inspiration:**
After some time without writing, I was kind of looking for some subjects I could write about, and that's when my daughter came to ask me, "Dad, do you know how to make video games?" I was both surprised and impressed by the question. "Of course I can," was the answer. "Of course, I've never tried," was the reality. So I started to think about what to do next.
## 🐨Wack-a-Molee
Since it is my first time and I know zero about animations, the first game that came to my mind, because of simplicity and because it seems to be easier to implement for mobile, was [Whac-A-Molee](https://en.wikipedia.org/wiki/Whac-A-Mole).
If you don't know the mechanics for classic **Whac-A-Molee**, they are very simple. Players need to hit a series of randomly popping-up animals with a mallet.
### Getting Started
With the idea in my mind, I started to check Google, YouTube (you know, the usual) for inspiration and options, because clearly, I didn't want to start from scratch and have to design my own sprites and stuff.
And I ended up finding this project made with React Native by **Tamas Szikszai**. All the credit goes to him for the concept, sprites, and overall design. I'm definitely not stealing someone's work, so here is that if you want to check out his channel, click [Here](https://www.youtube.com/channel/UCG4CEAVeZsfzKH4NpPwgs7w).
With the idea and a better start, let's get on with it!! 🎮:
The original project is using **React Native** and a little library called **rn-sprite-sheet** and we're using **AnalogJs** and that's pretty much it.
## 🦾Mechanics
I'm pretty much using the same mechanics that **Tamas** uses; however, I'm adding a couple of things, so let's explain this:
- **Gameplay**: The game will be pretty much 12 moles popping randomly, and you need to hit them to make them go away as fast as you can. This is divided into 50 levels; each level increases the speed of the moles popping, making it a little harder to finish. Additionally, you have a healing bar, so if you lose all your health, you're gone. Easy, right? (I hope).
- **Types of Mole**: You pretty much have 3 types of moles:
- **Regular**: This will pop and, after some time, it will hide.
- **Angry**: This one will pop, but it will attack and reduce your health if you don't hit it first.
- **Sentinel**: (Yeah, he looks like one of the X-Men Sentinels). This will drink some stuff and become a sentinel. If you hit him, you will gain some health.
- **Changes from the React Native One**: Different from the original implementation, this one has an initial screen. As well, when there's 30% of the time left, at least 4 moles will pop at the same time.
Funny, right? So let's dig a little bit into the explanation of how this will work. I honestly didn't read the blog post from **Tamas** since I do not personally pay for Medium, but I saw his video. Yeah, I already posted the link, so to save a little time, I'll explain the basics of how the code works, and we will go from there.
## 🧩The Animation Library
With the mechanics well established and a solid starting point, we hit the first obstacle, which is the sprite animation library. I'm pretty sure there are many options to do this in Angular and JavaScript in general; however, with my lack of experience in the subject, I found Canvas to be the easiest to understand. So how does that work? Let's dig into what I did and how it works.
### The Canvas Approach
```ts
@Component({
selector: 'game-animated-sprite',
standalone: true,
template: `<canvas #canvas></canvas>`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AnimatedSpriteComponent implements AfterViewInit, OnDestroy {
canvasRef = viewChild<ElementRef<HTMLCanvasElement>>('canvas');
imgSrc = input.required<string>();
rows = input.required<number>();
columns = input.required<number>();
animations = input.required<{ [key: string]: number[] }>();
loopMode = input(false);
frameWidth = input<number | null>(null);
frameHeight = input<number | null>(null);
initialFrame = input<number>(0);
private img = new Image();
private ctx!: CanvasRenderingContext2D;
private width!: number;
private height!: number;
private originalAspectRatio!: number;
private subscription!: Subscription;
private currentLoopIndex = 0;
private currentAnimationType!: string;
private frameSequence!: number[];
valueEffect = effect(() => {
const [w, h, imgSrc] = [
this.frameWidth(),
this.frameHeight(),
this.imgSrc(),
];
untracked(() => {
this.calculateDimensions();
});
});
ngAfterViewInit(): void {
const canvas = this.canvasRef()?.nativeElement;
if (canvas) {
this.ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
this.img.src = this.imgSrc();
this.img.onload = () => {
this.originalAspectRatio =
this.img.naturalWidth / this.img.naturalHeight;
this.calculateDimensions();
this.drawFrame(this.initialFrame());
};
}
}
private calculateDimensions(): void {
const [frameHeight, frameWidth] = [this.frameHeight(), this.frameWidth()];
if (this.img.complete) {
if (frameWidth && !frameHeight) {
this.width = frameWidth;
this.height = this.width / this.originalAspectRatio;
} else if (!frameWidth && frameHeight) {
this.height = frameHeight;
this.width = this.height * this.originalAspectRatio;
} else if (frameWidth && frameHeight) {
this.width = frameWidth;
this.height = frameHeight;
} else {
this.width = this.img.naturalWidth / this.columns();
this.height = this.img.naturalHeight / this.rows();
}
const canvas = this.canvasRef()?.nativeElement;
if (canvas) {
canvas.width = this.width;
canvas.height = this.height;
}
}
}
play(animationType: string, fps = 24, onFinish?: () => void): void {
this.clearSubscription();
this.currentLoopIndex = 0;
this.currentAnimationType = animationType;
this.frameSequence = this.animations()[animationType];
this.startAnimation(this.frameSequence, fps, onFinish);
}
pause(): void {
this.clearSubscription();
}
resume(): void {
if (this.currentAnimationType && this.frameSequence) {
this.startAnimation(this.frameSequence);
}
}
reset(): void {
this.clearCanvas();
this.currentLoopIndex = 0;
}
private startAnimation(
frameSequence: number[],
fps = 24,
onFinish?: () => void
): void {
const frameRate = 1000 / fps;
this.subscription = interval(frameRate)
.pipe(
tap(() => this.clearCanvas()),
map(() => frameSequence[this.currentLoopIndex]),
tap(frameIndex => this.drawFrame(frameIndex)),
tap(() => {
this.currentLoopIndex++;
if (this.currentLoopIndex >= frameSequence.length) {
if (this.loopMode()) {
this.currentLoopIndex = 0;
} else {
this.subscription.unsubscribe();
if (onFinish) {
onFinish();
}
}
}
})
)
.subscribe();
}
private clearCanvas(): void {
const canvas = this.canvasRef()?.nativeElement;
if (canvas) {
this.ctx.clearRect(0, 0, canvas.width, canvas.height);
}
}
private drawFrame(frameIndex: number): void {
const frameX = Math.floor(frameIndex % this.columns());
const frameY = Math.floor(frameIndex / this.columns());
const naturalFrameWidth = Math.floor(
this.img.naturalWidth / this.columns()
);
const naturalFrameHeight = Math.floor(this.img.naturalHeight / this.rows());
const padding = 1;
this.ctx.drawImage(
this.img,
frameX * naturalFrameWidth + padding,
frameY * naturalFrameHeight + padding,
naturalFrameWidth - padding * 2,
naturalFrameHeight - padding * 2,
0,
0,
this.width,
this.height
);
}
private clearSubscription(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
ngOnDestroy(): void {
this.clearSubscription();
}
}
```
So this is the component that pretty much animates the little mole, but it might as well work with other sprite sheets (
I tested it with a Zelda one, so I know it will).
Let's dig into the details of how this works or at least the **CORE** parts.
### Detailed Explanation
#### Inputs and Properties
```typescript
canvasRef = viewChild<ElementRef<HTMLCanvasElement>>('canvas');
imgSrc = input.required<string>();
rows = input.required<number>();
columns = input.required<number>();
animations = input.required<{ [key: string]: number[] }>();
loopMode = input(false);
frameWidth = input<number | null>(null);
frameHeight = input<number | null>(null);
initialFrame = input<number>(0);
```
- **Inputs**: Several inputs are defined to control the sprite's behavior:
- `imgSrc`: URL of the sprite sheet image.
- `rows` and `columns`: Define the sprite sheet's grid.
- `animations`: An object mapping animation names to frame sequences.
- `loopMode`: A boolean to determine if animations should loop.
- `frameWidth` and `frameHeight`: Dimensions for each frame.
- `initialFrame`: The starting frame of the animation.
- **Canvas Reference**: `canvasRef` is used to get the native canvas element.
#### Core Methods
1. **calculateDimensions**
```ts
private calculateDimensions(): void {
const [frameHeight, frameWidth] = [this.frameHeight(), this.frameWidth()];
if (this.img.complete) {
if (frameWidth && !frameHeight) {
this.width = frameWidth;
this.height = this.width / this.originalAspectRatio;
} else if (!frameWidth && frameHeight) {
this.height = frameHeight;
this.width = this.height * this.originalAspectRatio;
} else if (frameWidth && frameHeight) {
this.width = frameWidth;
this.height = frameHeight;
} else {
this.width = this.img.naturalWidth / this.columns();
this.height = this.img.naturalHeight / this.rows();
}
const canvas = this.canvasRef()?.nativeElement;
if (canvas) {
canvas.width = this.width;
canvas.height = this.height;
}
}
}
}
```
- **calculateDimensions**: This method adjusts the canvas dimensions based on the frame size or the image's natural dimensions.
- If both `frameWidth` and `frameHeight` are provided, use those dimensions.
- If only `frameWidth` is provided, calculate `frameHeight` to maintain the image's aspect ratio.
- If only `frameHeight` is provided, calculate `frameWidth` similarly.
- If neither are provided, calculate the frame dimensions based on the number of rows and columns in the sprite sheet.
This ensures that the image is properly scaled and displayed within the canvas.
2. **startAnimation**
```typescript
private startAnimation(
frameSequence: number[],
fps = 24,
onFinish?: () => void
): void {
const frameRate = 1000 / fps;
this.subscription = interval(frameRate)
.pipe(
tap(() => this.clearCanvas()),
map(() => frameSequence[this.currentLoopIndex]),
tap(frameIndex => this.drawFrame(frameIndex)),
tap(() => {
this.currentLoopIndex++;
if (this.currentLoopIndex >= frameSequence.length) {
if (this.loopMode()) {
this.currentLoopIndex = 0;
} else {
this.subscription.unsubscribe();
if (onFinish) {
onFinish();
}
}
}
})
)
.subscribe();
}
```
- **startAnimation**: Manages the animation frame updates using RxJS `interval`. It ensures frames are drawn at the correct rate and handles the end-of-animation logic.
- `interval(frameRate)`: Creates an observable that emits values at the specified frame rate.
- `tap(() => this.clearCanvas())`: Clears the canvas before drawing each frame.
- `map(() => frameSequence[this.currentLoopIndex])`: Maps the current loop index to the corresponding frame in the frame sequence.
- `tap(frameIndex => this.drawFrame(frameIndex))`: Draws the current frame.
- `tap(() => { ... })`: Updates the loop index and handles looping or finishing the animation.
The use of RxJS `interval` allows for precise control over the animation timing.
3. **drawFrame**
```typescript
private drawFrame(frameIndex: number): void {
const frameX = Math.floor(frameIndex % this.columns());
const frameY = Math.floor(frameIndex / this.columns());
const naturalFrameWidth = Math.floor(
this.img.naturalWidth / this.columns()
);
const naturalFrameHeight = Math.floor(this.img.naturalHeight / this.rows());
const padding = 1;
this.ctx.drawImage(
this.img,
frameX * naturalFrameWidth + padding,
frameY * naturalFrameHeight + padding,
naturalFrameWidth - padding * 2,
naturalFrameHeight - padding * 2,
0,
0,
this.width,
this.height
);
}
```
- **drawFrame**: Draws a specific frame from the sprite sheet on the canvas.
- `frameX` and `frameY` are calculated to determine the position of the frame within the sprite sheet.
- `naturalFrameWidth` and `naturalFrameHeight` represent the dimensions of each frame within the sprite sheet.
- `this.ctx.drawImage(...)`: Draws the calculated frame onto the canvas, scaling it to fit the specified dimensions.
The `padding` is used to ensure frames are drawn correctly without overlapping.
But do not believe a word of what I say, try it yourself 🥸 [here](https://stackblitz.com/edit/animated-sprite-angular-canvas?file=src%2Fcanvas-animation.component.ts,src%2Fmole.component.ts)
## 🌟 Conclusion: Wrapping Up Part 1
In this first part of our series on creating a Wack-A-Molee game with AnalogJs and Canvas, we've laid the groundwork by understanding the basic mechanics of the game and exploring the core component responsible for sprite animations. We've dissected the `AnimatedSpriteComponent`, looking at how it uses canvas to render and animate sprites efficiently.
We've used some of the latest **Angular** features like Signal Inputs and Signal Queries.
In the next part of the series, we'll dive deeper into game mechanics, adding interactivity and logic to bring the Wack-A-Molee game to life. Stay tuned as we continue building this fun game step by step!
---
If you found this article insightful, don't hesitate to connect with me on [Twitter](https://twitter.com/LuisHCCDev), [Threads](https://www.threads.net/@luishccdev), or [LinkedIn](https://www.linkedin.com/in/luis-castro-cabrera/). Let's embark on this journey of discovery and innovation together! 💻🚀📘
Feeling generous? Show some love and [buy me a coffee](https://www.buymeacoffee.com/luishcastrv). Your support is greatly cherished! ☕️
| luishcastroc |
1,900,606 | Complete Guide to JavaScript Objects | JavaScript objects are foundational elements in programming with JavaScript. They allow you to store... | 0 | 2024-06-25T20:45:54 | https://dev.to/tsolutionsx/complete-guide-to-javascript-objects-3oga | javascript, objects, webdev, beginners | JavaScript objects are foundational elements in programming with JavaScript. They allow you to store and manipulate key-value pairs, where each key is a string, and each value can be any data type. This guide will explore the various ways to create, access, and manipulate JavaScript objects, along with some advanced concepts like inheritance and static methods.
## Creating JavaScript Objects
**Object Literal Notation**
The simplest and most commonly used method to create objects is the object literal notation.
```javascript
const scorcism = {
name: "TSolutionsX",
age: 23
};
```
Curly Braces: Enclose key-value pairs within curly braces {}.
**Using the `new` Keyword**
Creating objects using constructor functions and the new keyword is less common but essential for certain use cases.
```javascript
function About(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
const me = new About("TSolutionsX", 23, "Toronto");
```
**Constructor Functions:** Define a function and use `this` to set properties.
**new Keyword:** Creates an object with an internal `this`.
**Using `Object.create()`**
This method allows you to create a new object with a specified prototype object.
```javascript
const aboutData = {
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
const me = Object.create(aboutData);
me.name = 'TSolutionsX';
me.age = 23;
```
**Prototype Inheritance:** The new object inherits properties and methods from the prototype object.
**Accessing Object Properties**
Dot Notation and Bracket Notation
Properties of a JavaScript object can be accessed using dot notation or bracket notation.
Properties of a JavaScript object can be accessed using dot notation or bracket notation.
```javascript
const me = {
name: "TSolutionsX",
age: 23
};
console.log(me.name); // Output: TSolutionsX
console.log(me["age"]); // Output: 23
```
Dot Notation: `object.property`
Bracket Notation: `object["property"]`
**Object Prototypes and Inheritance**
At the core of JavaScript lies the concept of prototypes. Every object in JavaScript is associated with a prototype object, which acts as a blueprint.
**Object Prototype**
The prototype object contains properties and methods accessible to all instances created from it.
```javascript
const me = {
name: "TSolutionsX",
eatsAppleDaily: false,
printAbout: function() {
console.log(`I am ${this.name}. I ${this.eatsAppleDaily ? "eat" : "don't eat"} apple daily.`);
}
};
const myFriend = Object.create(me);
myFriend.name = "Ladoo";
myFriend.eatsAppleDaily = true;
me.printAbout(); // Output: I am TSolutionsX. I don't eat apple daily.
myFriend.printAbout(); // Output: I am Ladoo. I eat apple daily.
```
**Static Methods**
`Object.keys()`
Returns an array of a given object’s own enumerable property names.
```javascript
const aboutMe = {
name: "TSolutionsX",
age: 23
};
let aboutMeKeys = Object.keys(aboutMe);
// Output: ['name', 'age']
```
`Object.values()`
Returns an array of a given object’s own enumerable property values.
```javacript
let aboutMeValues = Object.values(aboutMe);
// Output: ['TSolutionsX', 23]
```
`Object.assign()`
Copies the values of all enumerable own properties from one or more source objects to a target object.
```javascript
const target = { age: 23 };
const source = { name: "TSolutionsX" };
const merged = Object.assign(target, source);
console.log(merged); // Output: { age: 23, name: 'TSolutionsX' }
console.log(merged === target); // Output: true
```
`Object.entries()`
Returns an array of the given object’s own enumerable string-keyed property key-value pairs.
```javacript
console.log(Object.entries(aboutMe));
// Output: [['name', 'TSolutionsX'], ['age', 23]]
```
`Object.fromEntries()`
Transforms a list of key-value pairs into an object.
```javascript
const entries = [['name', 'TSolutionsX'], ['age', 23]];
console.log(Object.fromEntries(entries));
// Output: { name: 'TSolutionsX', age: 23 }
```
`Object.freeze()`
Freezes an object, preventing new properties from being added, existing properties from being removed or changed, and the prototype from being altered.
```javascript
Object.freeze(me);
me.name = "TSolutionsX"; // This change will not take effect
console.log(me); // Output: { name: "TSolutionsX", age: 23 }
```
`Object.isFrozen()`
Determines if an object is frozen.
```javascript
console.log(Object.isFrozen(me)); // Output: true
```
`Object.seal()`
Seals an object, preventing new properties from being added and marking all existing properties as non-configurable.
```javascript
Object.seal(me);
me.name = "TSolutionsX"; // This change will take effect
delete me.age; // This deletion will not take effect
console.log(me); // Output: { name: 'TSolutionsX', age: 21 }
```
`Object.isSealed()`
Determines if an object is sealed.
```javascript
console.log(Object.isSealed(me)); // Output: true
```
**Inheritance Static Methods**
`this` **Keyword**
The `this` keyword refers to the properties of the object it is within.
```javascript
const person = {
name: 'TSolutionsX',
sayMyName: function() {
return `My name is ${this.name}`;
}
};
console.log(person.sayMyName()); // Output: My name is TSolutionsX
```
`bind()`, `call()`, **and** `apply()`
`bind()`
Creates a new function that, when called, has its this keyword set to the provided value.
```javascript
function sayMyName() {
return `My name is ${this.name}`;
}
const person = { name: 'TSolutionsX' };
const boundSayMyName = sayMyName.bind(person);
console.log(boundSayMyName()); // Output: My name is TSolutionsX
```
`call()`
Calls a function with a given `this` value and arguments provided individually.
```javascript
function introduce(language) {
console.log(`I code in ${language}. My name is ${this.name}.`);
}
const mySelf = { name: "TSolutionsX" };
introduce.call(mySelf, 'Java'); // Output: I code in Java. My name is TSolutionsX.
```
`apply()`
Similar to `call()`, but accepts arguments as an array.
```javascript
function add(...args) {
let sum = args.reduce((acc, curr) => acc + curr, 0);
console.log(sum);
}
const numbers = [1, 2, 3, 4, 5];
add.apply(null, numbers); // Output: 15
```
**When to Use `call`, `bind`, and `apply`**
`call`: Execute a function immediately and specify what `this` should refer to.
`bind`: Create a new function that, when executed later, has a predetermined `this` value.
`apply`: Use when you have an array of arguments to pass to a function.
## Conclusion
Understanding JavaScript objects and their associated methods is crucial for any JavaScript developer. These concepts provide a solid foundation for working with data structures, creating complex functionalities, and leveraging the full power of JavaScript.
If this guide was helpful, please leave a like, follow.
Happy coding! 🍕 | tsolutionsx |
1,900,605 | shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 1.1 | I wanted to find out how shadcn-ui CLI works. In this article, I discuss the code used to build the... | 0 | 2024-06-25T20:45:51 | https://dev.to/ramunarasinga/shadcn-uiui-codebase-analysis-how-does-shadcn-ui-cli-work-part-11-n9b | javascript, opensource, nextjs, shadcnui | I wanted to find out how shadcn-ui CLI works. In this article, I discuss the code used to build the shadcn-ui/ui CLI. In part 1.1, we will look at a code snippet picked from [packages/cli/src/index.ts](https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/index.ts).
In part 1.0, I discussed the imports used and getPackageInfo utility function. Let’s continue where we left off in part 1.0 by picking a code snippet that is in continuation to part 1.0
The below code snippet is picked from [ui/packages/cli/src/index.ts](https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/index.ts)
```js
async function main() {
const packageInfo = await getPackageInfo()
const program = new Command()
.name("shadcn-ui")
.description("add components and dependencies to your project")
.version(
packageInfo.version || "1.0.0",
"-v, --version",
"display the version number"
)
program.addCommand(init).addCommand(add).addCommand(diff)
program.parse()
}
main()
```
new Command()
-------------
[Commander package](https://www.npmjs.com/package/commander) is used and is configured with [name](https://www.npmjs.com/package/commander#name), [description](https://www.npmjs.com/package/commander#description-and-summary) and [version](https://www.npmjs.com/package/commander#version-option).
program.addCommand
------------------
After a new command is initialised, init, add and diff commands are added to the program variable using addCommand. You can specify (sub)commands using .command() or .addCommand(). There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file.
program.parse
-------------
[Parse](https://www.npmjs.com/package/commander#parse-and-parseasync) function should be called with no parameters to parse process.argv via the CLI.

Conclusion:
-----------
In this article, I discussed a code snippet that deals with initialising command and adds custom commands such as init, add and diff that are used in shadcn-ui/ui CLI. I found out that program.parse() call with no arguments is important to parse the process.argv passed in via your CLI.
> _Want to learn how to build shadcn-ui/ui from scratch? Check out_ [_build-from-scratch_](https://tthroo.com/)
About me:
---------
Website: [https://ramunarasinga.com/](https://ramunarasinga.com/)
Linkedin: [https://www.linkedin.com/in/ramu-narasinga-189361128/](https://www.linkedin.com/in/ramu-narasinga-189361128/)
Github: [https://github.com/Ramu-Narasinga](https://github.com/Ramu-Narasinga)
Email: [ramu.narasinga@gmail.com](mailto:ramu.narasinga@gmail.com)
References:
-----------
1. [https://www.npmjs.com/package/commander#parse-and-parseasync](https://www.npmjs.com/package/commander#parse-and-parseasync)
2. [https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/index.ts](https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/index.ts) | ramunarasinga |
1,900,602 | Dockerizando uma API Express.js com Banco de Dados PostgreSQL para Testes e Produção | Docker é uma ferramenta poderosa que permite criar, implantar e executar aplicativos em contêineres.... | 0 | 2024-06-25T20:43:04 | https://dev.to/mspilari/dockerizando-uma-api-expressjs-com-banco-de-dados-postgresql-para-testes-e-producao-32lf | node, docker, api, database | Docker é uma ferramenta poderosa que permite criar, implantar e executar aplicativos em contêineres. Neste post, vamos mostrar como dockerizar uma API Express.js com bancos de dados PostgreSQL separados para teste e produção, e como configurar o ambiente para que as alterações locais reflitam no contêiner.
## Pré-requisitos
- Node.js instalado
- Docker instalado
- Docker Compose instalado
- Uma API Node.js existente (ou um novo projeto)
## Criando uma API Express.js
Primeiro, crie um novo projeto Express.js.
```
mkdir node-docker-api
cd node-docker-api
npm init -y
npm install express
npm install -D nodemon
```
Crie um arquivo `index.js`:
```
const express = require('express');
const app = express();
const port = 3333;
app.use(express.json());
app.get('/', (req, res) => {
res.send(`Hello, Docker from ${process.env.NODE_ENV} server !`);
});
app.listen(port, () => {
console.log(`API of ${process.env.NODE_ENV} listening at http://localhost:${port}`);
});
```
## Incremente seu package.json
Crie dois scripts no seu package.json um de `"dev":"NODE_ENV=development nodemon src/index.js"`, para desenvolvimento/testes, e outro de ` "start": "NODE_ENV=production node src/index.js"`, para produção.
```
{
"name": "node-docker-api",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "NODE_ENV=development nodemon src/index.js",
"start": "NODE_ENV=production node src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^4.19.2"
},
"devDependencies": {
"nodemon": "^3.1.4"
}
}
```
## Criando o Dockerfile
Crie um arquivo Dockerfile na raiz do projeto.
```
# Usando uma imagem base oficial do Node.js
FROM node:20-alpine
# Diretório de trabalho dentro do contêiner
WORKDIR /app
# Copiando package.json e package-lock.json
COPY package*.json ./
# Instalando as dependências do projeto dependendo do NODE_ENV
ARG NODE_ENV
RUN if [ "$NODE_ENV" = "production" ]; then npm install --omit=dev; else npm install; fi
# Copiando o restante da aplicação
COPY . .
# Expondo a porta em que a aplicação será executada
EXPOSE 3333
# Definindo a variável de ambiente para desenvolvimento ou produção
ENV NODE_ENV $NODE_ENV
# Comando para rodar a aplicação
CMD ["sh", "-c", "if [ \"$NODE_ENV\" = 'production' ]; then npm start; else npm run dev; fi"]
```
## Criando um .dockerignore
Crie um arquivo `.dockerignore` para evitar que arquivos desnecessários sejam copiados para a imagem Docker:
```
node_modules
npm-debug.log
.dockerignore
```
## Criando Arquivos docker-compose
Vamos criar dois arquivos docker-compose: um para desenvolvimento/teste (docker-compose.dev.yaml) e outro para produção (docker-compose.prod.yaml).
`docker-compose.dev.yaml`
Este arquivo conterá a configuração para o ambiente de desenvolvimento e teste.
```
services:
api:
build: .
ports:
- "3333:3333"
volumes:
- .:/app
- /app/node_modules
environment:
- NODE_ENV=development
- DATABASE_URL=postgresql://postgres:postgres@postgres:5432/devdb
depends_on:
- postgres
postgres:
image: postgres:latest
ports:
- "5432:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: devdb
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
```
`docker-compose.prod.yaml`
Este arquivo conterá a configuração para o ambiente de produção.
```
services:
api:
build: .
ports:
- "3333:3333"
environment:
- NODE_ENV=production
- DATABASE_URL=postgresql://postgres:postgres@postgres:5432/proddb
depends_on:
- postgres
postgres:
image: postgres:latest
ports:
- "5432:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: proddb
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
```
## Configurando o Ambiente de Desenvolvimento
Para refletir as alterações locais no contêiner, vamos usar o Docker Compose com volumes. O arquivo docker-compose.dev.yaml já está configurado para montar o diretório de trabalho local (.) no contêiner (/app), exceto para node_modules, que será mantido dentro do contêiner para evitar conflitos de dependências.
## Executando a Aplicação
### Ambiente de Desenvolvimento/Teste
Para o ambiente de desenvolvimento/teste, use o seguinte comando:
```
docker-compose -f docker-compose.dev.yaml up --build
```
### Ambiente de Produção
Para o ambiente de produção, use o seguinte comando:
```
docker-compose -f docker-compose.prod.yaml up --build
```
## Testando a Aplicação
Abra seu navegador e acesse http://localhost:3333. Você deve ver a mensagem "Hello, Docker!".
## Conclusão
Parabéns! Você dockerizou com sucesso sua API Express.js, configurou bancos de dados PostgreSQL diferentes para teste e produção, e configurou o ambiente de desenvolvimento para refletir as alterações locais no contêiner. Dockerizar suas aplicações torna o processo de desenvolvimento, teste e implantação mais consistente e fácil de gerenciar. Continue explorando as funcionalidades do Docker para melhorar ainda mais o seu fluxo de trabalho.
Se você tiver alguma dúvida ou sugestão, sinta-se à vontade para deixar um comentário abaixo! | mspilari |
1,900,601 | Hoisting | Hoisting is a behaviour in JavaScript when a declaration is moved to the top of it's enclosing scope... | 27,846 | 2024-06-25T20:42:52 | https://dev.to/abhinavkushagra/hoisting-1l7p | webdev, javascript, beginners, programming | Hoisting is a behaviour in JavaScript when a declaration is moved to the top of it's enclosing scope no matter where in the scope you've declared it.
---
## Var
Let's understand this with a simple example:
```javascript
var x = 11;
callMeAnytime();
function callMeAnytime() {
x = 9;
console.log(x);
var x;
};
console.log(x);
```
Many/Some of us would think this block of code will throw an error on execution but that's not what going to happen. What's exactly going to happen is:
```javascript
var x = 11;
callMeAnytime(); //function declaration is 'hoisted'
function callMeAnytime() {
x = 9;
console.log(x); //9
var x; // variable declaration is 'hoisted' to
}; // the top of the callMeAnytime function
console.log(x); // 11
```
You can think declaration as a flag and Javascript as the one who hoist the flag. On hoisting, flag reaches top. Isn't it?

[_Source_](https://tenor.com/en-GB/view/cubs-clark-clark-the-cub-flythew-win-gif-18610140)
---
## Let and Const
When it comes to let and const, hoisting is bit confusing and I'll tell you why?
Consider below examples.
```javascript
console.log(x);
let x = 11; // or, const x = 11;
```
On executing, you get `ReferenceError: Cannot access 'x' before initialization` and you going to think hoisting doesn't happen in let and const but that's not all. Let me clear this up in the next example:
```javascript
console.log(y);
let x = 11;
```
You get `ReferenceError: y is not defined` on executing and that's what makes the difference.
Here, JavaScript has no idea about the y variable is because it is not defined and isn't it obvious that we didn't define it? We've only defined x.
In the first code snippet, it says "cannot access before initialization" and not "is not defined" and that means Javascript has considered hoisting of let/const without a default initialization.
> The state between execution where `let`/`const` variables are hoisted and its existence is known but not accessible as it's not initialized yet, is called TEMPORAL DEAD ZONE** _(Sounds fancy.. Isn't it?)_.

[_Source_](https://tenor.com/en-GB/view/mike-shinoda-tea-fancy-gif-24287830)
---
> `let`/`const` are hoisted WITHOUT a default initialization and `var` is hoisted WITH default initialization of undefined.
| abhinavkushagra |
1,900,600 | Mastering Typography in UI Design: Enhancing Readability and User Experience | 👋 Hello, Dev Community! I'm Prince Chouhan, a B.Tech CSE student passionate about UI/UX design.... | 0 | 2024-06-25T20:34:57 | https://dev.to/prince_chouhan/mastering-typography-in-ui-design-enhancing-readability-and-user-experience-1627 | 👋 Hello, Dev Community!
I'm Prince Chouhan, a B.Tech CSE student passionate about UI/UX design. Today, let's dive into Typography in UI design.
🗓️ Day 8 Topic: Typography
📚 Today's Learning Highlights:
Typography Overview:
Typography arranges type to make written language legible, readable, and visually appealing. It enhances readability and navigation in user interfaces.
Role in UI/UX Design:
- Creates visually appealing interfaces 🎨
- Enhances readability and navigation 🧭
- Involves selecting typeface, font size, weight, and spacing.
Typeface vs. Font:
- Typeface: Design of a set of characters (e.g., Arial, Times New Roman).
- Includes styles like regular, bold, italic.
- Font: A specific instance of a typeface (e.g., Times New Roman 12pt bold).
Important Typographic Parts:
1. Baseline: Imaginary line on which letters sit.
2. X-height: Height of lowercase letters.
3. Cap height: Height of uppercase letters.
4. Ascender: Part of a letter above the x-height.
5. Descender: Part of a letter below the baseline.
Key Element:
1. Leading: Spacing between baselines.
2. Kerning: Spacing between characters.
3. Tracking: Spacing between groups of characters.
4. Weight: Different weights like light, regular, bold, etc.
Typefaces:
1. Serif: Traditional and formal.
2. Sans Serif: Modern and minimalistic.
3. Display: Stylized for large sizes.
4. Script: Mimics handwriting.
5. Monospace: Equal width for characters.

Best Practices:
- Sans Serif typefaces are preferred for digital interfaces.
- Pair with a serif typeface for headings.
- Keep line length to 40-60 characters for readability.
📢 Community Engagement:
What's your favorite typeface for UI design? Share your thoughts!
💬 Quote of the Day:
"Design is not just what it looks like and feels like. Design is how it works." - Steve Jobs
Thank you for reading! Stay tuned for more updates on my UI/UX design journey.
#UIUXDesign #LearningJourney #Typography #UXUI #UserInterface #DesignThinking #PrinceChouhan | prince_chouhan | |
1,900,598 | 1300 followers ... de repente | No es que las cifras de followers me quiten el sueño la verdad. Creo que como casi todos en primer... | 0 | 2024-06-25T20:34:34 | https://dev.to/jagedn/1300-followers-de-repente-4o32 | No es que las cifras de followers me quiten el sueño la verdad. Creo que como casi todos en primer lugar escribimos para nosotros mismos pero obviamente tambien para que nos lean, asi que de vez en cuando echas un ojo a ver cuanta gente te sigue
Hoy, y sin haber publicado mucho ni de calidad creo, he visto que tengo 1300 followers pero la mayoría el nick acaba en numeros, son perfiles de reciente creacion y sin ningun post
No se Rick... ojala fueran de verdad y mi contenido les guste pero bueno si son bots no pasa nada, espero poder llegar a los que no lo son y aportarles algo de mis articulos | jagedn | |
1,900,435 | Word Embeddings | Human Language and word meanings Human languages can be highly complex and misunderstood.... | 0 | 2024-06-25T20:34:18 | https://dev.to/rohab_shabbir/word-embeddings-446a | machinelearning, nlp, wordvector |
##**Human Language and word meanings**
Human languages can be highly complex and misunderstood. It can be easily understandable for humans but not for computers. Because same words can have different meanings in different context.
Google translate translates to a good certain limit but in some cases when it literally translates a webpage, some of the lines doesn't make sense because sometimes it translates independent of context. GPT-3 is a very good AI tool released by openAI that is trained over large models for translation, summarization and other purposes.
##**Meaning**
What is meaning according to different definitions:
- the idea represented by word or phrase
- the idea that a person wants to convey using different words, phrases etc
- the idea that is expressed in a work of writing
the commonest way of linguistic way of thinking about meaning is that they say
"it is a signifier(symbol) that signifies an idea"
It is also referred as denotational semantics
This model is not deeply implemented. In NLP the traditionally the way by which meaning is handled is to make use of dictionaries.
##**Wordnet**
Wordnet is a large lexical database of English, which makes groups of synonyms of words.
But it is also not highly efficient. For example, in this database good id grouped as synonym of proficient that may be correct but not in all contexts.
It is also missing new words.
##**Word Relationships**
**Representing words as discrete symbols**
In traditional NLP, words are represented as discrete symbols. In deep learning we have symbols like hotel, conference, motel which we refer as localized representation.
We have vector representation for each word separately.
For example: if I represent 2 words {hot vectors)
hotel as [0 0 0 0 0 0 0 0 0 0 1 0 0]
motel as [0 0 0 0 0 0 0 1 0 0 0 0 0]
now if a user mistakenly type motel instead of hotel this vector representation will never take uuser from motel to hotel because it doesn't show any similarity between these 2 words
**Distributional semantics**
In this, a meaning of a word is given by words around which it frequently occurs(meaning by context).
- The bank of road is curved here
- This bank increases the salary of employs annually
Depending upon context the word "bank" has different meaning
##**Word Embeddings**
Word vectors are called word embeddings.
It is basically how we represent a word to neural network. The word is represented in form of vectors in continuous vector space.
A dense vector is being built for each word, chosen so that it is similar to vectors of words that appear in similar contexts.
The very common size for vectors in real life is 300 dimensional vector.
##**Word2vec**
Introduced by Mikolov et al. in 2013.
**Idea**
We have a large number of text.
Each word in fixed vocabulary is represented by a vector.
Go through each position in text (t), which will have a center word (c) and context (o).
Use similarity of word vectors for c and o to calculate probability of o given c or the other way.
keep adjusting word vectors to increase probability.
Remember every word has 2 vectors:
center vector and context vector
**To minimize the loss**
To train a model, we gradually adjust our parameters to minimize loss.
We use some calculus here i.e. Chain rule in order to determine how to optimize values of parameters.
##**Conclusion**
In conclusion, word embeddings have transformed NLP by representing words as dense vectors that capture semantic relationships and contextual meanings, which traditional methods like one-hot encoding and TF-IDF could not. Tools like WordNet helped but had limitations. Word2Vec, introduced by Mikolov et al., significantly advanced the field by using context to create meaningful word vectors. These embeddings are crucial for translating, summarizing, and understanding text more accurately, bridging the gap between human language complexity and machine understanding.
| rohab_shabbir |
1,899,399 | Test | Test | 0 | 2024-06-25T20:34:05 | https://dev.to/segoja7/cross-plane-the-next-phase-of-infrastructure-automation-testing-infrastructure-with-crossplane-in-aws-3j3n | aws, crossplane, terraform, k8s | Test | segoja7 |
1,900,599 | Software Engineer in Dubai: Jobs, Salary & Challenges Explained for Fresh Graduates and Entry-Level Professionals | If you're a fresh graduate, entry-level engineer, or junior developer finding your first job in Dubai... | 0 | 2024-06-25T20:31:55 | https://dev.to/awwsamu/software-engineer-in-dubai-jobs-salary-challenges-explained-for-fresh-graduates-and-entry-level-professionals-1n51 | career, careerdevelopment, dubai | If you're a fresh graduate, entry-level engineer, or junior developer finding your first job in Dubai is challenging.
This article provides realistic and practical advice for freshers seeking software engineering jobs in Dubai.
## Understanding the Job Market for Freshers in Dubai
Dubai’s tech industry, while growing, is still small compared to major tech hubs like the USA, India, or Europe.
The overall market size in the UAE is estimated to be around $25 to $35 billion. It's also close to tech markets which have a relatively low average salary. For example, nearby India, which boasts a $250 billion market has a lower average wage than in Dubai.
This means that there are a lot of skilled engineers who are interested in relocating to Dubai, given the perceived increase in wages and the relatively easy visa process. This is why competition for positions in Dubai is fierce.
For fresh graduates and junior software developers, the issues is exacerbated, by the fact that companies in Dubai prefer hiring experienced professionals who can handle multiple tasks and mentor staff.
If you're going to land a job in Dubai, you therefore need to be aware of this and realise that getting a job as a fresher will take a lot of hard work and determination.
## **Preferred Skills and Experience**
Most companies in Dubai are on the lookout for versatile professionals. Generally for less skilled developers your opportunities are goign to fall into two camps; web development and full-stack development. Here's a breakdown of the skills you need for each:
### Web Development:
- **Front-End Technologies**: Proficiency in HTML, CSS, JavaScript, and frameworks like React or Vue.js.
- **Mobile Optimization**: Skills in creating mobile-friendly websites and improving page performance.
- **SEO and Performance**: Understanding of search engine optimization and web performance metrics.
### Full-Stack Development:
- **Back-End Technologies**: Knowledge of languages like Node.js, Java, and Python.
- **Database Management**: Experience with both SQL and NoSQL databases.
- **DevOps**: Basic understanding of DevOps practices and tools to manage end-to-end development processes.
## Companies to Target
### Government and Semi-Government Entities:
**Emirates**: A leading airline requiring robust web and full-stack development skills.
**Government Portals**: Various government entities need dedicated web developers for their portals.
### Private Sector:
**Tech Consultancies**: Firms like Hays and Robert Half frequently list tech job openings.
**Real Estate Companies**: The booming real estate market needs developers to manage property listing websites.
**E-commerce**: Companies like Dubizzle and Noon offer tech roles focused on product and service development.
## Salary Expectations
For a detailed overview of salaries I recommend this [full guide to the average software engineer salaries in Dubai](https://zerotaxjobs.com/articles/software-engineer-salaries-in-dubai).
However for fresh graduates and entry-level positions, most opportunities will be at companies with small budgets so unfortunately, the salaries in Dubai tend to be quite low.
### Web Developers:
**Starting Salary**: Approximately 5,000 AED per month. (~$1360 USD)
### Full-Stack Developers:
**Starting Salary**: Around 15,000 AED per month. (~$4080 USD)
These are starting salaries, and whilst this salaries could seem reasonable to people from more economical countries, you need to appreciate that Dubai is not a cheap place to live, so these salaries do not go far. I recommend using this [Dubai Software Engineer Salary and Cost of Living Calculator](https://zerotaxjobs.com/tools/dubai-software-engineer-salary-calculator) to calculate how your finances might be affected by moving to Dubai.
## Overcoming Challenges
As explained, the biggest challenges fresh graduates face is the high competition for jobs, coupled with the preference for experienced candidates. Here are some strategies to overcome this:
### Development Experience:
**Internships**: Seek internships that provide hands-on experience.
**Side Projects**: Develop personal or open-source projects to build your portfolio.
**Freelancing**: Take up freelance projects to gain practical experience.
### Check My Job Listings:
You can visit my own [site to find a software engineering job in Dubai](https://zerotaxjobs.com/). However, I generally find our jobs skewed towards senior positions, because junior positions are often filled through references and might not be publicly listed.
### Networking:
**LinkedIn**: Use LinkedIn to connect with professionals in your field. Engage with posts and join relevant groups.
**Tech Conferences**: Attend conferences like GITEX to meet industry professionals and learn about the latest trends.
### Recruitment Agencies:
**[Hays](https://www.hays.ae/recruitment-services)**: A well-known consultancy that frequently lists tech job opportunities.
**[Robert Half](https://www.roberthalf.ae/)**: Another prominent consultancy specializing in tech placements.
### Improving Personal Skills
While technical skills are crucial, soft skills like communication and presentation are equally important. Given Dubai's multicultural environment, you’ll be working with people from various nationalities. Here’s how to enhance your personal skills:
**Communication Skills**: Practice clear and effective communication.
**Presentation Skills**: Learn how to present your ideas confidently.
**Cultural Awareness**: Be mindful of cultural differences and learn to work in diverse teams.
### Leveraging Referrals
Referrals are a significant part of the hiring process in Dubai. Here’s how to leverage them:
**Networking**: Build a professional network on LinkedIn and other platforms.
**Employee Referrals**: Reach out to current employees of your target companies and request referrals.
### Timing Your Job Search
The job market in Dubai has seasonal fluctuations. The best times to apply for jobs are outside of the major vacation periods:
**Avoid**: Mid-December to mid-January (winter vacation) and July to August (summer vacation).
**Best Time**: February to June and September to November.
## Conclusion
Starting a career as a software engineer in Dubai can be challenging, especially for fresh graduates and entry-level professionals. However, by understanding the market dynamics, honing your technical and personal skills, and leveraging the right resources, you can navigate these challenges successfully. Be realistic about the competition and salary expectations, but remain hopeful and diligent in your job search. Dubai's tech industry is growing, and with the right approach, you can find opportunities that align with your career goals.
If you found this article helpful, feel free to [reach out with any questions or comments about working as a software engineer in Dubai](https://zerotaxjobs.com/about). Your feedback helps me provide more targeted and useful advice.
Good luck with your job search! | awwsamu |
1,900,596 | TypeScript SDK Development: A 5-year-old could follow this step-by-step ~ Part 5, CDN for Browsers | Helloooooooo! Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀 Part 1:... | 0 | 2024-06-25T20:26:22 | https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a | typescript, node, javascript, webdev | **Helloooooooo!**
Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀
Part 1: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif)
Part 2: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e)
Part 3: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c)
Part 4: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6)
This is Part 5 of our SDK development series where we get a CDN of our SDK
## Contents:
* ⚡ `Getting CDN`
* ⚡ `Integrating CDN and testing SDK`
### Step 1: Get a CDN
Head over to [`https://www.jsdelivr.com/`](https://www.jsdelivr.com/) and search for your NPM package.
Choose the default version, and copy the link.
Head over to the Test Browser app, and integrate the CDN:
```xml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/ts-lib-template-starter@1.0.0/dist/index.global.min.js"></script>
</head>
<body>
This is a Test HTML
<script>
sdk.fetchUsers().then((users) => console.log(users));
</script>
</body>
</html>
```
Open the file, and see the result:

### Step 2: Getting the latest CDN version always
Put `@latest` instead of the version to always fetch the latest CDN version
`https://cdn.jsdelivr.net/npm/ts-lib-template-starter@latest/dist/index.global.min.js`
Sometimes, when a new version of SDK is published, `jsDeliver` few minutes to a few days to point `@latest` version to the updated version.
To fix this, when you publish a new version, head over to [`https://www.jsdelivr.com/tools/purge`](https://www.jsdelivr.com/tools/purge) and enter the link of the CDN like:

This will purge the cache and point `@latest` version to the updated version.
## Wrapping Up:
We Just completed the steps to get a CDN of our SDK.
Stay tuned for further parts to dive deep into SDK development and explore features like Web Push Notifications, Service Workers etc. 🚀
.....
Now you're equipped with the knowledge to publish your own SDK. Happy coding! 🚀
That's it, folks! hope it was a good read for you. Thank you! ✨
👉 Follow me
[GitHub](https://github.com/smyaseen)
[LinkedIn](https://www.linkedin.com/in/sm-y) | smy |
1,900,594 | TypeScript SDK Development: A 5-year-old could follow this step-by-step ~ Part 4, Publishing to NPM | Helloooooooo! Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀 Part 1:... | 0 | 2024-06-25T20:25:36 | https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6 | webdev, javascript, node, typescript | **Helloooooooo!**
Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀
Part 1: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif)
Part 2: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e)
Part 3: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c)
Part 5: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a)
This is Part 4 of our SDK development series where we will publish our SDK
## Contents:
* ⚡ `Creating an NPM account`
* ⚡ `Publishing to NPM, semantic versioning, and LICENSE`
### Step 1: Creating an NPM account
Head over to [https://www.npmjs.com](https://www.npmjs.com) and create an account.
### Step 2: Publish
In the terminal write:
```bash
npm login
```
After following the login steps, write
```bash
npm publish
```
This can fail due to duplicate package names or wrong configuration in `package.json`
Your `package.json` should look like the following:
```json
{
"name": "ts-lib-template-starter",
"version": "1.0.0",
"description": "SDK development tutorial",
"main": "./src/index.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsup ./src/index.ts --watch"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^20.14.8",
"tsup": "^8.1.0",
"typescript": "^5.5.2"
}
}
```
Congrats you just published your first SDK to NPM 🎉🥳 🚀🚀🚀
### Step 3: Semantic versioning
When publishing a library it is good to keep versioning in check. Versioning helps the developer integrate the code to get an idea of what update happened to the SDK. Furthermore, the right versioning will help package managers to update to the level as it is mentioned in their `package.json`.
To help developers who rely on your code, we recommend starting your package version at `1.0.0` and incrementing as follows:
| **Code status** | **Stage** | **Rule** | **Example version** |
| --- | --- | --- | --- |
| First release | New product | Start with 1.0.0 | 1.0.0 |
| Backward compatible bug fixes | Patch release | Increment the third digit | 1.0.1 |
| Backward compatible new features | Minor release | Increment the middle digit and reset last digit to zero | 1.1.0 |
| Changes that break backward compatibility | Major release | Increment the first digit and reset middle and last digits to zero | 2.0.0 |
Learn more about semantic versioning here: [https://docs.npmjs.com/about-semantic-versioning](https://docs.npmjs.com/about-semantic-versioning)
### Step 4: LICENSE
Specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.

source: [https://snyk.io/learn/open-source-licenses/](https://snyk.io/learn/open-source-licenses/)
For example, this SDK is open for distribution and modifying the code so I would use MIT as LICENSE.
In `package.json`
```json
"license": "MIT"
```
Learn more about various types of LICENCES here: [https://snyk.io/learn/open-source-licenses/](https://snyk.io/learn/open-source-licenses/)
## Wrapping Up:
We Just completed the steps to publish our SDK. Head over to Part 5, where we will make a CDN for browsers 🚀
.....
Now you're equipped with the knowledge to publish your own SDK. Happy coding! 🚀
That's it, folks! hope it was a good read for you. Thank you! ✨
👉 Follow me
[GitHub](https://github.com/smyaseen)
[LinkedIn](https://www.linkedin.com/in/sm-y) | smy |
1,900,505 | Blackjack | Blackjack,1xbet365 dünya genelinde en popüler kart oyunlarından biridir. İki ila yedi oyuncu... | 0 | 2024-06-25T19:59:20 | https://dev.to/burakoz/blackjack-419g | 1xbet, blackjack, poker |

Blackjack,[1xbet365](https://1xbet365.xyz/) dünya genelinde en popüler kart oyunlarından biridir. İki ila yedi oyuncu arasında oynanabilir ve amaç, ellerdeki kartların toplam değerini 21'e en yakın olacak şekilde ayarlamaktır. Oyunun kuralları ve temel bilgileri aşağıda özetlenmiştir: [1xbet365](https://1xbet365.xyz/)
Temel Kurallar:
Kart Değerleri:
As: 1 veya 11 puan olarak değerlendirilebilir, oyuncunun isteğine bağlıdır.
2-10 arasındaki kartlar: Üzerlerindeki sayı değeri kadar puan verir.
Vale (J), Kız (Q), Papaz (K): Her biri 10 puan değerindedir.
Oyun Süreci:
Oyun, bir veya daha fazla deste kartla oynanabilir. Genellikle 6-8 deste kullanılır.
Oyuncular ve krupiye (dağıtıcı), iki kart alır. Oyuncuların kartları açık, krupiyenin ise biri açık, diğeri kapalıdır.
Oyuncuların amacı, ellerindeki kartların toplamını 21’e mümkün olduğunca yakın bir değere getirmektir. 21’i aşmamalıdırlar.
Oyun Seçenekleri:
Hit (Kart Çekme): Oyuncu, eline bir kart daha eklemeyi seçebilir.
Stand (Bekleme): Oyuncu, elindeki kartlarla devam etmeye karar verebilir.
Double Down (İkiye Katlama): Oyuncu, ilk iki kartının toplamına güveniyorsa bahsini ikiye katlayabilir ve yalnızca bir kart daha çekebilir.
Split (Bölme): Oyuncunun ilk iki kartı aynı değerdeyse, elini iki ayrı ele bölüp her biri için ayrı bahis yapabilir.
Surrender (Teslim Olma): Oyuncu, ilk iki kartını gördükten sonra bahsinin yarısını geri alarak oyundan çekilebilir (her casinoda bulunmaz).
Krupiye Kuralları:
Krupiye, elinin toplam değeri 17 veya daha fazlaysa kart çekmeyi bırakmalıdır.
Krupiyenin eli 16 veya daha düşükse kart çekmeye devam etmelidir.
Blackjack:
Oyuncu veya krupiye, ilk iki kartında bir As ve 10 puanlık bir kart (10, J, Q, K) alırsa bu "blackjack" olarak adlandırılır ve genellikle 1.5 katı ödeme yapar (3:2 oranında).
Strateji:
Blackjack, şans kadar stratejiye de dayalı bir oyundur. Temel strateji, hangi durumda kart çekmek, beklemek veya diğer seçenekleri kullanmak gerektiğini belirlemeyi içerir. Ayrıca, kart sayma teknikleri, oyunun sonucunu tahmin etmeye yardımcı olabilir ve avantaj sağlar, ancak çoğu kumarhane bu tür tekniklere izin vermez.
Blackjack Türleri:
Classic Blackjack: Geleneksel blackjack kuralları uygulanır.
European Blackjack: Krupiye ilk iki kartını almaz, sadece oyuncuların elleri tamamlandıktan sonra ikinci kartını çeker.
Atlantic City Blackjack: Oyunculara daha fazla seçenek sunar ve genellikle krupiyenin "stand" yapması gereken toplam değeri 17'dir.
Vegas Strip Blackjack: Atlantic City kurallarına benzer, ancak belirli varyasyonları vardır.
Blackjack, basit kuralları ve heyecan verici yapısıyla hem yeni başlayanlar hem de deneyimli oyuncular için cazip bir oyun olmaya devam ediyor. Kurallar ve stratejiler hakkında bilgi sahibi olarak, oyunun keyfini çıkarabilir ve kazanma şansınızı artırabilirsiniz.
| burakoz |
1,900,593 | TypeScript SDK Development: A 5-year-old could follow this step-by-step ~ Part 3, Making Test Apps | Helloooooooo! Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀 Part 1:... | 0 | 2024-06-25T20:23:57 | https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c | webdev, javascript, typescript, node | **Helloooooooo!**
Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀
Part 1: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif)
Part 2: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e)
Part 4: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6)
Part 5: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a)
This is Part 3 of our SDK development series where we will dive into creating test apps for react, browser, node, and legacy node.
## Contents:
* ⚡ `Setting up tsup for different execution environments`
* ⚡ `Creating our apps`
### Step 1: Setting up `tsup` for different environments
At the root of the project create `tsup.config.ts` file, and paste the following content:
```javascript
import { defineConfig } from "tsup";
export default defineConfig({
clean: true,
dts: true,
entry: ["src/index.ts"],
format: ["cjs", "esm", "iife"],
minify: true,
});
```
`clean` - Clean the output directory before each build
`dts` - type definitions for TypeScript
`entry` - specifying the entry point
`format` - `cjs` for legacy, `esm` for newer node projects and `iife` for browsers
`minify` - minifies our code and reduces bundle size
No extra configuration is needed, as `tsup` will automatically look for this file and handle everything for us :)
Now exit and re-rerun `build` command
```bash
npm run build
```
You will see the following output in our `dist` folder

`index.cjs` - for CJS output
`index.js` - for ESM
`index.global.js` - for browsers
### Step 2: Create a Node App
In `example-apps/Node` create a `index.js` file and paste the following content:
```javascript
import sdk from "../../dist/index.js";
console.log(await sdk.fetchUsers());
```
Now run the file with a node in a separate terminal and head over to the folder:
```bash
node index.js
```
You will see the output in the terminal.
### Step 3: Create a Legacy Node App
In `example-apps/Legacy-Node` create a `index.cjs` file and paste the following content:
```javascript
const sdk = require("../../dist/index.cjs");
sdk.default.fetchUsers().then((users) => console.log(users));
```
Now run the file with a node in a separate terminal and head over to the folder:
```bash
node index.cjs
```
You will see the output in the terminal.
### Step 4: Create a Browser App
In `example-apps/Browser` create a `index.html` file and paste the following content:
```xml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="../../dist/index.global.js"></script>
</head>
<body>
This is a Test HTML
<script>
sdk.fetchUsers().then((users) => console.log(users));
</script>
</body>
</html>
```
Open the file in the browser, you should see the following response in the inspect element's console tab:

### Step 5: Create a React App
Create a Link to our SDK, to behave as a library for projects without publishing.
```bash
npm link
```
In `example-apps` create a react app, for example with vite:
```bash
npm create vite@latest
```
and following steps. After successfully creating a react app, run the following command in the React root folder to link our SDK.
```bash
npm link ts-lib
```
In place of `ts-lib`, it should be your SDK / Library name in the package.json
After creating the React app, open a component file like `App.jsx` and integrate SDK like the following:
```javascript
import sdk from "ts-lib";
console.log(await sdk.fetchUsers());
```
Full view:
```javascript
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
import sdk from "ts-lib";
console.log(await sdk.fetchUsers());
function App() {
const [count, setCount] = useState(0);
return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
);
}
export default App;
```
Run the react App, and head over to the console, it should look like the following:
## Wrapping Up:
We Just completed the steps to build and run our SDK in different environments.
Head over to Part 4 to publish our SDK.
.....
Now you're equipped with knowledge to build your own SDK. Happy coding! 🚀
That's it, folks! hope it was a good read for you. Thank you! ✨
👉 Follow me
[GitHub](https://github.com/smyaseen)
[LinkedIn](https://www.linkedin.com/in/sm-y) | smy |
1,900,592 | TypeScript SDK Development: A 5-year-old could follow this step-by-step ~ Part 2, folder structure - integrating API | Helloooooooo! Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀 Part 1:... | 0 | 2024-06-25T20:22:57 | https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e | webdev, javascript, node, typescript | **Helloooooooo!**
Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀
Part 1: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif)
Part 3: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c)
Part 4: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6)
Part 5: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a)
This is Part 2 of our SDK development series where we will dive into creating a folder structure and integrating an API
Heads up: any attribute or method starting from `#` is a private field. Private fields are truly private and are not emitted on the console log, `d.ts`, or elsewhere.
## Contents:
* ⚡ `Creating a folder strucutre`
* ⚡ `Coding an example for fetching users from API`
### Step 1: Creating a folder structure

`apis` - for all external APIs
`models` - for all our interfaces
`services` - for business logic code
`index.ts` - our entry point
`example-apps` - contains our test apps for React, Browser, Node
### Step 2: Create a HTTP Client
In `src/services` create a `HttpClient.service.ts` file and paste the following content:
```javascript
export class HttpClient {
static #baseUrl: string = "https://jsonplaceholder.typicode.com";
constructor() {}
async get(endpoint: string) {
try {
const response = await fetch(`${HttpClient.#baseUrl}${endpoint}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error fetching data:", error);
throw error;
}
}
}
```
We have created a basic HTTP Client and using `jsonplaceholder` as our testing API endpoint.
### Step 3: Creating a User Model
In `src/models` create a `User.model.ts` file and paste the following content:
```javascript
export interface User {
id: number;
username: string;
email: string;
}
```
### Step 4: Create an API to fetch Users
In `src/apis` create a `Users.api.ts` file and paste the following content:
```javascript
import type { User } from "../models/User.model.ts";
import { HttpClient } from "../services/HttpClient.service.ts";
export class UsersAPI {
#httpClient: HttpClient;
constructor() {
this.#httpClient = new HttpClient();
}
async getUsers(): Promise<User[]> {
try {
const users = await this.#httpClient.get("/users");
return users as User[];
} catch (error) {
console.error("Error fetching users:", error);
throw error;
}
}
}
```
Created a basic example of fetching users from an external endpoint.
### Step 5: Create an Entry Point
Inside `src/index.ts` paste the following content:
```javascript
import { UsersAPI } from "./apis/Users.api.ts";
class SDK {
static #instance: SDK;
#usersAPI: UsersAPI;
constructor() {
this.#usersAPI = new UsersAPI();
}
public static getInstance(): SDK {
if (!SDK.#instance) {
SDK.#instance = new SDK();
}
return SDK.#instance;
}
public fetchUsers() {
return this.#usersAPI.getUsers();
}
}
export default SDK.getInstance();
```
A basic entry point of SDK.
This is a Singleton Class to have 1 existence throughout our application. Later useful when initializing with properties like API key once in application.
### Step 6: Build the SDK
Add the following script to your `package.json`
```bash
"build": "tsup ./src/index.ts --watch"
```
`--watch` the command will watch for any changes to the directory and automatically build your SDK.
Now run:
```bash
npm run build
```
### Step 7: Create a test Node App
In `example-apps` create a `index.js` file and paste the following content:
```javascript
import sdk from "../../dist/index.js";
console.log(await sdk.fetchUsers());
```
Now run the file with node:
```bash
node index.js
```
Your output should be looking like the following:

Congrats 🎉🥳 🚀🚀🚀 We Just Built and Ran our first proper SDK!
## Wrapping Up:
We Just completed the basic steps to build and run our proper SDK. Head over to Part 3, where we will integrate our first test React app, Browser app, Node app, and Legacy Node app 🚀
.....
Now you're equipped with knowledge to build your own SDK. Happy coding! 🚀
That's it, folks! hope it was a good read for you. Thank you! ✨
👉 Follow me
[GitHub](https://github.com/smyaseen)
[LinkedIn](https://www.linkedin.com/in/sm-y) | smy |
1,900,591 | TypeScript SDK Development: A 5-year-old could follow this step-by-step ~ Part 1, our first MVP | Helloooooooo! Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀 Part 2:... | 0 | 2024-06-25T20:22:16 | https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-1-our-first-mvp-1cif | webdev, typescript, javascript, node | **Helloooooooo!**
Hope you're doing great! This is SMY! 👋 Let's Jump right in 🚀
Part 2: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-2-folder-structure-integrating-api-3p2e)
Part 3: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-3-making-test-apps-4n3c)
Part 4: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-4-publishing-to-npm-48o6)
Part 5: [https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a](https://dev.to/smy/typescript-sdk-development-a-5-year-old-could-follow-this-step-by-step-part-5-cdn-for-browsers-237a)
Source Code: [https://github.com/smyaseen/typescript-sdk-template](https://github.com/smyaseen/typescript-sdk-template)
## Contents:
* ⚡ `Some Background of SDK Development`
* ⚡ `Developing and running our first version`
## 1️⃣ What -
SDK (sometimes also known as library) serves as a plug-in in applications to derive additional features from the technology.
## 2️⃣ Why -
SDK development with TypeScript offers reliability over a long time due to type safety, and maintenance in the long run.
## 3️⃣ How -
The fundamental steps required to build the SDK are the following:
1. Initializing the project with the right workflow settings.
2. Choosing Bundler, and understanding its purpose.
3. Understanding ESM, CJS, IIFE UMD to run SDK on different environments.
4. Publishing as a library on NPM, semantic versioning and License.
5. NPM for SPAs and CDN for Browsers.
In Part 1, we are going to build our first basic SDK to get a basic understanding.
### Step 1: Initialize Project
Run the following command to set the project in a new folder:
```bash
npm init -y
```
`"-y"` defaults to yes to all the follow-up prompts. You can change it later in the Package.json like author, license, version etc.
Head over to `package.json` and add `type: module` to work with the latest EcmaScript Module system (ESM).
Your `package.json` should look like the following:
```json
{
"name": "ts-lib",
"version": "1.0.0",
"description": "SDK development tutorial",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC"
}
```
### Step 2: Install fundamental dev libraries
1. TypeScript
2. `@types/node` - to work TypeScript with NodeJS
3. `tsup` - The simplest and fastest way to bundle your TypeScript libraries
```bash
npm i typescript @types/node tsup -D
```
### Step 3: Setup `tsconfig` for TypeScript settings
Create a `tsconfig.json` file at the root of the project
```bash
touch tsconfig.json
```
Head over to the file and paste the following configuration:
```json
{
"compilerOptions": {
/* Base Options: */
"esModuleInterop": true,
"allowImportingTsExtensions": true,
"emitDeclarationOnly": true,
"skipLibCheck": true,
"target": "es2022",
"allowJs": true,
"resolveJsonModule": true,
"moduleDetection": "force",
"isolatedModules": true,
"verbatimModuleSyntax": true,
/* Strictness */
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
/* If transpiling with TypeScript: */
"module": "NodeNext",
"sourceMap": true,
"outDir": "dist",
/* AND if you're building for a library: */
"declaration": true,
/* If your code runs in the DOM: */
"lib": ["es2022", "dom", "dom.iterable"]
},
"exclude": ["node_modules", "dist"]
}
```
You can hover over each property to learn more in-depth about it.
The fundamental thing to understand here is:
```json
"module": "NodeNext",
"sourceMap": true,
"outDir": "dist",
```
1. " `NodeNext` is the right option for authoring libraries, because it prevents you from emitting ESM with module specifiers that *only* work in bundlers but will crash in Node.js. When writing conventional code, using common sense, and relying on high-quality dependencies, its output is usually highly compatible with bundlers and other runtimes". You can learn more about it here [https://blog.andrewbran.ch/is-nodenext-right-for-libraries-that-dont-target-node-js/](https://blog.andrewbran.ch/is-nodenext-right-for-libraries-that-dont-target-node-js/)
2. `sourceMap` - Enables the generation of source files. These files allow debuggers and other tools to display the original TypeScript source code when working with the emitted JavaScript files. You can disable it for production.
3. `outDir` - Specify an output folder for all emitted files.
```json
/* AND if you're building for a library: */
"declaration": true,
/* If your code runs in the DOM: */
"lib": ["es2022", "dom", "dom.iterable"]
```
1. `declaration` - Generate .d.ts files from TypeScript and JavaScript files in your project.
2. `lib` - Specify a set of bundled library declaration files that describe the target runtime environment. `es2022` is for node applications like React, and `dom` & `dom.iterable` for running the library in the browser.
### Step 4: Write our first code
Create a `index.ts` file, and write the following basic code
```javascript
const add = (a: number, b: number): number => a + b;
const subtract = (a: number, b: number): number => a - b;
export { add, subtract };
```
Build our first code:
```bash
tsup ./index.ts
```
You may now see we have a `dist` folder with an output file `index.cjs`
Let's integrate and run our first SDK!
Create a `app.js` file, and paste the following code:
```bash
import { add, subtract } from "./dist/index.cjs";
console.log(add(1, 2));
console.log(subtract(2, 1));
```
Since we haven't published our SDK, we are directly linking with local build.
Now run our first app
```bash
node app.js
```
You should see the following output
```bash
3
1
```
Congrats 🎉🥳 🚀🚀🚀 We Just Built and Ran our first SDK!
## Wrapping Up:
We Just completed the basic steps to build and run our first SDK. Head over to Part 2, where we will build a basic folder structure, and integrate an External API endpoint 🚀
.....
Now you're equipped with knowledge to build your own SDK. Happy coding! 🚀
That's it, folks! hope it was a good read for you. Thank you! ✨
👉 Follow me
[GitHub](https://github.com/smyaseen)
[LinkedIn](https://www.linkedin.com/in/sm-y) | smy |
1,900,522 | Converting RGBA to HEX in JavaScript: A Comprehensive Guide | In web development, managing colors efficiently is crucial for creating visually appealing... | 0 | 2024-06-25T20:19:25 | https://dev.to/tsolutionsx/converting-rgba-to-hex-in-javascript-a-comprehensive-guide-amn | javascript, webdev, programming | In web development, managing colors efficiently is crucial for creating visually appealing applications. One common task is converting colors from RGBA (Red, Green, Blue, Alpha) format to HEX (Hexadecimal) format. In this article, we’ll explore a robust JavaScript function to achieve this conversion seamlessly.
## **Introduction to Color Formats**
Colors in web development can be represented in various formats, including:
**RGBA**: Specifies colors with Red, Green, Blue, and Alpha (opacity) values.
**HEX**: Represents colors using a hexadecimal code.
Converting between these formats is often necessary for consistent styling across different platforms and tools.
**The `rgbaToHex` Function**
The rgbaToHex function is designed to convert an RGBA color string to a HEX color string. Let's break down the function and understand how it works.
```javascript
export const rgbaToHex = (colorStr: string, forceRemoveAlpha: boolean = false) => {
// Check if the input string contains '/'
const hasSlash = colorStr.includes('/')
if (hasSlash) {
// Extract the RGBA values from the input string
const rgbaValues = colorStr.match(/(\d+)\s+(\d+)\s+(\d+)\s+\/\s+([\d.]+)/)
if (!rgbaValues) {
return colorStr // Return the original string if it doesn't match the expected format
}
const [red, green, blue, alpha] = rgbaValues.slice(1, 5).map(parseFloat)
// Convert the RGB values to hexadecimal format
const redHex = red.toString(16).padStart(2, '0')
const greenHex = green.toString(16).padStart(2, '0')
const blueHex = blue.toString(16).padStart(2, '0')
// Convert alpha to a hexadecimal format (assuming it's already a decimal value in the range [0, 1])
const alphaHex = forceRemoveAlpha
? ''
: Math.round(alpha * 255)
.toString(16)
.padStart(2, '0')
// Combine the hexadecimal values to form the final hex color string
const hexColor = `#${redHex}${greenHex}${blueHex}${alphaHex}`
return hexColor
} else {
// Use the second code block for the case when '/' is not present
return (
'#' +
colorStr
.replace(/^rgba?\(|\s+|\)$/g, '') // Get's rgba / rgb string values
.split(',') // splits them at ","
.filter((string, index) => !forceRemoveAlpha || index !== 3)
.map(string => parseFloat(string)) // Converts them to numbers
.map((number, index) => (index === 3 ? Math.round(number * 255) : number)) // Converts alpha to 255 number
.map(number => number.toString(16)) // Converts numbers to hex
.map(string => (string.length === 1 ? '0' + string : string)) // Adds 0 when length of one number is 1
.join('')
)
}
}
```
## **Understanding the Code**
**Input Checking**
The function starts by checking if the input string contains a ‘/’ character, which indicates the presence of an RGBA value.
**Handling RGBA with Slash**
If a slash is present, the function extracts the RGBA values using a regular expression.
The RGB values are converted to their hexadecimal equivalents.
The alpha value, if present, is converted to hexadecimal and optionally removed based on the `forceRemoveAlpha` flag.
The final HEX color string is constructed and returned.
**Handling Standard RGBA**
If no slash is present, the function handles standard `rgba()` or `rgb()` strings.
The RGB values are extracted, converted to numbers, and then to hexadecimal.
The alpha value is managed similarly to the previous case, with optional removal.
## **Usage Examples**
Here are a few examples demonstrating how to use the rgbaToHex function:
```javascript
console.log(rgbaToHex('rgba(255, 99, 71, 0.5)')) // Output: #ff634780
console.log(rgbaToHex('rgb(255, 99, 71)')) // Output: #ff6347
console.log(rgbaToHex('255 99 71 / 0.5')) // Output: #ff634780
console.log(rgbaToHex('255 99 71 / 0.5', true)) // Output: #ff6347
```
## **Conclusion**
Converting RGBA to HEX can be straightforward with the right approach. The rgbaToHex function presented in this article provides a versatile and efficient method for this conversion, accommodating different input formats and optional alpha value removal. Whether you're styling a web application or working on a design project, this function can help ensure your colors are consistent and correctly formatted.
| tsolutionsx |
1,900,521 | Open WebUI + talkd.ai/Dialog: RAG deployment and Development made easy with awesome UI! | Hey fellow devs and open-source enthusiasts! 🎉 We've got some awesome news that's going to... | 0 | 2024-06-25T20:19:05 | https://dev.to/vmesel/open-webui-talkdaidialog-rag-deployment-and-development-made-easy-with-awesome-ui-3gla | openwebui, talkdai, ui | ---
title: Open WebUI + talkd.ai/Dialog: RAG deployment and Development made easy with awesome UI!
published: true
description:
tags: openwebui, talkdai, ui
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ansg4iyxmwjiwltl8hok.png
# Use a ratio of 100:42 for best results.
---
Hey fellow devs and open-source enthusiasts! 🎉 We've got some awesome news that's going to supercharge the way you build and interact with RAGs.
We're super excited to announce that Open WebUI is our official front-end for RAG development. It's a total match!
For those who don't know what talkd.ai/Dialog is:
### talkd.ai/Dialog: the brain of the RAGs
Now, talkd.ai/Dialog is where the magic of conversation happens. Our dialog API makes it a breeze to build chatbots and virtual assistants that actually understand what users are saying and can ensure appropriate context is being passed to the prompt.
### Why talkd.ai/Dialog is a Game-Changer:
- Smart as Heck: Uses top-notch natural language processing to get what users mean.
- Context-Aware: Keeps track of conversation context so it doesn’t sound like a broken record.
- Scalable: Can handle a ton of simultaneous chats without breaking a sweat.
- Integration Friendly: Plug it into just about anything – WhatsApp, Telegram, Slack, you name it and you can build your own plugin!
## OpenWebUI: The Universal Web Interface
OpenWebUI is an extensible, feature-rich, and user-friendly self-hosted WebUI designed to operate entirely offline. It supports various LLM runners, including Ollama and OpenAI-compatible APIs. For more information, be sure to check out our Open WebUI Documentation.
### Key Features of OpenWebUI:
- Effortless Setup: Install seamlessly using Docker or Kubernetes for a hassle-free experience
- Ollama/OpenAI API Integration: Effortlessly integrate OpenAI-compatible APIs for versatile conversations alongside Ollama models. Customize the OpenAI API URL to link with LMStudio, GroqCloud, Mistral, OpenRouter, and more.
- Pipelines, Open WebUI Plugin Support: Seamlessly integrate custom logic and Python libraries into OpenWebUI using Pipelines Plugin Framework. Examples include Function Calling, User Rate Limiting, Usage Monitoring, Live Translation, Toxic Message Filtering, and much more.
## What do I need to do to use talkd.ai/dialog with Open WebUI?
To use both, you just need to clone talkd.ai/dialog repository from GitHub using the command below:
```
git clone https://github.com/talkdai/dialog.git
```
And run
```
docker-compose -f docker-compose-open-webui.yml
```
This will build the docker and will enable you to access your `localhost:3000` server of Open WebUI with talkd.ai already setup.
If everything went fine, you will be able to sign up locally on Open WebUI and reach a page like the one below:

Hope you like this collab!
Hugs from me and the talkd.ai team! | vmesel |
1,900,520 | Unlock Your Business Potential with ClickWhite's Premium SEO Services | In today's fast-paced digital world, establishing a strong online presence is essential for any... | 0 | 2024-06-25T20:15:42 | https://dev.to/auditfirst_io/unlock-your-business-potential-with-clickwhites-premium-seo-services-25e1 | seo | In today's fast-paced digital world, establishing a strong online presence is essential for any business striving for success. If you're looking to elevate your brand and reach your target audience effectively, [ClickWhite's SEO services](https://clickwhite.com/services/local-seo) offer the perfect solution. With the cutting-edge strategies and expert team, they ensure your business stands out in the crowded online marketplace.
Why SEO is Crucial for Your Business
Search Engine Optimization (SEO) is the backbone of digital marketing. It involves optimizing your website to rank higher in search engine results pages (SERPs), thereby increasing your visibility and attracting more organic traffic. Here’s why investing in SEO is a game-changer:
Increased Website Traffic: Higher rankings on search engines lead to more clicks and visits to your website.
Better User Experience: [SEO practices](https://clickwhite.com/services/local-seo) improve the usability and functionality of your website.
Enhanced Credibility and Trust: Websites that rank high are often perceived as more trustworthy and credible by users.
Higher ROI: SEO offers one of the best returns on investment compared to other digital marketing strategies.
ClickWhite's Comprehensive SEO Services
At ClickWhite, they understand that each business is unique, and a one-size-fits-all approach doesn’t work. The SEO services are tailored to meet the specific needs of your business. Here’s what they offer:
Keyword Research and Analysis: They identify the most relevant and high-performing keywords for your business to ensure maximum visibility.
On-Page Optimization: Their team optimizes your website’s content, meta tags, images, and structure to make it more search-engine friendly.
Technical SEO: They address technical aspects like site speed, mobile-friendliness, and crawlability to enhance your website's performance.
Content Creation and Marketing: High-quality, engaging content is key to SEO success. They create and promote content that resonates with your audience.
Link Building: Our link-building strategies help improve your site's authority and ranking by acquiring high-quality backlinks.
Local SEO: For businesses targeting local markets, they optimize your online presence to attract local customers.
Analytics and Reporting: They provide detailed reports and insights into your [SEO performance](https://clickwhite.com/services/local-seo), helping you make informed decisions.
Partner with ClickWhite for Unmatched SEO Success
Choosing ClickWhite means partnering with a team dedicated to your success. Their SEO experts stay ahead of industry trends and algorithm updates to ensure your business always has a competitive edge. They believe in transparent communication, providing regular updates and clear reports on your [SEO progress.](https://clickwhite.com/services/local-seo)
Ready to transform your online presence and drive more traffic to your website? Visit [ClickWhite SEO Services](https://clickwhite.com/services/local-seo) to learn more and get started on your journey to SEO success. | auditfirst_io |
1,900,519 | Recommendations | Hello guys, I need a platform where I can learn JavaScript from the beginner level. Any... | 0 | 2024-06-25T20:14:30 | https://dev.to/anthony_edet/recommendations-56md | Hello guys, I need a platform where I can learn JavaScript from the beginner level. Any recommendations! | anthony_edet | |
1,900,518 | Elevate Your Blockchain Project with Solana Development Services in Dubai, UAE | Dubai, UAE, is rapidly emerging as a global hub for blockchain innovation and technology. With its... | 0 | 2024-06-25T20:13:33 | https://dev.to/auditfirst_io/elevate-your-blockchain-project-with-solana-development-services-in-dubai-uae-lfd | blockchain, smartcontract |
Dubai, UAE, is rapidly emerging as a global hub for [blockchain innovation and technology.](https://auditfirst.io/) With its progressive regulatory environment and forward-thinking vision, Dubai is the ideal place to leverage cutting-edge blockchain solutions. Among these, Solana stands out for its unparalleled speed, scalability, and low transaction costs. Partnering with expert Solana development services in Dubai can propel your project to new heights.
Why Solana is the Ideal [Blockchain Platform for Dubai](https://auditfirst.io/)
Solana's advanced technology makes it an excellent choice for businesses in Dubai looking to harness the power of blockchain. Here’s why Solana is the perfect fit for Dubai’s dynamic market:
High Throughput: Solana can process up to 65,000 transactions per second (TPS), making it one of the fastest blockchain platforms, ideal for high-traffic applications.
Cost-Efficiency: With transaction fees averaging just $0.00025, Solana offers a cost-effective solution for businesses looking to scale without incurring high costs.
Scalability: Solana’s architecture supports massive scalability, ensuring that your blockchain solutions can grow alongside your business.
Robust Ecosystem: Solana’s ecosystem is rich with tools, libraries, and a supportive community, making development and deployment efficient and effective.
Benefits of Partnering with Solana Development Services in Dubai
Utilizing professional Solana development services in Dubai offers numerous advantages. Here’s how expert developers can drive your blockchain project’s success:
Custom Solutions: [Tailored blockchain solutions](https://auditfirst.io/) to meet the unique needs of your business, whether in finance, real estate, healthcare, or other industries.
Expertise and Experience: Access to seasoned developers with deep knowledge of Solana and blockchain technology, ensuring high-quality and efficient development.
End-to-End Services: Comprehensive services that include everything from initial consultation and project planning to deployment and ongoing maintenance.
Security and Compliance: Implementation of best practices for security and regulatory compliance, safeguarding your project and ensuring it meets all local and international standards.
Key Solana Development Services Offered in Dubai
Professional Solana development services in Dubai encompass a wide range of offerings to support your project at every stage:
Smart Contract Development: Creation and deployment of secure, efficient smart contracts to automate processes and transactions on the Solana blockchain.
DApp Development: Design and development of decentralized applications that leverage Solana’s speed and scalability to deliver exceptional user experiences.
Token Development: Creation of custom tokens for various use cases, including utility tokens, security tokens, and non-fungible tokens (NFTs).
Integration Services: Seamless integration of [Solana blockchain with your existing systems](https://auditfirst.io/) and platforms, enhancing functionality and interoperability.
Consulting and Advisory: Expert guidance on blockchain strategy, project feasibility, and best practices to ensure your project’s success.
Why Dubai is the Perfect Environment for Blockchain Innovation
Dubai’s commitment to becoming a leading blockchain hub is evident through its supportive regulatory framework and investment in technology infrastructure. Here’s why Dubai is ideal for blockchain projects:
Pro-Business Environment: Dubai’s government actively supports technological innovation and provides incentives for businesses to adopt blockchain solutions.
Strategic Location: Positioned at the crossroads of Europe, Asia, and Africa, Dubai offers unparalleled access to international markets.
World-Class Infrastructure: Dubai boasts state-of-the-art infrastructure, making it an ideal location for deploying and scaling blockchain solutions.
Conclusion
Leveraging Solana for your [blockchain development](https://auditfirst.io/) needs in Dubai can position your project at the forefront of innovation. By partnering with expert Solana development services, you can take full advantage of the platform’s capabilities to build scalable, secure, and high-performance blockchain solutions. Dubai’s favorable business environment, strategic location, and commitment to technology make it the perfect place to launch and grow your blockchain projects. | auditfirst_io |
1,900,517 | A Step-by-Step Guide to Choosing the Right Blockchain Development Service for Startups in Dubai | Blockchain technology is revolutionizing industries worldwide, and Dubai is no exception. As a... | 0 | 2024-06-25T20:11:36 | https://dev.to/auditfirst_io/a-step-by-step-guide-to-choosing-the-right-blockchain-development-service-for-startups-in-dubai-2bpk | blockchain, smartcontract | Blockchain technology is revolutionizing industries worldwide, and Dubai is no exception. As a startup in Dubai, choosing the right [blockchain development service](https://auditfirst.io/) can set the foundation for your success. This comprehensive guide will walk you through the essential steps to select the perfect blockchain development service tailored to your startup's needs.
Understanding Blockchain Technology
Before diving into the selection process, it's crucial to understand what blockchain technology entails. Blockchain is a decentralized digital ledger that records transactions across multiple computers securely and transparently. This technology ensures data integrity, enhances security, and reduces operational costs.
Step 1: Identify Your Business Needs
The first step in choosing the right blockchain development service is to identify your specific business needs. Determine the problems you want to solve with [blockchain technology](https://auditfirst.io/) and the goals you aim to achieve. Are you looking to streamline operations, enhance security, or create a new blockchain-based product? Clear objectives will guide you in selecting a service provider with the right expertise.
Step 2: Research Potential Providers
Once you've identified your needs, start researching potential blockchain development services in Dubai. Look for companies with a proven track record, robust portfolios, and positive client reviews. Key factors to consider include:
Experience and Expertise: Choose providers with extensive experience in [blockchain development](https://auditfirst.io/) and a deep understanding of various blockchain platforms like Ethereum (EVM), Solana, TON and Hyperledger.
Technical Proficiency: Ensure the provider has expertise in the specific technologies and tools required for your project.
Industry Knowledge: Providers with experience in your industry will better understand your unique challenges and requirements.
Step 3: Evaluate Their Portfolio and Case Studies
A reputable blockchain development company will have a portfolio showcasing their previous projects. Review their case studies to gauge their capability in delivering successful blockchain solutions. Pay attention to the complexity of the projects, the industries they have worked in, and the results achieved. This will give you insight into their problem-solving skills and innovation.
Step 4: Assess Their Team and Resources
The success of your blockchain project largely depends on the team working on it. Assess the expertise and qualifications of the development team. Look for certifications, relevant experience, and a collaborative approach. Additionally, consider the resources available to the provider, including access to cutting-edge technology and tools.
Step 5: Consider Their Development Process
Understanding the provider's development process is crucial to ensure it aligns with your project's requirements. A well-defined process typically includes:
Requirement Analysis: In-depth understanding of your business needs and objectives.
Design and Prototyping: Creating design mockups and prototypes for approval.
Development: Building the blockchain solution with regular progress updates.
Testing: Rigorous testing to identify and fix any issues.
Deployment and Maintenance: Launching the solution and providing ongoing support and maintenance.
Step 6: Check Their Security Measures
[Security is paramount in blockchain development.](https://auditfirst.io/) Ensure the provider follows best practices for security and compliance. They should have robust protocols to safeguard your data and prevent unauthorized access. Additionally, inquire about their approach to handling security breaches and their disaster recovery plans.
Step 7: Evaluate Their Pricing Model
Cost is a significant factor for startups. Evaluate the pricing models of different blockchain development services and choose one that offers the best value for your budget. Transparent pricing with no hidden costs is essential. Some providers offer flexible payment plans, which can be beneficial for startups with limited resources.
Step 8: Read Client Testimonials and Reviews
Client testimonials and reviews provide valuable insights into the provider's reliability and quality of service. Look for feedback on their communication, project management, and ability to meet deadlines. Positive testimonials from satisfied clients indicate a trustworthy provider.
Step 9: Request a Proposal
Once you've narrowed down your options, request detailed proposals from the shortlisted providers. The proposal should include:
Project Scope: Detailed description of the project, including deliverables and timelines.
Technical Approach: Explanation of the technologies and tools to be used.
Cost Breakdown: Comprehensive breakdown of costs involved.
Team Structure: Information about the team members and their roles.
Terms and Conditions: Contract terms, including warranties and support.
Conclusion
Choosing the right blockchain development service is a critical decision for your startup's success in Dubai. By following these steps, you can find a provider that aligns with your business needs, has a proven track record, and offers the expertise required to bring your blockchain project to life. Dubai's dynamic ecosystem and supportive regulatory environment make it the perfect place to harness the power of blockchain technology and drive innovation.
Blockchain Development Service FAQs
Q: What is blockchain technology?
A: Blockchain technology is a decentralized digital ledger that securely records transactions across multiple computers.
Q: Why is Dubai a hub for blockchain startups?
A: Dubai's supportive regulatory environment and thriving tech ecosystem make it an ideal place for blockchain startups.
Q: What should I look for in a blockchain development service?
A: Consider experience, technical proficiency, industry knowledge, and security measures when choosing a blockchain development service.
Q: How important is the development team's expertise?
A: The team's expertise is crucial for the success of your project, as it directly impacts the quality and innovation of the solution.
Q: What should a detailed proposal include?
A: A proposal should include the project scope, technical approach, cost breakdown, team structure, and terms and conditions.
By carefully considering these factors, your startup can successfully navigate the selection process and leverage [blockchain technology](https://auditfirst.io/) to achieve its goals in Dubai. | auditfirst_io |
1,900,516 | 10 Tips for Building Secure and Scalable Web Applications | The world has changed a lot in the last decade, and one of the major differences is the rise of the... | 0 | 2024-06-25T20:09:55 | https://dev.to/kaiakalwert/10-tips-for-building-secure-and-scalable-web-applications-171l | <p>The world has changed a lot in the last decade, and one of the major differences is the rise of the internet and the development of web applications. As the internet has become more and more popular, the need for web applications has also increased. A web application is a program that is designed to run on a web browser, and it can be used to perform a variety of tasks.</p>
<p>Web applications are an important part of the modern internet, and they are used by millions of people every day. In fact, you probably use web applications without even realizing it. For example, if you have ever used an online email service like Gmail, you have used a web application.</p>
<p>The popularity of web applications has led to a boom in the
<a target="_blank" href="https://youteam.io/blog/web-development-outsourcing-a-comprehensive-guide/">
<span style="color:rgb(17, 85, 204);">web development industry</span>
</a>. Today, there are thousands of companies that specialize in building web applications, and there are millions of web developers around the world. If you are thinking about building a web application, there are a few things that you need to keep in mind.</p>
<h2>1. Use a Reliable Web Host</h2>
<p>Web hosting is a service that makes a website or application available on the internet. Web hosting companies provide the servers and other infrastructure needed to store and serve website files.</p>
<p>There are many
<a target="_blank" href="https://www.liquidweb.com/blog/types-of-web-hosting/">
<span style="color:rgb(17, 85, 204);">different types of web hosting</span>
</a>
available, and the type you choose will depend on your specific needs. For example, shared hosting is a good option for small websites, while cloud hosting is better for web applications that need to scale.</p>
<p>When
<a target="_blank" href="https://saucal.com/blog/ecommerce-hosting/">
<span style="color:rgb(17, 85, 204);">choosing a web host</span>
</a>, it’s important to consider factors like reliability, security, speed, and support. Look for a web hosting company that offers a range of hosting options from dedicated servers to
<a target="_blank" href="https://www.liquidweb.com/blog/vps-security/">
<span style="color:rgb(17, 85, 204);">VPS security</span>
</a>
and be sure to read reviews and compare prices.</p>
<h2>2. Choose the Right Software Stack</h2>
<p>A software stack is a collection of technologies that developers use to build a web application. The stack includes the operating system, web server, database, and programming language.</p>
<p>There are many different software stacks to choose from, and the right one for your application will depend on a number of factors, including the size and complexity of the
<a target="_blank" href="https://trackingtime.co/best-practices/project-management-by-trackingtime.html?utm_source=linkbuilding+&utm_medium=referral+&utm_campaign=best+time+tracking+apps+">
<span style="color:rgb(17, 85, 204);">project</span>
</a>, your team’s expertise, and your budget. Also the
<a target="_blank" href="https://solveit.dev/blog/how-much-does-it-cost-to-design-an-app">
<span style="color:rgb(17, 85, 204);">price to design an app</span>
</a>
can vary greatly depending on these factors.</p>
<p>For example, a small e-commerce site might use a LAMP stack (Linux, Apache, MySQL, PHP), while a large social media platform might use a MEAN stack (MongoDB, Express, Angular, Node.js). Also, if you need to use an online and accessible database you can use tools such as
<a target="_blank" href="https://www.retable.io/">
<span style="color:rgb(17, 85, 204);">Retable</span>
</a>
to manage your web application's database.</p>
<p>When choosing a software stack, it’s important to consider security and scalability. Make sure that all of the technologies in your stack are well-maintained and have a good track record when it comes to security. You should also consider how easy it will be to scale your application as it grows.</p>
<h2>3. Use a Content Delivery Network</h2>
<p>
<a target="_blank" href="https://www.ranktracker.com/seo/glossary/content-delivery-network">
<span style="color:rgb(17, 85, 204);">Content delivery networks (CDNs)</span>
</a>
are a great way to improve the performance of your web application. They work by caching your content on servers located in data centers around the world. When a user requests content from your website, the CDN will serve the content from the server that is closest to the user.</p>
<p>This helps to reduce the amount of time it takes to load your web application, which can lead to a better user experience. CDNs also help to reduce the load on your web servers, which can help to improve the scalability of your web application.</p>
<p>In addition to improving the performance and scalability of your web application, CDNs also provide a layer of security. They can help to protect your web application from distributed denial-of-service (DDoS) attacks by absorbing malicious traffic.</p>
<h2>4. Choose the Right Database</h2>
<p>The database you choose will have a significant impact on the security and scalability of your web application.</p>
<p>Your database options include SQL (relational) databases and NoSQL (non-relational) databases.</p>
<p>SQL databases are best used for applications that require multi-row transactions and complex queries. They are also a good choice for applications that require data integrity and consistency.</p>
<p>NoSQL databases are best used for applications that require high scalability and low latency. They are also a good choice for applications that require flexible data models and high availability.</p>
<p>When choosing a database, consider the specific needs of your application and evaluate the security and scalability features of each database option.</p>
<h2>5. Implement Caching</h2>
<p>Caching is a fantastic way to speed up your web application and reduce the load on your server. Caching is the process of saving the results of a request and then reusing those results the next time the same request is made.</p>
<p>There are many different types of caching, but some of the most common include page caching, object caching, and database caching.</p>
<p>By implementing caching in your web application, you can improve your app’s performance and scalability.</p>
<h2>6. Use a Secure Software Development Life Cycle (SDLC)</h2>
<p>A Secure
<a target="_blank" href="https://kruschecompany.com/what-is-a-software-development-life-cycle/">
<span style="color:rgb(17, 85, 204);">Software Development Life Cycle (SDLC)</span>
</a>
is a set of best practices that help developers build secure software from the ground up.</p>
<p>The SDLC process includes the following steps:</p>
<p>• Planning</p>
<p>• Design</p>
<p>• Implementation</p>
<p>• Testing</p>
<p>• Deployment</p>
<p>• Maintenance</p>
<p>Security is a key consideration at every stage of the process. This means identifying potential security risks, developing a plan to mitigate those risks, and testing the application for security vulnerabilities.</p>
<p>By following a secure SDLC, you can build security into your application from the very beginning, rather than trying to bolt it on after the fact.</p>
<h2>7. Secure Your Application and Database</h2>
<p>Security should be a top priority at every stage of web application development. Your development team should have a good understanding of
<a target="_blank" href="https://kruschecompany.com/it-security-what-is-it/">
<span style="color:rgb(17, 85, 204);">common security threats</span>
</a>
and how to protect your application from them.</p>
<p>A few key security best practices to follow include:</p>
<p>• Using HTTPS to encrypt data in transit</p>
<p>• Validating and escaping user input to protect against SQL injection and cross-site scripting (XSS) attacks</p>
<p>• Using multi-factor authentication (MFA) to protect user accounts</p>
<p>• Regularly scanning your code and dependencies for vulnerabilities</p>
<p>• Keeping your software and systems up to date</p>
<p>• Limiting access to your database and using strong, unique passwords</p>
<p>In addition to securing your application, you’ll also need to secure your database. This includes encrypting sensitive data at rest, using strong access controls, and monitoring your database for unusual activity.</p>
<h2>8. Monitor Your Application and Server</h2>
<p>Monitoring your web application and server is crucial for security and scalability. Monitoring allows you to keep an eye on things like traffic, server load, and errors. This can help you identify any issues before they become serious problems.</p>
<p>
<a target="_blank" href="https://www.ecommercemarketingpodcast.com/best-wix-affiliate-apps/">
<span style="color:rgb(17, 85, 204);">There are many tools available</span>
</a>
that can help you monitor your web application and server. Some of the most popular include New Relic, Datadog, and SolarWinds. These tools can provide you with real-time data about your application and server, so you can quickly identify and address any issues.</p>
<p>In addition to using monitoring tools, you should also set up alerts so that you are notified if anything unusual happens. This can help you take action quickly and prevent any problems from getting out of hand.</p>
<h2>9. Use a Web Application Firewall</h2>
<p>Web application firewalls (WAFs) are an essential part of any web application security strategy. WAFs help to protect your web applications from a wide range of attacks, including SQL injection, cross-site scripting, and other common web application vulnerabilities.</p>
<p>A WAF is essentially a filter that sits between your web application and the traffic coming to and from it, and it blocks malicious requests before they can reach your web application. This helps to protect your web application from attacks and vulnerabilities without having to make changes to the application itself.</p>
<p>There are many different WAFs available, and it’s important to choose the right one for your web application. Look for a WAF that offers a wide range of security features, is easy to deploy and manage, and is designed to scale with your web application.</p>
<h2>10. Test Your Application Regularly</h2>
<p>Even after your web application is live, you should continue testing for performance and security.</p>
<p>Regular testing helps you identify and fix vulnerabilities before they’re exploited and ensure your application can handle increased traffic and data.</p>
<p>Automated testing tools can help you run tests more frequently and catch issues early.</p>
<h2>Conclusion</h2>
<p>So, there you have it. These are the 10 tips for building secure and scalable web applications. We hope that these tips help you build applications that are in line with the best practices for web application development.</p> | kaiakalwert | |
1,900,515 | Blockchain Development for Fintech: Opportunities and Challenges | The financial technology (fintech) sector is undergoing a significant transformation, largely driven... | 0 | 2024-06-25T20:09:52 | https://dev.to/auditfirst_io/blockchain-development-for-fintech-opportunities-and-challenges-jkm | blockchain, smartcontract | The financial technology (fintech) sector is undergoing a significant transformation, largely driven by the integration of blockchain technology. This powerful technology, best known for its role in powering cryptocurrencies like Bitcoin and Ethereum, is now being leveraged to revolutionize traditional financial systems. In this article, we will explore the opportunities and challenges that blockchain development presents for the fintech industry, focusing on smart contracts audit, DApp development, [smart contracts development](https://auditfirst.io/), and the role of DApp development companies.
Opportunities in Blockchain for Fintech
1. Enhanced Security and Transparency
Blockchain technology offers unparalleled security features due to its decentralized and immutable nature. Each transaction is recorded on a block and linked to the previous one, creating a chain of records that is highly resistant to tampering. This transparency and security are crucial for fintech applications, ensuring that financial transactions are conducted safely and transparently.
2. Reduced Costs and Increased Efficiency
By eliminating the need for intermediaries, blockchain technology can significantly reduce transaction costs. Traditional financial systems often rely on multiple intermediaries to process transactions, each adding their fees. Blockchain's peer-to-peer network can streamline these processes, leading to faster and cheaper transactions.
3. Improved Access to Financial Services
Blockchain can democratize access to financial services, especially in underserved regions. With blockchain, individuals and businesses can access a wide range of financial services without relying on traditional banking infrastructure. This can lead to greater financial inclusion and the empowerment of marginalized communities.
4. Smart Contracts Development and Audit
Smart contracts are self-executing contracts with the terms directly written into code. They automatically execute transactions when predefined conditions are met, reducing the need for manual intervention and minimizing the risk of human error. [Smart contracts development and smart contracts audit](https://auditfirst.io/) are crucial to ensure the reliability and security of these automated agreements, enhancing the efficiency of various financial processes, from loan disbursements to insurance claims.
5. Innovation in Payment Systems through DApp Development
Blockchain technology is paving the way for new and innovative payment systems. Cryptocurrencies and stablecoins offer an alternative to traditional currencies, providing faster and more secure payment options. DApp development is crucial for creating decentralized applications that can facilitate these transactions. A DApp development company can provide the expertise needed to build robust and efficient decentralized applications, addressing the long-standing challenges of international payments.
Challenges in Blockchain for Fintech
1. Regulatory Uncertainty
One of the significant challenges facing blockchain development in fintech is regulatory uncertainty. Governments and regulatory bodies worldwide are still grappling with how to manage and oversee blockchain-based activities. The lack of clear regulations can create obstacles for fintech companies looking to innovate and expand using blockchain technology.
2. Scalability Issues
While blockchain offers numerous benefits, scalability remains a critical concern. The current blockchain infrastructure can struggle to handle large volumes of transactions, leading to slower processing times and higher costs. Developing scalable solutions that can support widespread adoption is a crucial challenge for the industry.
3. Integration with Legacy Systems
Many financial institutions still rely on legacy systems that are not designed to work with blockchain technology. Integrating blockchain with these outdated systems can be complex and costly, posing a significant barrier to widespread adoption. Fintech companies must find ways to bridge this gap and ensure seamless integration.
4. Security Vulnerabilities
While blockchain is inherently secure, it is not immune to attacks. Cybersecurity threats, such as hacking and phishing, remain a concern. Moreover, vulnerabilities in [smart contract code](https://auditfirst.io/) can be exploited, leading to financial losses. Conducting regular smart contracts audits and ensuring robust security measures are essential to mitigate these risks.
5. Energy Consumption
Blockchain, particularly proof-of-work (PoW) based systems like Bitcoin, consumes a significant amount of energy. This high energy consumption has raised environmental concerns and calls for more sustainable blockchain solutions. Developing energy-efficient consensus mechanisms, such as proof-of-stake (PoS), is crucial for the technology's future.
Conclusion
Blockchain technology holds immense potential for the fintech industry, offering opportunities to enhance security, reduce costs, and improve access to financial services. However, it also presents challenges, including regulatory uncertainty, scalability issues, and integration with legacy systems. As the technology continues to evolve, addressing these challenges will be critical to unlocking the full potential of blockchain in fintech.
For fintech companies, embracing blockchain technology can lead to innovation and growth, but it requires careful navigation of the associated challenges. By staying informed and adaptable, the fintech industry can harness the power of blockchain to create a more efficient, inclusive, and secure financial future.
By understanding the opportunities and challenges of blockchain in fintech, businesses can strategically position themselves to capitalize on this transformative technology. Whether it's through enhanced security, innovative payment systems, or [smart contracts development](https://auditfirst.io/) and audit, blockchain has the potential to reshape the financial landscape and drive the fintech industry forward.
| auditfirst_io |
1,887,877 | Interfaces con privacidad en Solidity y zk-WASM | Los usuarios de blockchain necesitan privacidad en sus finanzas, identidad, redes sociales y más.... | 0 | 2024-06-25T20:08:14 | https://dev.to/turupawn/interfaces-con-privacidad-en-solidity-y-zk-wasm-1amg | ---
title: Interfaces con privacidad en Solidity y zk-WASM
published: true
description:
tags:
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-06-14 03:08 +0000
---
Los usuarios de blockchain necesitan privacidad en sus finanzas, identidad, redes sociales y más. Pero web3 es transparente y público. Entonces, ¿cómo pueden los usuarios proteger su anonimato en un ambiente con estas características?
La clave es crear pruebas de computación en un lugar donde únicamente el usuario tiene acceso, donde los datos del usuario estén seguros. Ese lugar es precisamente el navegador, antes que los datos del usuarios toquen el internet. A esto le llamamos generación de pruebas a nivel de cliente, "client side proving", o "browser proving" en inglés.

<p><small><em>Para mantener los parámetros privados, estos nunca deben salir de nuestro navegador</em></small></p>
Conozcamos, con un ejemplo práctico y sencillo, cómo crear interfaces que hagan uso de zk-wasm, la tecnología que hace esto posible.
## Dependencias
Para este ejemplo usaremos circom, si no lo tienes instalado puedes hacerlo con los comandos a continuación.
```bash
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
git clone https://github.com/iden3/circom.git
cd circom
cargo build --release
cargo install --path circom
npm install -g snarkjs
```
## 1. Crea un circuito
Haremos un ejemplo muy sencillo: generar una prueba de computación de una multiplicación `a*b=c` pero manteniendo privados `a` y `b`. Si te interesa un ejemplo más avanzado con un caso de uso real visita [mi artículo anterior](https://dev.to/turupawn/smart-contracts-privados-con-solidity-y-circom-3a8h).
Circom nos permite crear circuitos, que permiten generar pruebas de ejecución ofuscando los parámetros.
Comienza creando el circuito a continuación.
`myCircuit.circom`
```js
pragma circom 2.0.0;
template Multiplier() {
signal input a;
signal input b;
signal output c;
c <== a*b;
}
component main = Multiplier();
```
Ahora compílalo y genera los artefactos que usaremos más adelante.
```bash
circom myCircuit.circom --r1cs --wasm --sym
snarkjs powersoftau new bn128 12 pot12_0000.ptau -v
snarkjs powersoftau contribute pot12_0000.ptau pot12_0001.ptau --name="First contribution" -v
snarkjs powersoftau prepare phase2 pot12_0001.ptau pot12_final.ptau -v
snarkjs groth16 setup myCircuit.r1cs pot12_final.ptau myCircuit_0000.zkey
snarkjs zkey contribute myCircuit_0000.zkey myCircuit_0001.zkey --name="1st Contributor Name" -v
snarkjs zkey export verificationkey myCircuit_0001.zkey verification_key.json
```
## 2. Lanza los contratos
El siguiente comando generará un contrato verificador en el archivo de `verifier.sol`. Lánzalo en un blockchain de preferencia. Este contrato contiene la función `verifyProof()` que recibe por parámetro una prueba de computación hecha con nuestro circuito y devuelve `true` si la prueba es correcta.
Nota: Este contrato es compatible con L1 EVMs, L2 optimistas, pero en términos de L2 ZK, actualmente únicamente es compatible con Scroll.
```bash
snarkjs zkey export solidityverifier myCircuit_0001.zkey verifier.sol
```
Ahora lanza el siguiente contrato de _lógica personalizada_ pasando como parámetro de constructor el address del contrato verificador que lanzamos anteriormente. En este contrato puedes agregar la lógica en solidity que desees, por ejemplo el conteo de votos de un sistema de votación o la recepción o envío de tokens ERC20 en un sistema DeFi anónimo. En este ejemplo únicamente almacenaremos el resultado de la multiplicación que hicimos en nuestro circuito.
```javascript
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
interface ICircomVerifier {
function verifyProof(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[1] calldata _pubSignals) external view returns (bool);
}
contract CircomCustomLogic {
ICircomVerifier circomVerifier;
uint public publicInput;
constructor(address circomVeriferAddress) {
circomVerifier = ICircomVerifier(circomVeriferAddress);
}
function sendProof(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[1] calldata _pubSignals) public {
// ZK verification
circomVerifier.verifyProof(_pA, _pB, _pC, _pubSignals);
// Your custom logic
publicInput = _pubSignals[0];
}
}
```
## 3. Construye un frontend
Ahora crea la siguiente estructura de archivos:
```
js/
blockchain_stuff.js
snarkjs.min.js
json_abi/
MyContract.json
zk_artifacts/
myCircuit_final.zkey
myCircuit.wasm
verification_key.json
index.html
```
* `js/snarkjs.min.js`: descarga [este archivo](https://github.com/iden3/snarkjs/releases/tag/v0.7.4) que contiene la librería de snark.js
* `json_abi/MyContract.json`: el ABI del contrato `CircomCustomLogic` que recién lanzamos, por ejemplo en Remix, lo puedes hacer dando clic en el botón "ABI" en la pestaña de compilación.
* `zk_artifacts`: coloca en esta carpeta los artefactos generados anteriormente. Nota: Cambia el nombre de `myCircuit_0002.zkey` por `myCircuit_final.zkey`
* `index.html` y `js/blockchain_stuff.js` los detallo a continuación
El archivo HTML a continuación describe la interfaz gráfica donde colocaremos los números a multiplicar. En un ambiente de producción recomendaría usar un frontend framework como react, vue o angular. Este ejemplo es con fines didácticos.
`index.html`
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<input id="connect_button" type="button" value="Connect" onclick="connectWallet()" style="display: none"></input>
<p id="account_address" style="display: none"></p>
<p id="web3_message"></p>
<p id="contract_state"></p>
<input type="input" value="" id="a"></input>
<input type="input" value="" id="b"></input>
<input type="button" value="Send Proof" onclick="_sendProof()"></input>
<br>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.3.5/web3.min.js"></script>
<script type="text/javascript" src="js/blockchain_stuff.js"></script>
<script type="text/javascript" src="js/snarkjs.min.js"></script>
</body>
</html>
<script>
function _sendProof()
{
a = document.getElementById("a").value
b = document.getElementById("b").value
sendProof(a, b)
}
</script>
```
Nuestro archivo de javascript contiene tanto la lógica de generación de pruebas zk usando la librería snark.js como la lógica de blockchain usando la librería web3.js. En un ambiente de producción recomendaría usar typescript y no javascript vainilla, este ejemplo es con fines didácticos.
`js/blockchain_stuff.js`
```js
const NETWORK_ID = 534351
const MY_CONTRACT_ADDRESS = "0xFdAFc996a60bC5fEB307AAF81b1eD0A34a954F06"
const MY_CONTRACT_ABI_PATH = "./json_abi/MyContract.json"
var my_contract
var accounts
var web3
function metamaskReloadCallback() {
window.ethereum.on('accountsChanged', (accounts) => {
document.getElementById("web3_message").textContent="Se cambió el account, refrescando...";
window.location.reload()
})
window.ethereum.on('networkChanged', (accounts) => {
document.getElementById("web3_message").textContent="Se el network, refrescando...";
window.location.reload()
})
}
const getWeb3 = async () => {
return new Promise((resolve, reject) => {
if(document.readyState=="complete")
{
if (window.ethereum) {
const web3 = new Web3(window.ethereum)
window.location.reload()
resolve(web3)
} else {
reject("must install MetaMask")
document.getElementById("web3_message").textContent="Error: Porfavor conéctate a Metamask";
}
}else
{
window.addEventListener("load", async () => {
if (window.ethereum) {
const web3 = new Web3(window.ethereum)
resolve(web3)
} else {
reject("must install MetaMask")
document.getElementById("web3_message").textContent="Error: Please install Metamask";
}
});
}
});
};
const getContract = async (web3, address, abi_path) => {
const response = await fetch(abi_path);
const data = await response.json();
const netId = await web3.eth.net.getId();
contract = new web3.eth.Contract(
data,
address
);
return contract
}
async function loadDapp() {
metamaskReloadCallback()
document.getElementById("web3_message").textContent="Please connect to Metamask"
var awaitWeb3 = async function () {
web3 = await getWeb3()
web3.eth.net.getId((err, netId) => {
if (netId == NETWORK_ID) {
var awaitContract = async function () {
my_contract = await getContract(web3, MY_CONTRACT_ADDRESS, MY_CONTRACT_ABI_PATH)
document.getElementById("web3_message").textContent="You are connected to Metamask"
onContractInitCallback()
web3.eth.getAccounts(function(err, _accounts){
accounts = _accounts
if (err != null)
{
console.error("An error occurred: "+err)
} else if (accounts.length > 0)
{
onWalletConnectedCallback()
document.getElementById("account_address").style.display = "block"
} else
{
document.getElementById("connect_button").style.display = "block"
}
});
};
awaitContract();
} else {
document.getElementById("web3_message").textContent="Please connect to Scroll Testnet";
}
});
};
awaitWeb3();
}
async function connectWallet() {
await window.ethereum.request({ method: "eth_requestAccounts" })
accounts = await web3.eth.getAccounts()
onWalletConnectedCallback()
}
loadDapp()
const onContractInitCallback = async () => {
var publicInput = await my_contract.methods.publicInput().call()
var contract_state = "Public input: " + publicInput
document.getElementById("contract_state").textContent = contract_state;
}
const onWalletConnectedCallback = async () => {
}
//// Functions ////
const sendProof = async (a, b) => {
document.getElementById("web3_message").textContent="Generating proof...";
const { proof, publicSignals } = await snarkjs.groth16.fullProve( { a: a, b: b}, "../zk_artifacts/myCircuit.wasm", "../zk_artifacts/myCircuit_final.zkey");
const vkey = await fetch("../zk_artifacts/verification_key.json").then( function(res) {
return res.json();
});
const res = await snarkjs.groth16.verify(vkey, publicSignals, proof);
pA = proof.pi_a
pA.pop()
pB = proof.pi_b
pB.pop()
pC = proof.pi_c
pC.pop()
document.getElementById("web3_message").textContent="Proof generated please confirm transaction.";
const result = await my_contract.methods.sendProof(pA, pB, pC, publicSignals)
.send({ from: accounts[0], gas: 0, value: 0 })
.on('transactionHash', function(hash){
document.getElementById("web3_message").textContent="Executing...";
})
.on('receipt', function(receipt){
document.getElementById("web3_message").textContent="Success."; })
.catch((revertReason) => {
console.log("ERROR! Transaction reverted: " + revertReason.receipt.transactionHash)
});
}
```
## 4. Prueba la aplicación
Antes de probar, debes adaptar las variables `NETWORK_ID` y `MY_CONTRACT_ADDRESS` en `js/blockchain_stuff.js`. `NETWORK_ID` es el identificador único de la chain que estés usando, en este ejemplo estoy usando `534351` que representa a Scroll Sepolia Testnet, si deseas usar otro te recomiendo buscar el identificador en [chainlist](https://chainlist.org/). Por otro coloca el address del contrato `CircomCustomLogic` que recién lanzaste en la variable `MY_CONTRACT_ADDRESS`.
Ahora estás listo para probar la aplicación en cualquier servidor web. Usualmente yo uso `lite-server` para desarrollar, así lo instalas y levantas un servidor, solo asegúrate de estar en la carpeta del proyecto:
```bash
npm install -g lite-server #para instalar
lite-server #para levantar el servidor
```

<html><small><em>Una vez todo esté listo, tu aplicación debería de verse de esta manera</em></small></html>
## ¿Qué más necesito aprender para desarrollar una zkDapp?
Para desarrollar una aplicación descentralizada y anónima necesitarás una combinación de conocimientos en Circom, Solidity y programación web. Dependiendo de los casos de uso también ocuparás un poco de programación backend en el caso de necesitar un Relayer. Estaré creando guías sobre estos temas así que te invito a que te suscribas.
También te dejo un par de materiales de aprendizaje como siguiente paso:
* [Documentación oficial de circom](https://docs.circom.io/)
* [Solidity en 15 minutos](https://dev.to/turupawn/como-lanzar-un-dex-paso-a-pasox-2cnm)
* [Playlist de introducción a desarrollo en ZK](https://www.youtube.com/watch?v=gLXlIuEafo4&list=PLhTCvqIxiz5yj1ysnVo4jlYzS2BoF7NPI)
**¡Gracias por leer esta guía!**
Sígueme en dev.to y en [Youtube](https://www.youtube.com/channel/UCNRB4tgwp09z4391JRjEsRA) para todo lo relacionado al desarrollo en Blockchain en Español. | turupawn | |
1,900,513 | How to Find the Best Solidity Smart Contracts Audit Company | When searching for a Solidity smart contract audit company, focusing on key considerations can help... | 0 | 2024-06-25T20:08:10 | https://dev.to/auditfirst_io/how-to-find-the-best-solidity-smart-contracts-audit-company-53cp | blockchain, smartcontract | When searching for a Solidity smart contract audit company, focusing on key considerations can help you make the best choice. Here are some critical aspects to keep in mind:
1. Security Expertise
Ensure the company has a team of seasoned security experts with a strong background in blockchain technology and [smart contracts](https://auditfirst.io/). Look for auditors who have contributed to reputable security forums, published research papers, or have been involved in significant blockchain projects.
2. Customized Audit Services
Each smart contract is unique, and so should be the audit approach. Opt for companies that offer customized audit services tailored to your specific contract needs. They should be able to adapt their methodology based on the complexity and purpose of your [smart contract.](https://auditfirst.io/)
3. Use of Advanced Tools
The audit company should employ advanced tools and technologies to identify vulnerabilities. Automated tools can catch a wide range of issues, but they should be complemented by manual review by experienced auditors to catch subtle and complex bugs.
4. Post-Audit Support
A good audit company doesn’t just stop at identifying issues; they provide post-audit support to help you understand the findings and implement the necessary fixes. Look for companies that offer re-audit services after you’ve made changes to ensure all vulnerabilities are addressed.
5. Industry Recognition and Standards
Choose a company that adheres to industry standards and is recognized by leading blockchain organizations. Certifications from recognized bodies can add an extra layer of credibility to the audit firm.
6. Client Portfolio and Case Studies
Review the company’s client portfolio and case studies to see the types of projects they have handled. This can give you an idea of their experience and capability in dealing with projects similar to yours.
Clear and Detailed Reporting
The audit report should be clear, detailed, and easy to understand. It should include a summary of findings, detailed descriptions of vulnerabilities, risk assessments, and actionable recommendations for mitigation.
8. Confidentiality and Integrity
Ensure the audit company has strict confidentiality policies in place to protect your project’s details. The integrity of the audit process and the security of your information should be a top priority.
Conclusion
Choosing the right [Solidity smart contract audit](https://auditfirst.io/) company involves careful consideration of several factors, from expertise and customized services to post-audit support and industry recognition. By focusing on these aspects, you can find a reliable partner to ensure the security and efficiency of your smart contracts. Taking the time to research and select a reputable audit company is a crucial investment in the success and security of your blockchain projects. | auditfirst_io |
1,900,512 | Smart Contracts in Business: Use Cases | In the dynamic world of business, smart contracts are revolutionizing how transactions are conducted.... | 0 | 2024-06-25T20:06:54 | https://dev.to/auditfirst_io/smart-contracts-in-business-use-cases-38np | blockchain, smartcontract | In the dynamic world of business, smart contracts are revolutionizing how transactions are conducted. These self-executing contracts with the terms of the agreement directly written into code are transforming various industries by enhancing efficiency, transparency, and security. This article delves into the use cases of [smart contracts in business](https://auditfirst.io/), highlighting their potential to streamline operations and drive innovation.
What Are Smart Contracts?
Smart contracts are digital agreements that automatically execute and enforce themselves when predefined conditions are met. They are built on blockchain technology, ensuring immutability and transparency. Unlike traditional contracts, smart contracts eliminate the need for intermediaries, reducing costs and the risk of fraud.
Key Use Cases of Smart Contracts in Business
1. Supply Chain Management
Smart contracts can significantly improve supply chain management by automating processes and providing real-time visibility. They ensure that payments are released only when goods are delivered, reducing delays and disputes. Companies like IBM and Maersk are already leveraging blockchain-based smart contracts to streamline their supply chains.
2. Insurance
The insurance industry is poised for transformation with [smart contracts](https://auditfirst.io/). They can automate claims processing, ensuring that payouts are made promptly when certain conditions are met. This reduces administrative costs and enhances customer satisfaction. For instance, flight delay insurance can automatically compensate travelers if a delay exceeds a predefined threshold.
3. Real Estate
In real estate, smart contracts can simplify property transactions by automating the transfer of ownership and funds. They reduce the need for intermediaries like real estate agents and lawyers, making the process faster and more cost-effective. Platforms like Propy are already using smart contracts to facilitate real estate deals.
4. Financial Services
The financial sector stands to gain immensely from smart contracts. They can automate complex processes such as loan disbursements, trade settlements, and compliance checks. Smart contracts enhance the efficiency of financial operations while reducing the risk of human error and fraud.
5. Healthcare
In healthcare, smart contracts can improve data management and patient care. They enable secure sharing of medical records between authorized parties, ensuring data integrity and patient privacy. Additionally, they can automate billing and insurance claims, reducing administrative burdens on healthcare providers.
6. Legal Industry
The legal industry can benefit from smart contracts by automating routine tasks like document verification and contract management. [Smart contracts](https://auditfirst.io/) ensure that contractual obligations are met without the need for constant oversight, freeing up legal professionals to focus on more complex tasks.
7. Voting Systems
Smart contracts can enhance the integrity and transparency of voting systems. They ensure that votes are counted accurately and that the results are tamper-proof. This technology can be applied in both political elections and corporate governance to ensure fair and transparent processes.
Advantages of Smart Contracts
Transparency: All parties have visibility into the terms and execution of the contract, reducing the likelihood of disputes.
Security: Blockchain technology ensures that smart contracts are tamper-proof and secure from unauthorized access.
Efficiency: By automating processes, smart contracts reduce the time and costs associated with traditional contract execution.
Trust: The self-executing nature of smart contracts builds trust among parties, as the need for intermediaries is eliminated.
Challenges and Considerations
While smart contracts offer numerous benefits, there are challenges to consider. Legal recognition and enforceability can vary across jurisdictions, and coding errors can lead to unintended consequences. Businesses must ensure that smart contracts are thoroughly tested and reviewed by legal and technical experts before deployment.
Conclusion
[Smart contracts](https://auditfirst.io/) are set to revolutionize the business landscape by automating processes, enhancing transparency, and reducing costs. As more industries recognize the potential of this technology, its adoption is expected to grow, driving innovation and efficiency. By understanding and leveraging smart contracts, businesses can stay ahead of the curve and capitalize on the benefits of blockchain technology.
Embrace the future of business with [smart contracts](https://auditfirst.io/) and unlock new levels of efficiency and trust in your operations. | auditfirst_io |
1,900,502 | Join TemplateMonster Affiliate Program - Get up to 30% Commissions | Have a website and want to monetize its traffic? Want to promote your marketplace products? Join... | 0 | 2024-06-25T20:02:58 | https://dev.to/hasnaindev1/join-templatemonster-affiliate-program-get-up-to-30-commissions-2a0i | webdev, website, webpack, webcomponents | Have a website and want to monetize its traffic? Want to promote your marketplace products?
Join **TemplateMonster affiliate family** and convert your traffic into money.
Get up to 30% share from the sales your leads make; we will help you make it to the top!
**Sign Up URL**: https://rebrand.ly/templatemonsteraffiliate
**Why Become a TemplateMonster Affiliate?**
**TemplateMonster** has become a one-stop source of web design, development, and marketing products and services. People associate our brand name with the biggest collection of website templates, graphics, plugins, and other digital items. We are welcoming you to become a part of our affiliate community and grow together. Here is what we promise.
**How It Works?**
**TemplateMonster marketplace** provides beneficial terms and conditions for the affiliate partners. In addition to paying 30% for the initial client's purchase, we provide you with a set of free tools to help you with online promotion and marketing. The application process is easy; just follow these simple steps.
**1) Sign up for the program**
Create and verify a free account and get access to the affiliate admin panel.
**2) Share your unique referral URL**
Generate a referral URL with your affiliate ID and share it on your website, email, or social media.
**3) Check the statistics**
Track the traffic you send and see the related sales. The more leads you refer, the more profit you get.
**4) Earn commission**
Earn up to 30% commission for all new purchases, analyze your campaigns, and promote the highest-converting products.
**Sign Up URL**: https://rebrand.ly/templatemonsteraffiliate | hasnaindev1 |
1,900,509 | Atomic Agents - New opensource library to build AI agents atomically | Hello all, I am the creator of Atomic Agents, A new multi-agent open source framework inspired by... | 0 | 2024-06-25T20:02:50 | https://dev.to/kennyvaneetvelde/atomic-agents-new-opensource-library-to-build-ai-agents-atomically-27da | ai, python, agentic, github | Hello all, I am the creator of **Atomic Agents**, A new multi-agent open source framework inspired by Atomic Design principles.
https://github.com/KennyVaneetvelde/atomic_agents
A lot of existing frameworks and methodologies for Agentic AI are focused on building autonomous multi-agent systems that you basically wind up and let go. While these can be fun to demo, they’re not always practical for real-world applications. Real-life companies aren’t looking for a bot that writes articles in a different style each time, with a different structure and a different tone. They want a bot that can write articles in a consistent style, with a consistent structure and a consistent tone that aligns with their brand. Beside fine-tuning a model, which requires a lot of data and money, and isn’t even possible if you really want to use the latest GPT model, there’s no practical way to gain full control of the output of these frameworks.
In business, management rarely allocates budget just to create something that’s cool but has no value. They want to see a return on investment. They want to see real business issues being solved and automated and cut costs. To achieve this, you need modularity, you need to be able to control the output, make sure it’s not a black box, make the output reproducible, and make it reliable. This is where Atomic Agents come in.
Since this framework is new, I'd love some feedback, suggestions, and PRs! I have been using it a TON and it's way easier than langchain, crewAI, ...
Feel free to get in touch with me on LinkedIn for business inquiries https://www.linkedin.com/in/kennyvaneetvelde/ | kennyvaneetvelde |
1,900,508 | DOM Event Handling | What is an Event? An event is an action or occurrence that happens in the browser, such as... | 0 | 2024-06-25T20:00:29 | https://dev.to/__khojiakbar__/dom-event-handling-56p7 | dom, event, javascript | ## What is an Event?
An event is an action or occurrence that happens in the browser, such as a user clicking a button, a webpage loading, or a mouse hovering over a link. JavaScript allows you to "listen" for these events and execute code in response.
---
## Common Types of Events
1. **Mouse Events:** `click`, `dblclick`, `mouseover`, `mouseout`, `mousedown`, `mouseup`, `mousemove`
2. **Keyboard Events:** `keydown`, `keyup`, `keypress`
3. **Form Events:** `submit`, `change`, `focus`, `blur`
4. **Window Events:** `load`, `resize`, `scroll`
5. **Touch Events:(for mobile)** `touchstart`, `touchend`, `touchmove`,
---
## Event Listeners
To handle events, you need to set up event listeners. An event listener is a function that is called when an event occurs. There are several ways to add event listeners in JavaScript:
#### Using `addEventListener()`
The most recommended way to attach event listeners is by using the addEventListener() method. It allows you to add multiple events to the same element and provides better control over event handling.
```
document.getElementById('myButton').addEventListener('click', function() {
alert('Button was clicked!');
});
```
#### Inline Event Handlers
You can also add event handlers directly in the HTML using attributes like `onclick`, `onmouseover`, etc. However, this method is less flexible and not recommended for modern web development.
```
<button onclick="alert('Button was clicked!')">Click Me</button>
```
#### Using DOM Properties
Another way to add event handlers is by setting the event property of a DOM element. This method can only attach one event handler at a time.
```
document.getElementById('myButton').onclick = function() {
alert('Button was clicked!');
};
```
#### Event Object
When an event occurs, it generates an event object that contains useful information about the event. This object is automatically passed to the event handler function.
```
document.getElementById('myButton').addEventListener('click', function(event) {
console.log('Event type:', event.type);
console.log('Element:', event.target);
console.log('Mouse coordinates:', event.clientX, event.clientY);
});
```
---
#### Removing Event Listeners
You can remove an event listener using the removeEventListener() method.
```
function handleClick() {
alert('Button was clicked!');
}
document.getElementById('myButton').addEventListener('click', handleClick);
// Remove the event listener
document.getElementById('myButton').removeEventListener('click', handleClick);
```
--- | __khojiakbar__ |
1,900,507 | Best Practices for a Smart Contract Audit | Smart contracts are transforming the digital landscape by enabling automated, self-executing... | 0 | 2024-06-25T20:00:18 | https://dev.to/auditfirst_io/best-practices-for-a-smart-contract-audit-1kk6 | blockchain, smartcontract | Smart contracts are transforming the digital landscape by enabling automated, self-executing agreements without the need for intermediaries. These contracts operate on blockchain technology, which offers transparency, security, and efficiency. However, the code-based nature of smart contracts introduces a significant challenge: the potential for security vulnerabilities. [Given that smart contracts](https://auditfirst.io/smart-contracts/audit) often handle valuable assets and sensitive information, even minor flaws can lead to substantial financial losses and breaches of trust.
Conducting a smart contract audit is not merely a good practice; it is an essential step to ensure the integrity and security of blockchain projects. A thorough audit can uncover hidden vulnerabilities, prevent exploitation by malicious actors, and enhance the overall robustness of the contract. By understanding and implementing best practices for a smart contract audit, developers and businesses can safeguard their projects and maintain the trust of their users.
In the following sections, we will delve into the key aspects of preparing for an audit, the detailed auditing process, and the critical actions to take post-audit. This comprehensive guide aims to equip you with the knowledge and tools necessary to conduct effective smart contract audits, ultimately fortifying the security of your blockchain initiatives.
Understanding Smart Contract Audits
Smart contract audits are a critical component in ensuring the security and reliability of blockchain-based contracts. These audits involve a meticulous review of the smart contract code to identify potential vulnerabilities that could be exploited by malicious actors. The primary goal is to ensure that the contract performs its intended functions without any security breaches or unexpected behavior.
Key Aspects of Smart Contract Audits
Identification of Common Vulnerabilities: Audits focus on uncovering common issues such as reentrancy attacks, where a function can be re-entered before the previous execution is complete; integer overflow and underflow, which can cause erroneous calculations; and gas inefficiencies, which can lead to higher transaction costs and potential denial-of-service (DoS) attacks.
Code Review: Both automated tools and manual code reviews are used in the audit process. Automated tools can quickly scan for known vulnerabilities, while manual reviews allow auditors to understand the logic and flow of the contract, identifying complex issues that automated tools might miss.
Security Analysis: This involves a comprehensive analysis of the contract’s security features, including access controls, authentication mechanisms, and any cryptographic techniques used. Ensuring these components are correctly implemented is crucial for preventing unauthorized access and manipulation.
Performance Evaluation: Evaluating the performance of the [smart contract](https://auditfirst.io/smart-contracts/audit), especially in terms of gas consumption, is essential. Optimizing the code to be more gas-efficient not only saves costs but also improves the contract’s scalability and user experience.
Compliance and Standards: Ensuring that the smart contract complies with industry standards and best practices, such as those outlined by organizations like the Ethereum Foundation, is vital. Compliance helps in maintaining interoperability and enhancing the overall trustworthiness of the contract.
Preparing for a Smart Contract Audit
Code Cleanliness: Organize and comment on the code.
Documentation: Provide comprehensive documentation.
Testing: Conduct thorough tests.
Dependency Management: Ensure all dependencies are secure and up to date.
Design Review: Evaluate the contract design to identify potential flaws.
Auditing Process
Initial Review: Understand contract purpose.
Automated Scanning: Use tools to detect issues. A free tool is https://auditfirst.io/smart-contracts/automated-audit
Manual Review: Detailed examination of the code.
Issue Categorization: Severity-based categorization.
Report Generation: Detailed audit report.
Review Past Audits: Examine previous audits for recurrent issues.
Continuous Monitoring: Implement systems for ongoing contract monitoring post-deployment.
Best Practices in Detail
Modular Design: Break down contracts into smaller, manageable components.
Access Control: Implement strict access control measures.
Gas Optimization: Optimize for gas efficiency to prevent excessive costs.
Formal Verification: Use mathematical methods to prove contract correctness.
Bug Bounties: Engage the community in identifying potential vulnerabilities through bug bounty programs.
Post-Audit Actions
Implement Recommendations: Address and resolve identified issues.
Retesting: Conduct retesting to ensure all fixes are effective.
Continuous Security Practices: Maintain a proactive approach to security, including regular updates and monitoring.
Conclusion
[Smart contract audits](https://auditfirst.io/smart-contracts/audit) are crucial for blockchain project security, enhancing credibility and trust. By adhering to best practices, you ensure robust and reliable smart contracts, protecting your project and users.
Smart Contract Audit FAQ
Q: What is a smart contract audit?
A: A smart contract audit is a thorough examination of the code used to create smart contracts to identify and rectify potential vulnerabilities and security issues.
Q: Why are smart contract audits important?
A: They are essential to ensure the security and reliability of smart contracts, preventing exploits and safeguarding user assets.
Q: What tools are used in smart contract audits?
A: You can start with a free tool to identify security vulnerabilities in solidity code https://auditfirst.io/smart-contracts/automated-audit
Q: How often should smart contracts be audited?
A: Smart contracts should be audited before deployment and after significant updates or changes.
Q: What are common vulnerabilities found in smart contracts?
A: Common issues include reentrancy attacks, integer overflow/underflow, and gas inefficiencies.
Q: Can smart contract audits guarantee 100% security?
A: While audits significantly reduce risks, they cannot guarantee absolute security due to the complex and evolving nature of [blockchain technology.](https://auditfirst.io/smart-contracts/audit) | auditfirst_io |
1,900,506 | The Best Video Conferencing APIs and SDKs | Adding video conferencing capabilities to your app or website can enhance user engagement, but... | 0 | 2024-06-25T19:59:23 | https://dev.to/emilyrobertsatstream/the-best-video-conferencing-apis-and-sdks-2eac | videoconferencing, videoapi, videosdk | Adding video conferencing capabilities to your app or website can [enhance user engagement](https://getstream.io/blog/video-engagement/), but building these features from scratch is hard. Before integrating them into your platform, you must solve challenges like real-time audio and video processing, security, and complex UI.
Thankfully, cutting-edge conferencing solutions have come to the rescue. These tools help developers add robust video solutions to their applications, saving valuable time and resources in the process.
This article highlights what to look for in a conferencing API or SDK, the leading providers, and their pricing plans.
## What is a Video Conferencing API or SDK?
An [API](https://getstream.io/glossary/application-programming-interface-api/) is a set of protocols that allow different software programs to communicate with each other.
An SDK is a collection of software tools and components. These help developers build applications with a specific framework, platform, or API. Usually, they include code libraries, documentation, and code samples or snippets.
Real-time communication services cater primarily to app developers. They can get started by obtaining API credentials, setting up a server-side web application, and developing a client-side web application.
Specific to video conferences:
- APIs let you access specific functionalities, like initiating calls and managing participants.
- SDKs provide code and documentation to make it easier to use the video API.
SDKs are invaluable tools for integrating real-time [video conferencing functionality](https://getstream.io/video/video-calling/) into various platforms, such as:
- Communication apps: Face-to-face interaction within messaging platforms.
- Telemedicine apps: Video chat between patients and healthcare professionals.
- Social media platforms: Video calls to connect with friends, fans, and family.
- E-learning platforms: Live lectures.
## What Are the Benefits of Using an API over building Conferencing In-house?
### Faster Adoption
Providers offer pre-built video conference capabilities that you can quickly integrate into your product. This accelerates time-to-market by avoiding months or years spent developing these complex features in-house. You also capitalize on rapidly evolving video tech with minimal custom coding.
### Less In-House Maintenance
Third-party solutions enable you to offload ongoing maintenance, updates, and upgrades to the provider. This frees your engineers to focus on your core product experience.
### Better Security
Components have built-in, enterprise-grade security measures like encryption and access permissions. Providers identify vulnerabilities that individual dev teams may miss.
### More Cost-Effective
There's no need to maintain complex server architectures. So, though there can be an upfront investment, in the long run, it's cost-effective. Plus, you pay for only what you use while benefiting from economies of scale. Capital is freed for revenue-generating initiatives.
### Faster Time to Market
You integrate proven, ready-to-use modules versus undertaking lengthy development cycles yourself. Businesses can then quickly launch products and services, gaining a competitive edge in the market.
### Scalability
[Video conferencing solutions](https://getstream.io/blog/video-conferencing-nextjs/) must handle scale seamlessly, from small group calls to large broadcasts. Ready-made components leverage cloud infrastructure for elastic scaling. You gain access to virtually unlimited capacity compared to self-hosted environments that may be prone to bottlenecks.
## Key API Features for Conferencing Apps
Here are some features to look for in video conference services. You may not need all of them --- so choose features based on your needs.
### Core Audio/Video Features
At the heart of any video app lies robust audio and video capabilities. Look for providers that support:
- High-quality video streaming with features like HD resolution, [low latency](https://getstream.io/glossary/low-latency/), and seamless switching between camera sources
- High frames per second (FPS) for smooth video
- Reliable audio conference with noise suppression and echo cancellation
- Compatibility across different devices, operating systems, and browsers
- Call management
- Screen sharing functionality
- Video recording
- Multi-party and peer-to-peer calling
### Customization
If you want the flexibility to tailor the video app experience to your brand and user needs, look for these features:
- Embeddable UI components
- White-labeling and branding
- Virtual backgrounds and effects like blur
### Collaboration
To improve productivity and engagement, consider features like:
- [Real-time text chat](https://getstream.io/chat/)
- Breakout rooms
- Whiteboard
- Speaker spotlight
- Hand-raising functionality
- Reactions and emoticons
### Security
Look for solutions that implement security features like:
- End-to-end encryption
- User authentication
- Compliance with regulations like GDPR
### Deployment and Management
Validate if your video-calling components provide:
- Flexible deployment options
- Robust video analytics and metrics
- Moderation capabilities (e.g., mute/unmute participants)
- Technical support
- Various pricing models
## 7 Best Video Conferencing API Providers
### 1. [Agora](https://www.agora.io/en/products/video-call/): Best for Real-Time Engagement With High-Concurrent Users
Agora provides a real-time voice and live calling API. The API supports an unlimited number of concurrent channels. Each channel can support up to 1 million concurrent users.
Key features include:
- Interactive live streaming
- Cross-platform support (Android, iOS, Windows, Flutter, and Unity)
- Screen sharing
- Real-time chat functionality
- Whiteboard
- Supplemental Enhancement Information (SEI) that improves user experience
- Videos free of lags and jitters even in bad network conditions
- 99.99% uptime
- GDPR, [HIPAA-compliant](https://getstream.io/blog/hipaa-video-conferencing/)
Agora video components have an extensive partner gallery if you want to add additional capabilities. Users praise the platform for high-quality calls that remain clear as more users join. Pricing depends on the features you want to add. However, it's free for up to 10,000 minutes every month.
### 2. [Stream](https://getstream.io/video/): Best for Feature-Rich User Experiences
Stream's performant SDKs for leading software frameworks and intuitive UI kits make building feature-rich [in-app video conferencing](https://getstream.io/video/video-calling/) quick and painless.

Key features include:
- Pre-built UI kit to easily add responsive elements like logos, colors, and typefaces
- One-to-one and group calls and HD videos
- Global edge network for low-latency calls
- Live conference and webinar functionality
- Unlimited media and file sharing
- Multi-platform support
- Detailed developer documentation for video API integration
- Both SaaS and self-hosted option
You can use Stream for use cases like healthcare, social, HR, recruitment, and finance. It supports a variety of SDKs like [React](https://getstream.io/video/sdk/react/), [React Native](https://getstream.io/video/sdk/react-native/), [iOS](https://getstream.io/video/sdk/ios/), [Android](https://getstream.io/video/sdk/android/), [Flutter](https://getstream.io/video/sdk/flutter/), [Unity](https://getstream.io/video/sdk/unity/), and [Javascript](https://getstream.io/video/sdk/javascript/).
The SaaS option has multiple [pricing plans](https://getstream.io/pricing/#video): ranging from a free plan to custom enterprise plans.
### 3. [Dyte](https://dyte.io/): Best for Immersive Live Experiences
Dyte uses WebRTC and optimized streaming protocols (HTTP Live Streaming or HLS) to deliver ultra-low-latency video streams. It also uses Real-Time Messaging Protocol ([RTMP](https://getstream.io/blog/real-time-messaging-protocol/)) to host high-definition videos easily.

You can host webinars with live transcription and interactive elements like built-in chat, polls, and quizzes to create immersive experiences. Engagement features like emoticons, screen sharing, private chats, GIF and image sharing, and backdrops are also available.
Key features include:
- Call recording facility
- Breakout rooms
- Custom UI support
- Low-code processes
- SOC 2, HIPAA, and GDPR compliance
- 10,000 free minutes monthly
After the free tier, the charges are $0.004 per user per minute.
### 4. [Daily](https://www.daily.co/): All-In-One Solution
Daily's video solution has features for all use cases and has robust analytics and rich mobile experiences.

Key features include:
- Ability to host 100,000 real-time active participants with its global mesh network in 30 availability zones
- <13ms median first-hop latency or less for 5 billion people
- End-to-end encryption and serverless peer-to-peer modes for data protection
- Adheres to SOC 2, GDPR, and HIPAA regulations
- Integrates easily with AI platforms like ChatGPT and supports noise cancellation and real-time transcription
- Recording
- Ability to create animated graphics and custom layouts in multi-party live streams and recorded content
It provides 10,000 free minutes every month. If you want more, there's usage-based pricing. Volume discounts are available, and startups can get special pricing credits.
### 5. [Amazon Chime](https://aws.amazon.com/chime/chime-sdk/): Best SDK for Large Webinars
Amazon Chime SDK allows developers to add real-time audio, video, and messaging features with machine learning. You can deliver real-time content to 10,000 members. Its live connector lets you stream videos to large audiences on your streaming platform.

You can use client libraries like iOS, Android, Windows, and JavaScript to enable voice and video on WebRTC-enabled browsers.
Key features include:
- Video simulcast and [scalable video coding](https://getstream.io/glossary/scalable-video-coding/) (SVC) for better quality across devices
- Content sharing
- Mute controls and volume notifications
- Device controller to manage sound input and output
- Pre-built and customizable bandwidth features to control video bandwidth
- Background blur for visual privacy
- Amazon Voice Focus for noise reduction
Pricing is pay-as-you-go.
### 6. [Apphitect](https://www.apphitect.ae/instant-messaging-solution.php): Top On-Premise Option
Apphitect video conferencing API is a self-hosted solution that can scale up to 1 billion conversations. It offers 99.999% uptime SLA and 100ms latency.

Key features include:
- 150+ chat features that fit any iOS, Android, and web application
- White-label functionality to add your logo, color, and other custom features
- SOC 2, HIPAA, and GDPR-compliant
- Real-time chat with push notifications, group chat, file transfer, spell check, and cross-platform messaging
- One-to-one video chats, conference scheduling, and screen sharing
Contact their sales team for pricing.
### 7. [Cometchat](https://www.cometchat.com/voice-and-video-calls): Best for Broad Platform Coverage
Cometchat's video call SDKs help you integrate real-time audio and video conferencing technology into your apps. It has all the core features for video conferences, like whiteboards, screen sharing, group calling, one-to-one calling, presenter mode, and moderator mode. Cometchat is a good option if you want support for a wide range of technologies like React, Angular, Vue, iOS, Flutter, Android, Kotlin, and PHP.

Key features include:
- Pre-built workflows for calling: You can create WhatsApp-style direct calling and [Zoom-style meeting rooms](https://getstream.io/blog/swiftui-video-conferencing-app/)
- Call recording
- HIPAA, GDPR, PIPEDA, SOC 2, and ISO 27001 compliance
- Modular architecture to customize SDK and UI kits
- 99.99% uptime
- No-code widget to add code for your web app in minutes
Cometchat is free for 25 users and has an "Essential" and "Pro" pricing structure for $109/month and $529/month, respectively.
## Did You Find the Right Conferencing API or SDK?
Integrating video conference capabilities into your applications can open new avenues for collaboration, engagement, and growth. But choose the wrong one, and you risk damaging your brand's reputation. By selecting the right conferencing solutions, you can streamline development, reduce time-to-market, and deliver positive user experiences. | emilyrobertsatstream |
1,900,503 | Top Security Threats Mitigated by Smart Contract Audit Services | Smart contracts are a cornerstone of blockchain technology, enabling decentralized and automated... | 0 | 2024-06-25T19:58:06 | https://dev.to/auditfirst_io/top-security-threats-mitigated-by-smart-contract-audit-services-5g4d | blockchain, smartcontract | Smart contracts are a cornerstone of blockchain technology, enabling decentralized and automated transactions without the need for intermediaries. However, the potential for security vulnerabilities in smart contracts is significant, making the role of [smart contract audit](https://auditfirst.io/) services crucial. In this article, we will explore the top security threats that smart contract audit services mitigate, ensuring the safety and reliability of blockchain applications.
1. Reentrancy Attacks
Reentrancy attacks occur when a malicious contract repeatedly calls a function before the initial execution is complete. This can lead to unexpected changes in the state of the contract and result in significant financial losses. Smart contract audit services identify and fix reentrancy vulnerabilities by ensuring proper function calls and state management.
2. Integer Overflow and Underflow
Integer overflow and underflow vulnerabilities arise when arithmetic operations exceed the maximum or minimum values a variable can hold. This can lead to incorrect calculations and unintended contract behavior. Auditors use static analysis tools to detect potential overflow and underflow issues and implement safe mathematical operations.
3. Access Control Issues
Improper access control can allow unauthorized users to perform restricted actions on a smart contract. This can lead to data manipulation, fund theft, or other malicious activities. [Smart contract audit services](https://auditfirst.io/) review the contract's access control mechanisms, ensuring that only authorized entities can execute sensitive functions.
4. Denial of Service (DoS) Attacks
Denial of Service attacks aim to disrupt the normal functioning of a smart contract, rendering it unusable. This can occur through various means, such as consuming excessive gas or triggering infinite loops. Auditors analyze the contract's logic to identify potential DoS vectors and optimize gas consumption to prevent such attacks.
5. Front-Running Attacks
Front-running occurs when a malicious actor intercepts and preempts transactions by paying higher gas fees, gaining an unfair advantage. This can result in financial losses for the affected users. Smart contract audit services assess the transaction ordering mechanisms and implement measures to mitigate front-running risks, such as using commit-reveal schemes.
6. Logic Errors
Logic errors are flaws in the [smart contract's code](https://auditfirst.io/) that lead to unintended behavior or incorrect outcomes. These errors can result from poorly designed algorithms or misunderstandings of the contract's intended functionality. Auditors meticulously review the contract's code to ensure that it behaves as expected under all conditions.
7. Insecure External Calls
Smart contracts often interact with external systems or other contracts, which can introduce security risks if not handled properly. Insecure external calls can lead to data leakage, unauthorized access, or unexpected behavior. Smart contract audit services scrutinize all external interactions and implement best practices to secure these calls.
8. Uninitialized Storage Pointers
Uninitialized storage pointers can lead to unintended data manipulation and security breaches. This vulnerability arises when storage pointers are declared but not properly initialized. Auditors identify and initialize all storage pointers to prevent unauthorized access and data corruption.
9. Timestamp Dependence
Smart contracts that rely on timestamps for critical operations can be vulnerable to manipulation, as miners can influence the block timestamp. This can affect the contract's behavior and lead to security issues. Audit services analyze timestamp dependencies and recommend alternative solutions to ensure accurate and reliable time-based operations.
10. Insufficient Testing
Insufficient testing of smart contracts can leave critical vulnerabilities undiscovered. Comprehensive testing, including unit tests, integration tests, and formal verification, is essential for ensuring the security of smart contracts. Audit services provide thorough testing and validation to identify and rectify potential issues before deployment.
Conclusion
[Smart contract audit services](https://auditfirst.io/) play a vital role in mitigating the top security threats in blockchain applications. By addressing vulnerabilities such as reentrancy attacks, integer overflow, access control issues, and more, these services ensure the safety, reliability, and integrity of smart contracts. Investing in a comprehensive smart contract audit is essential for any blockchain project aiming to build trust and security within its ecosystem.
For more information on how [smart contract audit services](https://auditfirst.io/) can enhance your blockchain project's security, contact us today.
| auditfirst_io |
1,900,498 | Responsividade | 1. O que é responsividade? Responsividade é a ténica de adaptar uma página web para vários... | 0 | 2024-06-25T19:53:59 | https://dev.to/annalaura2/responsividade-dpb |
## 1. O que é responsividade?
Responsividade é a ténica de adaptar uma página web para vários dispositivos diferentes, ou seja, ocorrem mudanças no css baseadas na resolução. O recurso utilizado na responsividade é o "Media query".
## 2. Configuração HTML para responsividade:
Inicialmente, é necessário adicionar uma meta tag no head:
`
<meta name="viewport" content=""width=device=width, initial-scale="1.0">`
## 3. Media Query:
Media Query é o recurso que usamos para criar o breakpoints. Os breakpoints adaptam o projeto para os diversos tipos de tela.
Ao configurar a largura, as regras são alteradas dependendo do tamanho da tela.
## 4. Breakpoints mais utilizados:
4.1 600px e abaixo: celular.
4.2 768 até 600px: tablets.
4.3 992px até 768px: mini-laptops.
4.4 992px e acima: laptop e desktop.
| annalaura2 | |
1,900,500 | Docker Security Checklist: Are You Production Ready? | Secure Docker images for production with this essential guide. Learn how to scan for vulnerabilities, use multi-stage builds, avoid embedded secrets, and ensure smooth container deployments | 0 | 2024-06-25T19:53:22 | https://dev.to/shettigarc/docker-security-checklist-are-you-production-ready-443p | docker, devsecops, devops | ---
description: "Secure Docker images for production with this essential guide. Learn how to scan for vulnerabilities, use multi-stage builds, avoid embedded secrets, and ensure smooth container deployments"
author: "Chandra Shettigar"
---
You've built a great application using Docker, but are you really ready to push it to production? Before you hit that button, let's make sure your Docker image is secure and reliable.
## No Dev Tools in Production
The Docker image you use for testing and development is probably packed with tools and dependencies you don't need in production. This makes it larger and potentially more vulnerable. Keep your production images lean and mean!
## Use a Multi-Stage Build
Think of [multi-stage](https://www.devteds.com/multi-stage-docker-build-tutorial/) builds like a factory assembly line. You build your application in one stage, then create a separate, minimal image in another stage. This final image only contains what's essential for running your app in production, reducing its attack surface.
If you'd like to learn more about multi-stage builds and see a step-by-step example, check out this tutorial: [Multi-Stage Docker Build](https://youtu.be/EkOCLmvwEhc?si=InFp4bXnNLFn9r49)
## Scan Your Image for Vulnerabilities
Before pushing your image to a registry or deploying it to production, always scan it for vulnerabilities. Think of this as a security checkpoint for your code.
Tools like [Docker Scout](https://docs.docker.com/scout/) can help you identify potential weaknesses in your image and provide recommendations for fixing them. This is a crucial step in ensuring the security of your application before it's exposed to the wider world.
## Integrate Security Into Your CI/CD
Integrate image scanning into your Continuous Integration/Continuous Delivery (CI/CD) pipeline. This ensures every image you build for deployment gets a thorough security check before it goes anywhere near production.
## Enable Registry Scanning
Many container registries, like AWS Elastic Container Registry (ECR), can automatically scan images when they're pushed. This adds another layer of defense, catching any vulnerabilities that might have slipped through earlier checks.
## No Sensitive Data in the Image
Never, ever store sensitive data (passwords, API keys, certificates) directly in your Docker image. Treat your images like postcards: anyone can read them! Use environment variables, secrets management tools, or volume mounts to inject sensitive data at runtime.
## Avoid Docker Drift: One Image, All Deployment Environments
Use the same Docker image across all your application environments (testing, staging, production). This reduces the chances of unexpected surprises when you promote your application.
**Pro Tip:** If you're using multiple Dockerfiles or building environment-specific Docker images, you're probably doing it wrong. This approach often leads to baking configuration details or secrets into your images, which is a major security risk. Keep it simple and use a single image for all environments!
## Know Your Base Image
Be picky about your base image. It's the foundation of your Docker image, so choose one that is well-maintained and has a good security track record. Consider using security-hardened images for extra protection.
There are three main ways security vulnerabilities sneak into your container images:
- **Inherited Vulnerabilities:** These come from the base image itself. Using a clean, well-maintained base image is crucial to avoid spending time fixing OS-level issues.
- **Tool Vulnerabilities:** The tools you install for your application can also introduce vulnerabilities. Keep these to a minimum and make sure they're up-to-date.
- **Application Vulnerabilities:** Your own application code can be a source of vulnerabilities. Thorough testing and code review are essential.
## Create a Scan Review Process
Don't just scan your images, review the reports! Establish a process to assess vulnerabilities and decide how to handle them. You might fail the build pipeline if new vulnerabilities are found, or you might fix them later. The choice depends on your team's workflow and the level of risk you're willing to accept.
## Security Scanning at Runtime
Scanning your images before deployment is important, but don't forget about runtime security. Monitoring your containers in production and having a plan to address any vulnerabilities that emerge is critical. The specific tools you use will depend on your container infrastructure.
## Conclusion
Taking a little extra time to ensure your Docker image is secure can save you a lot of headaches down the road. By following these steps, you'll be well on your way to running a secure and reliable application in production.
| shettigarc |
1,900,499 | Juniors Are Doomed And This Is Good (LLMs Hype, Copilots, and The Turning Point) | TL;DR get good or quit tech Junior Engineering Is Hard A junior engineer is a person who... | 0 | 2024-06-25T19:53:22 | https://geeklore.io/articles/juniors-are-doomed-and-this-is-good-llms-hype-copilots-and-the-turning-point-kn2Kf | TL;DR
get good or quit tech
## Junior Engineering Is Hard
A junior engineer is a person who is just starting in tech. Be it frontend, backend, or operations, it is a person just starting out. How can you distinguish a junior engineer from a mid-level or a senior? Quite easy, actually. Here are the top 5 signs to catch a junior:
- Highly intensive desire to talk about tech
- Iressistable need to express an opinion
- Constant questions that can be googled
- Aggressive display of superiority over non-tech acquaintances
- Constant, loud, neverending, ear-numbing, complete and utter yapping
Ah, yes. The junior engineer, an alpha speciment indeed.
But what exactly are junior engineers doing in their daily worklife? Well, this has been a hot topic since I have been in tech. Let's explore more by looking deeper into three categories:
- Frontend
- Backend
- Operations
**Frontend**
Requirements for a junior frontend engineer role:
- HTML/CSS: Proficiency in HTML5 and CSS3, understanding of web standards, and responsive design principles.
- JavaScript: Good knowledge of JavaScript (ES6+), including DOM manipulation and JavaScript frameworks/libraries such as React, Vue.js, or Angular.
- Version Control: Familiarity with Git and GitHub or other version control systems.
- Web Performance: Basic understanding of optimizing web applications for maximum speed and scalability.
- Cross-Browser Compatibility: Understanding of how to ensure consistency across various browsers and devices.
- Debugging: Basic skills in using browser developer tools to debug and profile applications.
- API Integration: Experience with RESTful services and APIs.
- Build Tools: Familiarity with build tools such as Webpack, npm, or Yarn.
You need to know HTML and CSS. You need to know JavaScript. You need to know your way around a library like React. GIT. SEO and PageSpeed Insights. Tailwind, Bootstrap, Flexbox, Grid. Be able to write unit tests. REST, CORS, data transformation. Builders.
Often you will also be required to understand UI/UX principles. You will need to participate in scrum and agile rituals. You will also find yourself bashing your head against technologies like Docker, be required to at least once troubleshoot a CI/CD pipeline in Github Actions, Azure DevOps, or Gitlab, and worst of all - experience the absolute horror of *rebase and merge*.
All of this while nobody takes you seriously because you are *only doing frontend*.
Takeaway: being a frontend sucks.
**Backend**
Requirements for a junior backend engineer role:
- Programming Languages: Proficiency in one or more backend programming languages such as Python, Java, Ruby, Node.js, or PHP.
- Database Management: Understanding of relational databases (e.g., MySQL, PostgreSQL) and non-relational databases (e.g., MongoDB, Redis).
- API Development: Experience in designing and developing RESTful APIs and/or GraphQL APIs.
- Version Control: Familiarity with Git and platforms like GitHub, GitLab, or Bitbucket.
- Server Management: Basic knowledge of server, networking, and hosting environments (e.g., Linux, Apache/Nginx).
- ORM Frameworks: Experience with Object-Relational Mapping frameworks like SQLAlchemy, Hibernate, or Django ORM.
- Security: Basic understanding of security principles and practices, including data protection and authentication.
- Testing: Familiarity with backend testing frameworks and tools, such as JUnit, pytest, or Mocha.
- Containerization: Basic knowledge of containerization tools like Docker.
Again, you need to know a programming language. You need to be slightly *(he-he)* proficient in SQL, and NoSQL. You need to understand and be able to apply the concept of caching. You need to understand the difference between REST and GraphQL. GIT. ORMs (what even is this). S E C U R I T Y. Testing. Docker. Kubernetes. Packer. And so on.
Being a backend at least comes with bragging rights. You can also lie to your friends that you are a haxxer.
Takeaway: being a backend still sucks but has its perks
**Operations**
Opinion too long, too lazy to explain. [read this as a start, more incoming](https://www.geeklore.io/articles/devops-by-kubeden-chapter-1-5WyKP)
In short: operations guys are cool, aways have been, always will be.
We went over the roles, now the question - **will there be junior engineers in the future?**
No. Let me elaborate.
## "Evolution, Dummy!"
Junior engineering hasn't always been like this. A few years ago, you would have done perfectly fine with just a programming language and a library.
**What changed?**
Evolution happened, dummy.
As with any other area of our lives, we evolved. A top performer will always inspire. Top performers through the years pushed harder and harder and left a mark with every push. We got inspired, and we tried to mirror their behavior, their achievements, and their success. Some of us could, others couldn't. But regardless of the outcome for each of us, we all collectively became better.
We entered a "new normal" of knowing more, raising expectations, and accelerating our field.
Sure, there has been a few cracks in the transmission like the mass layoffs after Covid but ultimately the machine is moving. And it's moving fast.
Should you be scared? It depends.
## Ain't No Rest For The Junior
There will not be junior engineers as the ones we are used to observing and meeting around us today. The junior engineers of the future will be all-round experts. A guild of generalists, proficient in everything we are now struggling to get good at. Skill issues will not be in their dictionaries.
Claude (the hottest new guy on the block) and ChatGPT (even though in it's depressive phase lately) are the tools defining the reality of software engineering that is to come. The epitome of acceleration. LLMs make learning faster, more action-based, and the dopamine reward of succeeding in doing simple tasks is hooking millions of people to code. This allows for a more rapid development of candidates, and will also cut the unworthy.
If you can't do a task, you are not supposed to be in tech. If you are scared of LLMs *"taking your job"*, you should find another job. The pressure will simply be too much for you to handle.
With this, I close my article and express my greatest respects to three individuals - **John McAfee, Terry A. Davis, and Alex Mahan**.
Peace. | kubeden | |
1,900,497 | What is Google Cloud Functions (simplified)? | Google Cloud Functions is a service that runs specific code (a function) in response to events,... | 0 | 2024-06-25T19:52:32 | https://dev.to/robertasaservice/what-is-google-cloud-functions-simplified-10gp | Google Cloud Functions is a service that runs specific code (a function) in response to events, without needing to keep servers running all the time.
**Key features:**
**Event-driven:** Functions are triggered or executed through HTTP requests, changes in database, or uploads to cloud storage
**Scalability:** Functions scales automatically based on incoming requests
**Serverless:** No need to manage servers
**A Simple Metaphor to Understand Google Cloud Functions:**
Imagine you run a bakery.
In this bakery, you have a bell that rings whenever a customer enters, signaling the bakers to start baking a specific type of pastry based on the customer's request.
**The Bell:** This is like the event trigger in Google Cloud Functions. It could be an HTTP request, a new file uploaded to cloud storage, or a database update.
**The Bakers:** These are like the cloud functions. They are small, specific tasks (functions) that get executed in response to the bell ringing (event).
**The Recipe:** This is the code you write for your function, dictating what the bakers should do when the bell rings.
**The Bakery Manager:** This is Google Cloud, managing the bakers (functions). You don’t worry about hiring more bakers (scaling), ensuring they have the ingredients (resources), or dealing with their schedules (server management). The manager takes care of everything so that the right number of bakers are always ready to respond to the bell.
#cloudfunctions #serverless #gcp #googlecloud #cloud #google | robertasaservice | |
1,900,496 | String search methods in JavaScript.! | String indexOf() String lastIndexOf() String search() String match() String matchAll() String... | 0 | 2024-06-25T19:50:25 | https://dev.to/samandarhodiev/string-search-methods-in-javascript-5gm2 | `String indexOf()
String lastIndexOf()
String search()
String match()
String matchAll()
String includes()
String startsWith()
String endsWith()`
<u>**`indexOf()`**</u>
Ushbu metod string satrining elementiga mos indeks raqamni qaytaradi, element topilmasa -1 qaytaradi!
```
let myEmail = "samandarhodiev04@gmail.com";
console.log(myEmail);
//natija - samandarhodiev04@gmail.com
let indexOf_ = myEmail.indexOf('a');
console.log(indexOf_);
//natija - 1
```
<u>**`LastIndexOf()`**</u>
Ushbu metod IndeOF() metodi kabi ishlaydi ammo ular orasida bir farq bor.
<u>**Farq:**</u>
**indexOf()** - metodi izlanayotgan satr elementiga mos indeks raqamini chapdan o'ngga qarab izlaydi va topilgan 1-natijani qaytaradi.
**LastIndexOf()** - metodi esa o'ngdan chapga qarab izlaydi va topilgan 1-natijani qaytaradi.!
```
let myEmail = "samandarhodiev04@gmail.com";
console.log(myEmail);
//natija - samandarhodiev04@gmail.com
let LastIndexOf_ = myEmail.lastIndexOf('a');
console.log(LastIndexOf_);
//natija - 19
```
<u>**`search()`**</u>
Ushbu metod satrni yoki satr elementini oladi va mos keluvchi indeks raqamini qaytaradi.!
IndexOf() va Search() metodiga o'xshash bo'lishiga qaramasdan, search() elementga mos indeks raqam qayerdan boshlab izlanishi kerakligini belgilayolmaydi.!
```
let myEmail = "samandarhodiev04@gmail.com";
console.log(myEmail);
//natija - samandarhodiev04@gmail.com
let search_ = myEmail.search('.com');
console.log(search_);
//natija - 22
```
<u>**`match()`**</u>
Ushbu metod izlanayotgan element yoki satr ni o'z ichiga olgan massivni qaytaradi, ushbu metod katta-kchik harflarga sezgir va quyidagi misolda katta kchik harflar farq qilmagan holda izlash imkonini beruvchi xolatlar keltirilgan.!
```
let fruits_ = 'apple, banana, lEmon, apple, mango, appLe';
console.log(fruits_);
//natija - apple, banana, lemon, apple, mango, apple
let match_1 = fruits_.match('le');
console.log(match_1);
//natija - ['le', index: 3, input: 'apple, banana, lemon, apple, mango, apple', groups: undefined]
let match_2 = fruits_.match(/le/g);
console.log(match_2);
//natija - ['le', 'le']
let match_3 = fruits_.match(/le/gi);
console.log(match_3);
//natija - ['le', 'lE', 'le', 'Le']
```
<u>**`matchAll()`**</u>
ES2020
<u>**`includes()`**</u>
Ushbu metod string satiri ichida biror bir satr yoki element bor yoki yo'qligini aniqlabberadi, bor bo'lsa - true yo'q bo'lsa - false qiymat qaytaradi, ushbu metod ES6 da kiritilgan va katta-kichik xarflarga sezgir.!
```
let fruits_ = 'apple, banana, lEmon, apple, mango, appLe';
console.log(fruits_);
//natija - apple, banana, lemon, apple, mango, apple
let includes_1= fruits_.includes('apple');
console.log(includes_1);
//natija - true
let includes_2= fruits_.includes('carrot');
console.log(includes_2);
//natija - false
```
<u>**`startWith()`**</u>
ES6.
Ushbu metod string elementi qanday xarf yoki raqam bilan boshlanishiga qarab true yoki false qiymat qaytaradi shuningdek katta va kichik xarflarga sezgir va izlash qayerdan boshlanishi kerakligini belgilash mumkin.
**<u>sintaksis: </u>****startwith('sign' , n)!**
```
let myEmail = "samandarhodiev04@gmail.com";
console.log(myEmail);
//natija - samandarhodiev04@gmail.com
let startWith_1 = myEmail.startsWith('s');
console.log(startWith_1);
//natija - true
let startWith_2 = myEmail.startsWith('M');
console.log(startWith_2);
//natija - false
let startWith_3 = myEmail.startsWith('a', 12);
console.log(startWith_3);
//natija - false
```
<u>**`EndsWith()`**</u>
ES6.
Ushbu metod string elementi qanday xarf yoki raqam bilan boshlanishiga qarab true yoki false qiymat qaytaradi shuningdek katta va kichik xarflarga sezgir va izlash qayerdan boshlanishi kerakligini belgilash mumkin.
**<u>sintaksis: </u>****startwith('sign' , n)!**
```
let myEmail = "samandarhodiev04@gmail.com";
console.log(myEmail);
//natija - samandarhodiev04@gmail.com
let endsWith_1 = myEmail.endsWith('M');
console.log(endsWith_1);
//natija - false
let endsWith_2 = myEmail.endsWith('m');
console.log(endsWith_2);
//natija - true
let endsWith_3 = myEmail.endsWith('o',25);
console.log(endsWith_3);
//natija - true
```
| samandarhodiev | |
1,900,495 | Dependency Discovery Deck: A Game-Changer for Scaled Agile Teams | In the dynamic environment of Agile development, effectively managing dependencies is essential for... | 0 | 2024-06-25T19:45:29 | https://dev.to/nihyo/dependency-discovery-deck-a-game-changer-for-scaled-agile-teams-58lo | agile, depedency, gamification, opensource |

In the dynamic environment of Agile development, effectively managing dependencies is essential for ensuring smooth project execution and timely delivery. Many teams encounter challenges in identifying and managing these dependencies, leading to project delays and inefficiencies. The Dependency Discovery Deck, an innovative card deck, has emerged as a transformative solution to these challenges.

## Challenges in Dependency Management
Before utilizing the Dependency Discovery Deck, the team faced significant obstacles during backlog refinement sessions. Dependencies were frequently overlooked until they caused critical bottlenecks, leading to project delays and frustration. The team struggled to visualize task interconnections, which resulted in missed deadlines and scope creep. Additionally, communication gaps and misaligned priorities further complicated the workflow.

## Introduction to the Dependency Discovery Deck
The Dependency Discovery Deck is a set of gamified cards designed to assist Agile teams in systematically identifying and managing dependencies during backlog refinement sessions. Each card represents a specific strategy or tool to uncover hidden dependencies and address potential blockers before they impact the project timeline.
## Impact of the Dependency Discovery Deck
1. Structured Framework:
The Dependency Discovery Deck provides a structured framework for dependency management. This clear process replaces ad-hoc discussions, ensuring comprehensive exploration of potential dependencies. The cards guide teams through various aspects of dependency identification, such as analyzing stakeholder relationships and mapping technical requirements.
2. Enhanced Collaboration:
The deck fosters a more inclusive and collaborative environment. Each team member is encouraged to actively participate, share insights, and contribute ideas. The gamified nature of the cards makes the process engaging and interactive, ensuring all voices are heard and fostering a sense of shared responsibility and ownership.
3. Improved Planning and Estimation:
By identifying dependencies early in the refinement process, teams can create more accurate and realistic project plans. This proactive approach allows for more effective resource allocation, better risk management, and the setting of achievable milestones. As a result, planning accuracy improves significantly, leading to more predictable and reliable project outcomes.
4. Visualization of Dependencies:
The visual component of the Miro Board, combined with the Dependency Discovery Deck, facilitates the mapping and visualization of dependencies. Teams can clearly see how different tasks and features are interconnected, helping to anticipate and mitigate potential blockers. This clarity helps maintain a smooth workflow and prevents last-minute surprises.
5. Empowerment of the Team:
The Dependency Discovery Deck empowers teams by providing a clear and structured approach to dependency management. This instills confidence in handling complex projects, equipping team members to tackle challenges and motivating them to contribute to the collective success of the project.
## Conclusion
The Dependency Discovery Deck has proven to be a valuable tool for Agile teams, offering a structured framework for dependency management, enhancing collaboration, improving planning and estimation, and empowering team members. Teams struggling with dependency management can benefit from exploring this innovative tool in the Miroverse. Using the Dependency Discovery Deck can significantly enhance Agile workflows, leading to more efficient and effective project outcomes.
For teams looking to further optimize their Agile practices, exploring other card decks like the Dependency Discovery Deck in the Miroverse is highly recommended. These tools can provide additional strategies and insights to enhance Agile development processes.
##Links
[Github](https://github.com/nilsbert/Dependency-Discovery-Deck)
[Etsy](https://agilegames.etsy.com/listing/1712190266)
[Miro](https://miro.com/miroverse/dependency-discovery-deck/) | nihyo |
1,900,448 | Web Accessibility: Making Digital Services Inclusive for All | Imagine a scenario where a government agency provides vital services such as issuing permits and... | 0 | 2024-06-25T19:42:12 | https://dev.to/thegirlme/web-accessibility-making-digital-services-inclusive-for-all-2hci | webaccessibility, productivity |
Imagine a scenario where a government agency provides vital services such as issuing permits and accessing public health information, but individuals with disabilities face challenges in obtaining these services. This difficulty arises because the agency's website isn't designed to accommodate their needs.
If you're new to web accessibility, it refers to designing and coding websites to allow people with disabilities to use them effectively. A key aspect of web accessibility is ensuring that individuals with various disabilities—visual, auditory, motor, or cognitive impairments—can navigate and interact with websites without barriers.
You may have heard about features like screen readers on websites. These are tools that read aloud the content of web pages, enabling users who are blind or visually impaired to access and navigate the information displayed. This is just one example of how web accessibility enhances inclusivity by making digital content accessible to everyone, regardless of their abilities.
#### Understanding the type of disabilities needed to be considered the best solution for them
As a software developer, incorporating web accessibility is fundamental to our daily development process. It requires us to consider the diverse range of disabilities that users of our websites may have. This means ensuring that our websites and applications are designed and developed to accommodate:
- Visual impairment: people who deal with blindness or have low vision may rely on screen readers. This is the best practice for helping them catch up with our website's main content.
- Motor impairment: people with motor impairment may use alternative input devices like keyboards or switches instead of a mouse. This implementation will help them to feel comfortable and welcome to our service.
- Hearing impairment: users deal with deafness or difficulty hearing; there is another alternative, like captions for audio content, to ensure that the essential concepts are captured without making it difficult for them.
- Cognitive Disabilities: Using clear and simple language in our application, organising content, and providing predictable navigation will make our website more accessible.
We can not talk about all disabilities, but I hope this helps.
#### Importance of web accessibility
Web accessibility significantly influences how our end product will satisfy our customers. This concept is crucial before jumping to the implementation process. Let's talk about its positive impact on the users.
- Inclusion: we need to consider the inclusion concept when developing an application. That's where web accessibility comes in. Allowing people with disabilities to perceive, understand, navigate and interact with the web is priceless because people will feel welcomed, and the app's main functionality will be easily accessible.
- Level of Usability: Improves overall usability for all users, not just those with disabilities. For example, clear navigation benefits users in noisy environments or small screens.
- Future-proofing: Ensures that the web can stand with evolving technologies and will be the best fit in the future by including people with disabilities.
- Business improvements: Webs with high accessibility tend to have many audiences. All people are included, and they feel comfortable when using the service. A website with web accessibility tends to have more customers and market reach.
In essence, web accessibility is about creating an inclusive online environment where all individuals, including those with disabilities, can access information, engage with services, and participate fully in the digital world. It involves using best practices in web design, such as providing alternative text for images, ensuring keyboard navigation compatibility, and implementing accessible forms and multimedia content.
| thegirlme |
1,900,510 | How to Build a GraphQL API for MongoDB Using Hasura in Six Steps | Learn how to quickly connect Hasura to MongoDB and generate a secure, high-performance GraphQL API. | 0 | 2024-06-25T19:41:00 | https://www.mongodb.com/developer/products/atlas/graphql-apis-hasura/ | graphql, mongodb, hasura | ---
title: How to Build a GraphQL API for MongoDB Using Hasura in Six Steps
published: true
description: Learn how to quickly connect Hasura to MongoDB and generate a secure, high-performance GraphQL API.
tags: graphql,mongodb,mongo,hasura
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
published_at: 2024-06-25 19:41 +0000
canonical_url: https://www.mongodb.com/developer/products/atlas/graphql-apis-hasura/
---
In 2012, GraphQL was introduced as a developer-friendly API spec that allows clients to request exactly the data they need, making it efficient and fast. By reducing the need for multiple requests and limiting the over-fetching of data, GraphQL simplifies data retrieval, improving the developer experience. This leads to better applications by ensuring more efficient data loading and less bandwidth usage, particularly important for mobile or low-bandwidth environments.
Using GraphQL instead of REST on MongoDB is desirable for many use cases, especially when data from multiple MongoDB instances needs to be accessed simultaneously or when engineers need to join NoSQL data from MongoDB with data from another source.
However, engineers often encounter difficulties implementing GraphQL APIs and layering them onto their MongoDB data sources. This learning curve and the maintenance overhead often inhibit adoption. Hasura was designed to address this common challenge with adopting GraphQL.
Hasura is a low-code GraphQL API solution. With Hasura, even engineers unfamiliar with GraphQL can build feature-rich GraphQL APIs — complete with pagination, filtering, sorting, etc. — on MongoDB and dozens of other data sources in minutes.
Hasura also supports data federation, enabling developers to create a unified GraphQL API across different databases and services. In this guide, I’ll show you how to quickly connect Hasura to MongoDB and generate a secure, high-performance GraphQL API.
I will take you through the following steps to:
- Create a project on Hasura Cloud
- Create a database on MongoDB Atlas
- Connect Hasura to MongoDB
- Generate a high-performance GraphQL API instantly
- Try out GraphQL queries with relationships
- Analyze query execution
In addition, I will delve into the mechanics behind the generated API's exceptional performance, detailing the techniques and optimizations that contribute to its efficiency.
By the conclusion of this guide, you will possess the skills necessary to build your own high-performance, production-ready GraphQL API using Hasura, tailored for your existing or new MongoDB Atlas instance.
## Step 1: Create a project on Hasura Cloud

To begin, you will need a project on Hasura Cloud and a MongoDB database on Atlas. Head over to [cloud.hasura.io](https://cloud.hasura.io/signup?utm_source=mongodb&utm_medium=blog&utm_campaign=mongodb_developer_portal) to create an account or log in. Once you are on the Cloud Dashboard, navigate to [Projects](https://cloud.hasura.io/projects) and click on `New Project` to create a new project.

You can create a free project by selecting the region of your choice. In this example, we are using AWS infrastructure, US West region.
Remember the region selected. We want to co-locate the GraphQL API deployed using Hasura Cloud in the same region as the database on MongoDB Atlas. This will be done in one of the subsequent steps. Click on the `Create Free Project` button, as highlighted. As always, you can upgrade the project later as required.
Once the project is created, you’ll be taken to the project details page, which displays the GraphQL endpoint among other details. Take note of the `Hasura Cloud IP` on this page, as it’s required during the MongoDB Atlas setup to allow the connection from Hasura to MongoDB.

Click on `Launch Console` to open the project's Hasura Console. You will land on the API Explorer page to try out the GraphQL APIs.

Click on the `DATA` tab at the top to navigate to the Data Management section of the console. Here you can connect to the various databases that Hasura supports. Choose MongoDB from the list and click on `Connect Existing Database`.

At this point, Hasura requires the connection details of MongoDB.
## Step 2: Create a database on MongoDB Atlas
Hasura can connect to a new or an existing MongoDB Atlas database and generate the GraphQL API for you. Now, go ahead and create a new database and use some autogenerated sample data.
Go to [MongoDB Atlas](https://cloud.mongodb.com/), create a project if you don’t already have one, and navigate to the Database page under the Deployments section. You should see a page like the one below:

Click on the `Build a Database` button. On the next page, select the deployment specifics. Start with the Free M0 cluster, free forever and ideal for getting started. You can always upgrade later when required.

Give the cluster a name; for this example, use `Hasura`. You will need to select the region. For this tutorial, pick AWS as the provider and choose the `us-west-2` region to keep the data close to the Hasura instance (recall that our Hasura cluster was deployed on US West, as well).

Remember to choose the region closest to your users. Keeping your database and API region the same is recommended to avoid performance and latency issues.
Next, add your IP address for local connectivity and create a new database user with `atlasAdmin` permission that you’ll need to access the MongoDB cluster from Hasura Cloud.

Note the password, as we will need it later. Now, click on `Create Database User`. `Choose a connection method` and skip the next steps. Optionally, in case you are stuck in any of the steps above, you can refer to the instructions for [creating a new MongoDB database deployment](https://www.mongodb.com/docs/atlas/getting-started/#create-a-database-user-for-your-cluster) in the docs, particularly until Step 4.
## Step 3: Load sample dataset
Once the database deployment is complete, you might want to load some sample data for the cluster. You can do this by heading to the `Database` tab and under the newly created Cluster, click on the `...` that opens an option to `Load Sample Dataset`. This may take a few seconds.

At this stage, we have created a Hasura Cloud project and a MongoDB Atlas database.
## Step 4: Connect Hasura to MongoDB
To connect Hasura to MongoDB, first add the Hasura Cloud IP address to your MongoDB cluster. To do that, navigate to the Network Access page (under Security) from the Atlas dashboard.

Click on `ADD IP ADDRESS` and enter the `Hasura Cloud IP` that you obtained from the Hasura Cloud dashboard in the first step.

Once completed, Hasura Cloud should be able to communicate with the MongoDB Atlas instance. The next step is to get the database connection string.
On the Atlas dashboard, head to the `Database page` and click on `Connect` next to the Hasura cluster created some steps back. Choose the `Drivers` option.

You will get a popup with the connection string details. Copy the connection string for the database, which will be similar to this format:
```bash
mongodb+srv://praveen:<password>@hasura.1oyflxi.mongodb.net/?retryWrites=true&w=majority
```
Note that you need to replace `<password>` with the actual password of the database user that you created earlier.
You can access the Database Users from the Database Access tab under the Security section of the left navigation menu. Remember that the database user needs to have `atlasAdmin` permission for the connection to work.
Now, move back to the Hasura Cloud dashboard for the next step.
As you are on the Connect Existing Database for MongoDB page, enter the values for the name of the database as `mongodb`, the connection string copied from the previous step. This instance comes with a sample database called `sample_mflix`. Enter that under the `db` config.

Finally, click on `Connect Database` and you are all set with the connection of Hasura and MongoDB, all hosted on their respective Cloud instances.
## Step 5: Generate a high-performance GraphQL API
You can generate an API instantly for the sample database that was loaded to MongoDB by going to the mongodb -> Manage page on Hasura Console.

Review the collections from the sample database shown on this page. For example, you can see collections such as users, theaters, movies, comments, sessions, and embedded_movies. Now you can Track them to make sure Hasura generates the GraphQL (and REST) API for the collections.
Start by tracking the movies collection. Click on the Track button next to the movies collection.
In this step, you’ll need to indicate to Hasura the structure of the JSON object so that Hasura can inspect it and generate a GraphQL schema for it.
Insert the following JSON as input:
```json
{
"_id": {
"$oid": "573a1390f29313caabcd42e8"
},
"plot": "A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.",
"genres": [
"Short",
"Western"
],
"runtime": {
"$numberInt": "11"
},
"cast": [
"A.C. Abadie",
"Gilbert M. 'Broncho Billy' Anderson",
"George Barnes",
"Justus D. Barnes"
],
"poster": "https://m.media-amazon.com/images/M/MV5BMTU3NjE5NzYtYTYyNS00MDVmLWIwYjgtMmYwYWIxZDYyNzU2XkEyXkFqcGdeQXVyNzQzNzQxNzI@._V1_SY1000_SX677_AL_.jpg",
"title": "The Great Train Robbery",
"fullplot": "Among the earliest existing films in American cinema - notable as the first film that presented a narrative story to tell - it depicts a group of cowboy outlaws who hold up a train and rob the passengers. They are then pursued by a Sheriff's posse. Several scenes have color included - all hand tinted.",
"languages": [
"English"
],
"released": {
"$date": {
"$numberLong": "-2085523200000"
}
},
"directors": [
"Edwin S. Porter"
],
"rated": "TV-G",
"awards": {
"wins": {
"$numberInt": "1"
},
"nominations": {
"$numberInt": "0"
},
"text": "1 win."
},
"lastupdated": "2015-08-13 00:27:59.177000000",
"year": {
"$numberInt": "1903"
},
"imdb": {
"rating": {
"$numberDouble": "7.4"
},
"votes": {
"$numberInt": "9847"
},
"id": {
"$numberInt": "439"
}
},
"countries": [
"USA"
],
"type": "movie",
"tomatoes": {
"viewer": {
"rating": {
"$numberDouble": "3.7"
},
"numReviews": {
"$numberInt": "2559"
},
"meter": {
"$numberInt": "75"
}
},
"fresh": {
"$numberInt": "6"
},
"critic": {
"rating": {
"$numberDouble": "7.6"
},
"numReviews": {
"$numberInt": "6"
},
"meter": {
"$numberInt": "100"
}
},
"rotten": {
"$numberInt": "0"
},
"lastUpdated": {
"$date": {
"$numberLong": "1439061370000"
}
}
},
"num_mflix_comments": {
"$numberInt": "0"
}
}
```
Alternatively, if you want to copy these objects from your Mongo collections directly, head to the Collections tab under the Database section.

Click on the `Validate` button to validate the JSON document. In the next step, you will see the models derived from this document. Finally, click on the `Track Collection` button.

## Step 6: Try out GraphQL queries
Once you track the collection, you should navigate to the API Explorer page on the Hasura Console to start trying out some GraphQL queries. Execute the following GraphQL query inside the GraphQL interface.
```graphql
query {
movies (limit: 10, order_by: { released: desc }) {
_id
title
released
imdb {
rating {
numberDouble
}
}
}
}
```
We are trying to fetch 10 movies, sorted by released, descending. You will get a JSON response on the right as you execute the query by clicking the `play` button.

And voilà! A GraphQL API for the movies collection is now tested and ready for consumption. Play around with different queries as you see them on the Explorer tab on the left sidebar. You can repeat this for tracking more collections like comments, users, theaters, etc., and get APIs generated for all of them.
## How is the GraphQL API highly performant?
Hasura's instant generation of the GraphQL API for collections significantly minimizes the need for boilerplate code, which would otherwise be required in the form of GraphQL resolvers on any server.
Ensuring that both the database and the API reside in the same region mitigates latency concerns. However, let's delve deeper into the mechanics of query execution behind the scenes. It essentially revolves around these key factors:
### 1: Database pushdown with query optimization
Hasura operates as a compiler that receives a GraphQL query, enriches it with predicates as part of the query, and then delegates the query with projection, relationships, and authorization rules to the database to handle the workload. This approach circumvents server-side data processing and capitalizes on the database's capabilities to achieve high efficiency and performance.
Given GraphQL's inherent capability for clients to specify their desired data, it becomes imperative to retrieve only the exact fields requested by the client. Hasura achieves this by compiling the query with projection. In the absence of Hasura, a typical query might be suboptimal, resulting in fetching unnecessary data (more data than required).

### 2: Usage of aggregation pipelines
Let’s analyze the query that is generated by Hasura. For the example, GraphQL query that we used above, click on the Analyze button on the GraphiQL section of the API Explorer page.
You’ll see that the query execution plan looks like this:
```json
{
"aggregate": "movies",
"pipeline": [
{
"$sort": {
"released": -1
}
},
{
"$limit": 10
},
{
"$replaceWith": {
"released": {
"$dateToString": {
"date": "$released"
}
},
"_id": "$_id",
"imdb": {
"$cond": {
"if": "$imdb",
"then": {
"rating": {
"$cond": {
"if": "$imdb.rating",
"then": {
"numberDouble": "$imdb.rating.numberDouble"
},
"else": null
}
}
},
"else": null
}
},
"title": "$title"
}
}
],
"cursor": {}
}
```
You can see the usage of aggregation pipelines for high performance.
Iterating on the API with updates to collections
Updating the structure of a document in a collection is a straightforward process with Hasura. Simply adjust the Hasura metadata to include or exclude the modified fields. The schema's flexibility allows you to update the logical model to incorporate API changes seamlessly. No database migrations are necessary; — just add or remove fields from the metadata to reflect in the API.
## Summary
The integration of MongoDB with Hasura's GraphQL Engine introduces a heightened level of efficiency and scalability for developers. Harnessing Hasura's ability to create a unified GraphQL API from varied data sources, developers can swiftly expose MongoDB data through a secure, high-performance, and extensively customizable GraphQL API.
## Resources to learn more about the integration.
- [Hasura docs for MongoDB Atlas integration](https://hasura.io/docs/latest/databases/mongodb/mongodb-atlas/)
- [Running Hasura and MongoDB locally](https://hasura.io/docs/latest/databases/mongodb/docker/)
- [It should’ve been MongoDB all along!](https://www.youtube.com/watch?v=to9_hFLcw8Y)
- [Hasura Discord server](https://hasura.io/discord)
| praveenweb |
1,900,494 | BTC RECOVERY MADE EASY | Picture this: you're sitting at your computer, feeling like a tech-savvy genius, as you watch the... | 0 | 2024-06-25T19:40:10 | https://dev.to/joe_matthew_65db13dbbd7c4/btc-recovery-made-easy-3oih | Picture this: you're sitting at your computer, feeling like a tech-savvy genius, as you watch the value of your Bitcoin steadily rise. It's like watching a thrilling roller coaster ride, but with dollar signs instead of loops. Life couldn't be better. But then, disaster strikes. In a moment of sheer panic, you realize that your precious Bitcoin has vanished into thin air. Poof! Gone. Cue the heart palpitations and the distinct feeling of wanting to crawl into a hole and never emerge again. How could this happen? Losing Bitcoin is more than just a financial setback. It's like misplacing the key to a vault filled with potential wealth. The urgency to recover those elusive coins becomes all-consuming. Whether your Bitcoin was stolen, lost due to a technical glitch, or simply misplaced in the vast abyss of the internet, you need help. And you need it fast. Because in the world of cryptocurrency, time is money, and every minute counts. Losing Bitcoin can feel like a swift kick to the gut. It's not just the financial loss that stings, but also the emotional toll it takes. You start questioning your own abilities, your decision-making skills, and maybe even your faith in humanity. That's where professional Bitcoin recovery services step in. They have the knowledge, experience, and the magical powers (okay, not really magical, but close) needed to track down and retrieve your precious digital treasure. Here we have SPYHOST CYBER SECURITY COMPANY’s super heroes. Helping people like you restore what's properly yours is their mission, and they accomplish it with a touch of magic, SPYHOST CYBER SECURITY COMPANY’s staff is an impressive group. They've refined their abilities in the shadowy realm of bitcoin recovery, always staying one step ahead of the hackers, con artists, and general miscreants that lurk on the internet. They are the ideal squad to have on your side because they possess a great deal of technical skill together with. Once you've entrusted your Bitcoin recovery mission to SPYHOST CYBER SECURITY COMPANY, they kick things off with an initial consultation. They'll listen to your story, ask the right questions, and assess the situation. Consider them your personal therapists for Bitcoin-related trauma. Reach out to SPYHOST CYBER SECURITY COMPANY with the given information. Email: Spyhost@cyberdude.com , whatsapp + 1(571) 478-7636
| joe_matthew_65db13dbbd7c4 | |
1,900,385 | Interpreting Benchmarks and Evaluations in LLMs | Welcome to the era of Large Language Models (LLMs). If you've heard terms like "benchmarks" or... | 0 | 2024-06-25T19:38:54 | https://dev.to/jivaniyash/interpreting-benchmarks-and-evaluations-in-llms-312h | beginners, llm | Welcome to the era of Large Language Models (LLMs). If you've heard terms like "benchmarks" or "evaluations" and wondered what they mean & how to interpret them in the context of LLMs, you're in the right place. Let's break down these concepts to understand them.
## Benchmarks
Benchmarks refer to standardized tests or tasks in the form of datasets used to evaluate and compare the performance of different models. These benchmarks often include various language understanding and generation tasks, such as text completion, question answering, and summarization. Benchmarks provide a measure of how well an LLM performs compared to others. Some of the benchmarks used to evaluate LLMs are -
1. **General Language Understanding Evaluation (GLUE)** benchmark is a collection of 9 natural language understanding tasks
2. **MMLU (Massive Multitask Language Understanding)** is a benchmark to measure knowledge acquired during pretraining. It covers 57 subjects across STEM
3. **HumanEval** focuses on whether the LLM's generated code works as intended
Detailed information can be found in [2] & [3].
## Evaluations
Evaluation refers to measuring and assessing a model's performance and effectiveness in how accurately the model can predict or generate the next word in a sentence, understand context, summarize data, and respond to queries. Evaluation is crucial because it helps determine the model's strengths and weaknesses, and provides insights into areas of improvement. There are 2 different ways to compute metrics scores
1. Statistical Scorer
These are purely number-based scorers - i.e. they don't consider semantics into account. Some of these are -
a. **BLEU (BiLingual Evaluation Understudy)** evaluates the output of LLM application against annotated ground truths by calculation precision for each matching n-gram between actual & predicted outputs.
b. **ROUGE (Recall-Oriented Understudy for Gisting Evaluation)** is primarily used for evaluating text summaries from NLP models and calculates recall by comparing the overlap of n-grams between LLM outputs and expected outputs.
2. Model-Based Scorer
These are NLP-based scorer that takes semantics into account. Some of these are -
a. **BLEURT(Bilingual evaluation understudy with Representations from Transformers)**, often used for machine translation, uses pre-trained models like BERT to score LLM outputs on some expected outputs
b. **NLI(Natural Language Inference)** uses the NLP classification model to classify whether an LLM output is logically consistent (entailment), contradictory, or unrelated (neutral) with respect to a given reference text.
Detailed information can be found in [4].
---
After undergoing the benchmark’s evaluation, models are usually awarded a score from 0 to 100. These are the numbers you usually see when companies publish along with their LLM model to compare other models evaluated on the benchmark.
## References
1. [Turing](https://www.turing.com/resources/understanding-llm-evaluation-and-benchmarks)
2. [Papers with Code](https://paperswithcode.com/datasets)
3. [HumanLoop](https://humanloop.com/blog/llm-benchmarks)
4. [Confident-AI](https://www.confident-ai.com/blog/llm-evaluation-metrics-everything-you-need-for-llm-evaluation)
| jivaniyash |
1,900,492 | lazy_fred / FRED API Wrapper | Ever want to pull ALL of the most popular econometric data that you can from the St. Louis FRED... | 0 | 2024-06-25T19:38:38 | https://dev.to/jjmcguff/lazyfred-fred-api-wrapper-281a | Ever want to pull ALL of the most popular econometric data that you can from the St. Louis FRED timeseries data? Now you can!
https://github.com/Jmetrics86/lazy_fred
| jjmcguff | |
1,900,491 | Top 7 Featured DEV Posts of the Week | Welcome to this week's Top 7, where the DEV editorial team handpicks their favorite posts from the... | 0 | 2024-06-25T19:38:26 | https://dev.to/devteam/top-7-featured-dev-posts-of-the-week-3jj5 | top7 | _Welcome to this week's Top 7, where the DEV editorial team handpicks their favorite posts from the previous week._
Congrats to all the authors that made it onto the list 👏
{% embed https://dev.to/allieoopz/mike-mcquaid-on-15-years-of-homebrew-2oi7 %}
Allison shares an interview with Mike McQuaid, a project leader and longest tenured maintainer of Homebrew, a project utilized by tens of millions of developers.
---
{% embed https://dev.to/cometkim/dealing-with-unicode-string-done-right-and-better-2nei %}
Hyeseong created a library to handle Unicode grapheme clusters and documents the process of creating, optimizing, and testing a high-quality library.
---
{% embed https://dev.to/jessicagarson/choosing-between-an-index-level-api-a-query-an-aggregation-or-esql-in-elasticsearch-4668 %}
Jessica provides a comprehensive guide on selecting the appropriate method for data retrieval in Elasticsearch, comparing index-level API, queries, aggregations, and ESQL.
---
{% embed https://dev.to/isaachagoel/are-sync-engines-the-future-of-web-applications-1bbi %}
Isaac explores the potential of sync engines as a foundational technology for the future of web applications.
---
{% embed https://dev.to/m4xshen/how-i-grew-my-open-source-project-to-1k-stars-3mk2 %}
Max shares his journey and strategies for growing his open-source project to 1,000 stars on GitHub.
---
{% embed https://dev.to/magnificode/some-ux-design-principles-everyone-should-know-293k %}
Dominic outlines essential UX design principles that are crucial for creating user-friendly and engaging digital products.
---
{% embed https://dev.to/hetarth02/i-made-my-own-json-parser-4902 %}
Hetarth shares his experience and process of building a custom JSON parser from scratch, highlighting key challenges and learnings.
_And that's a wrap for this week's Top 7 roundup! 🎬 We hope you enjoyed this eclectic mix of insights, stories, and tips from our talented authors. Keep coding, keep learning, and stay tuned to DEV for more captivating content and [make sure you’re opted in to our Weekly Newsletter] (https://dev.to/settings/notifications) 📩 for all the best articles, discussions, and updates._ | thepracticaldev |
1,900,398 | Day 6 of 90 Days of DevOps: Dockerizing a Node.js App | Today, I tackled the process of Dockerizing a Node.js application, an essential skill in the DevOps... | 0 | 2024-06-25T19:37:29 | https://dev.to/arbythecoder/day-6-of-90-days-of-devops-dockerizing-a-nodejs-app-2fam | docker, node, devops, containers | Today, I tackled the process of Dockerizing a Node.js application, an essential skill in the DevOps toolkit.
Dockerization allows for consistent environments across various stages of development, testing, and production,
ensuring that applications run smoothly regardless of where they are deployed. However, this journey wasn't without its challenges!
#### Steps Taken
**1. Setting Up the Project Directory:**
First, I created a new directory for my Node.js application.
```sh
mkdir day6docker
cd day6docker
```
**2. Initializing the Node.js Project:**
Next, I initialized a new Node.js project and set up a basic Express server.
```sh
npm init -y
```
Created a `server.js` file:
```js
const express = require("express");
const path = require("path");
const axios = require("axios");
const morgan = require("morgan");
const app = express();
const morganMiddleware = morgan(
":method :url :status :res[content-length] - :response-time ms",
{
stream: {
write: message => console.log(message.trim()),
},
}
);
app.use(morganMiddleware);
app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "pug");
async function getRandomJoke() {
const response = await axios.get("https://api.chucknorris.io/jokes/random");
return response.data;
}
app.get("/", async (req, res, next) => {
try {
const response = await getRandomJoke();
res.render("home", {
title: "Random Chuck Norris Jokes",
joke: response,
});
} catch (err) {
next(err);
}
});
app.get("/joke", async (req, res, next) => {
try {
const response = await getRandomJoke();
res.json(response);
} catch (err) {
next(err);
}
});
app.use(function (err, req, res, next) {
console.error(err);
res.set("Content-Type", "text/html");
res.status(500).send("<h1>Internal Server Error</h1>");
});
const server = app.listen(process.env.PORT || 4000, () => {
console.log(`chucknorris server started on port: ${server.address().port}`);
});
function cleanupAndExit() {
server.close(() => {
console.log("chucknorris server closed");
process.exit(0);
});
}
process.on("SIGTERM", cleanupAndExit);
process.on("SIGINT", cleanupAndExit);
```
Installed Express:
```sh
npm install express
```
**3. Creating a Dockerfile:**
I then created a Dockerfile to define the image.
```Dockerfile
# Use the official Node.js image.
FROM node:14
# Create and change to the app directory.
WORKDIR /app
# Copy application dependency manifests to the container image.
COPY package*.json ./
# Install dependencies.
RUN npm install
# Copy local code to the container image.
COPY . .
# Run the web service on container startup.
CMD [ "node", "server.js" ]
# Inform Docker that the container listens on the specified network ports at runtime.
EXPOSE 3000
```
**4. Building the Docker Image:**
With the Dockerfile set up, I built the Docker image.
```sh
docker build -t my-node-app .
```
**5. Running the Docker Container:**
Finally, I ran the Docker container.
```sh
docker run -d -p 3000:3000 my-node-app
```
#### Challenges and Solutions
**Challenge 1: Dependency Issues**
Initially, I faced issues with my Node modules. My PowerShell commands weren't recognized properly. To resolve this, I used the following commands to clean up my environment and reinstall dependencies:
```powershell
Remove-Item -Recurse -Force .\node_modules
Remove-Item -Force .\package-lock.json
npm install
```
When faced with vulnerabilities, I used:
```powershell
npm audit fix
npm audit fix --force
```
**Challenge 2: Image Not Found and Authorization Errors**
When running the Docker container, I encountered errors indicating that the image wasn't found locally and pull access was denied.
To fix this, I either had to build the image from the Dockerfile or pull it from a repository:
**Option A: Build the Image**
```sh
docker build -t my-node-app .
```
**Option B: Pull the Image**
```sh
docker pull <username>/my-node-app:latest
```
**Challenge 3: Docker Container Issues**
On running the container, it initially failed to start. Checking the logs showed a missing module error. This was solved by ensuring all necessary files were included in the Docker context and correctly referenced.
#### Conclusion
Dockerizing an application, while challenging at times, is incredibly rewarding. It ensures that your application can run anywhere, from a local machine to a production server, with the same environment and dependencies. Mastering this skill is a significant step in the journey towards becoming a proficient DevOps engineer.
See you on Day 7 in a bit – it's not easy, but we move! | arbythecoder |
1,900,490 | Architect level: Introduction to React | Overview of React What is React? React is a declarative, component-based... | 0 | 2024-06-25T19:33:44 | https://dev.to/david_zamoraballesteros_/architect-level-introduction-to-react-3ai8 | react, webdev, javascript, programming | ## Overview of React
### What is React?
React is a declarative, component-based JavaScript library used to build user interfaces. Maintained by Facebook, React facilitates the creation of fast, scalable, and maintainable applications. It emphasizes reusable components, which encapsulate their own logic and rendering. At its core, React employs a virtual DOM to enhance performance by minimizing direct DOM manipulations.
### History and Evolution of React
React was introduced by Facebook in 2013, primarily to address performance and maintenance challenges in their complex applications. Over the years, React has seen significant enhancements that have cemented its place as a leading tool for UI development.
#### Key Milestones:
- **2013:** Initial release of React, introducing the virtual DOM and component-based architecture.
- **2015:** Launch of React Native, extending React principles to mobile development.
- **2016:** Introduction of React Fiber, a reimplementation of React's core algorithm to improve performance and provide new capabilities.
- **2017:** Release of React 16 (Fiber), featuring error boundaries, fragments, and portals.
- **2019:** Introduction of Hooks, which enabled state and lifecycle features in functional components, simplifying code reuse and improving readability.
### Comparison with Other Frameworks/Libraries
#### Angular:
- **Comprehensive Framework:** Angular, by Google, provides a full-featured solution with tools like two-way data binding, dependency injection, and an integrated templating system.
- **Opinionated Structure:** Angular's strong conventions and comprehensive nature make it ideal for large projects requiring strict structure but can be cumbersome for smaller, flexible projects.
#### Vue:
- **Progressive Framework:** Vue offers a balance between Angular and React, combining a simple core with powerful features and an approachable learning curve.
- **Flexibility and Integration:** Vue's flexibility makes it suitable for both small and large projects, allowing incremental adoption in existing applications.
### Why Choose React?
### Benefits of Using React
1. **Component-Based Architecture:**
- React promotes modular development through encapsulated components, enhancing maintainability and scalability. This is crucial for large applications where reusability and isolation of concerns are paramount.
2. **Virtual DOM:**
- React’s virtual DOM optimizes performance by reducing direct DOM manipulations. It efficiently updates the real DOM, ensuring fast and smooth user interactions even in complex applications.
3. **Declarative UI:**
- React’s declarative paradigm simplifies the development process. Developers can describe how the UI should look for any given state, and React handles the rendering, leading to predictable and easily debuggable code.
4. **Rich Ecosystem and Community:**
- React boasts a vast ecosystem, including state management libraries like Redux and MobX, form handling tools like Formik and React Hook Form, and numerous third-party components. The extensive community support ensures continuous improvement and a wealth of resources.
5. **Cross-Platform Development:**
- React Native allows developers to apply their React skills to mobile development, promoting code reuse across web and mobile platforms, which accelerates development cycles and reduces maintenance efforts.
6. **Backward Compatibility and Stability:**
- React’s focus on backward compatibility ensures that new features and updates can be integrated without significant rewrites. This stability is vital for long-term projects and enterprise-level applications.
### Case Studies of Successful React Applications
1. **Facebook:**
- React was initially developed for Facebook’s News Feed to address performance and maintainability challenges. It now powers Facebook’s entire web application, ensuring a dynamic and responsive user experience at scale.
2. **Instagram:**
- Instagram, a subsidiary of Facebook, leverages React for its web interface. React’s efficient rendering and modular architecture help deliver a seamless and interactive user experience, essential for a social media platform.
3. **Airbnb:**
- Airbnb uses React to build and maintain its web platform. React’s component-based architecture and performance optimizations enable Airbnb to create reusable UI components, ensuring consistency and maintainability across its application.
4. **Netflix:**
- Netflix employs React for its client-side interface, enhancing startup speed and runtime performance. React’s efficient rendering and modular architecture enable Netflix to deliver a smooth and responsive experience to millions of users.
5. **Uber:**
- Uber relies on React for its web application, utilizing its component-based structure to build scalable and maintainable user interfaces. React’s performance optimizations are crucial for Uber’s real-time functionalities and dynamic user interactions.
6. **WhatsApp Web:**
- WhatsApp Web, another Facebook product, utilizes React to provide a seamless messaging experience on desktop browsers. React’s efficient state management and rendering capabilities ensure a responsive and reliable user interface.
## Conclusion
For architect-level developers, mastering React and understanding its principles and ecosystem is crucial for building modern, high-performance web applications. React’s component-based architecture, virtual DOM, and strong community support make it a powerful tool for developing scalable and maintainable UIs. Leveraging React’s benefits allows you to design sophisticated applications and lead successful projects like those at Facebook, Instagram, Airbnb, Netflix, and Uber. With React, you can drive innovation, ensure efficient development processes, and deliver high-quality user experiences in any application. | david_zamoraballesteros_ |
1,900,489 | Key Elements of HTML: A Guide for Aspiring Web Developers | Understanding HTML is fundamental to mastering web development. Here, I’ll highlight the key elements... | 0 | 2024-06-25T19:32:47 | https://dev.to/ridoy_hasan/key-elements-of-html-a-guide-for-aspiring-web-developers-34aj | webdev, html, learning, programming |
Understanding HTML is fundamental to mastering web development. Here, I’ll highlight the key elements of HTML that every developer should know:
### **HTML Key Elements**
**1. `<html>`**: The root element, encapsulating all HTML content on a page.
**2. `<head>`**: Contains meta-information about the HTML document, such as its title and links to CSS files and scripts.
**3. `<title>`**: Sets the title of the web page, displayed in the browser tab.
**4. `<body>`**: The main container for all visible content, including text, images, and interactive elements.
**5. `<header>`**: Defines introductory content, typically containing navigation links and site titles.
**6. `<nav>`**: Represents a section with navigation links, facilitating user movement across the site.
**7. `<main>`**: Signifies the central content of a document, unique and essential for accessibility.
**8. `<section>`**: Organizes content into thematic groups, enhancing readability and structure.
**9. `<article>`**: Encloses independent, self-contained content such as articles, blogs, or news stories.
**10. `<footer>`**: Defines the footer for a document or section, typically containing contact info or links.
**11. `<div>`**: A versatile container for grouping and styling elements with CSS.
**12. `<p>`**: Defines paragraphs, the building blocks for text content.
**13. `<a>`**: Creates hyperlinks, enabling navigation between different pages or sites.
**14. `<img>`**: Embeds images, requiring the `src` attribute to specify the image source.
**15. `<form>`**: Structures interactive forms, enabling user input and data submission.
### **Conclusion**
Mastering these HTML elements is crucial for building well-structured, accessible, and visually appealing web pages. Whether you’re just starting out or looking to refine your skills, a solid understanding of HTML is indispensable for any web developer. Keep exploring, keep coding, and continue building amazing web experiences!
connect me on LinkedIn -
https://www.linkedin.com/in/ridoy-hasan7
#WebDevelopment #HTML #LearnHTML #CodingBasics #WebDesign #TechSkills #WebDevJourney #LinkedInLearning #ProfessionalGrowth | ridoy_hasan |
1,900,488 | Lead level: Introduction to React | Overview of React What is React? React is a declarative, component-based... | 0 | 2024-06-25T19:31:59 | https://dev.to/david_zamoraballesteros_/lead-level-introduction-to-react-4613 | webdev, javascript, programming, react | ## Overview of React
### What is React?
React is a declarative, component-based JavaScript library for building user interfaces, primarily maintained by Facebook. It's designed to help developers create fast, scalable, and maintainable UIs for web applications. React promotes the development of reusable components that encapsulate their own logic and rendering, making it easier to manage complex applications. The core concept of React revolves around the virtual DOM, which optimizes UI rendering and improves performance.
### History and Evolution of React
React was introduced by Facebook in 2013 to address the challenges of building dynamic and high-performance user interfaces. Its unique approach to UI development quickly gained traction among developers.
#### Key Milestones:
- **2013:** React was open-sourced, introducing the concept of the virtual DOM and a component-based architecture.
- **2015:** React Native was released, allowing developers to use React for mobile app development.
- **2016:** React Fiber was announced, a complete rewrite of React's core algorithm to improve performance and add new features.
- **2017:** React 16 (Fiber) was released, introducing new concepts such as error boundaries, fragments, and portals.
- **2019:** Introduction of React Hooks, enabling state and lifecycle management in functional components and promoting code reuse and simplicity.
### Comparison with Other Frameworks/Libraries
#### Angular:
- **Comprehensive Framework:** Angular, developed by Google, is a full-featured framework that offers a wide range of built-in features, such as two-way data binding, dependency injection, and a powerful templating system.
- **Structured and Opinionated:** Angular's strong conventions and structure make it ideal for large teams and complex projects but can be restrictive for smaller, more flexible projects.
#### Vue:
- **Progressive Framework:** Vue is designed to be incrementally adoptable, making it easy to integrate into projects of any size. It combines features from both Angular and React, offering a gentle learning curve.
- **Flexibility and Simplicity:** Vue's simplicity and ease of integration make it a popular choice for both small and large-scale applications, providing a balance between structure and flexibility.
### Why Choose React?
### Benefits of Using React
1. **Component-Based Architecture:**
- React's component-based architecture encourages the creation of reusable UI components that manage their own state and rendering logic. This modular approach enhances code maintainability, scalability, and readability, which is essential for large-scale applications.
2. **Virtual DOM:**
- React's virtual DOM optimizes rendering performance by minimizing direct manipulations of the real DOM. By calculating the most efficient way to update the UI based on state changes, React ensures a fast and responsive user experience.
3. **Declarative UI:**
- React's declarative paradigm simplifies UI development by allowing developers to describe how the UI should look for any application state. This abstraction makes the code more predictable, easier to debug, and reduces the complexity of managing UI states.
4. **Rich Ecosystem and Community:**
- React boasts a vast ecosystem of tools, libraries, and community support. From state management solutions (Redux, MobX) to form handling libraries (Formik, React Hook Form), React's ecosystem provides robust solutions for various development needs.
5. **Cross-Platform Development:**
- React Native extends React's component-based approach to mobile app development, promoting code reuse across web and mobile platforms. This cross-platform capability accelerates development cycles and reduces maintenance efforts.
6. **Backward Compatibility and Stability:**
- React's commitment to backward compatibility ensures that upgrades and new features can be adopted without significant rewrites. This stability is crucial for long-term projects and enterprise applications.
### Case Studies of Successful React Applications
1. **Facebook:**
- React was initially developed for Facebook's News Feed to address performance and maintainability challenges. Today, React powers the entire Facebook web application, providing a dynamic and responsive user experience at scale.
2. **Instagram:**
- Instagram, a subsidiary of Facebook, leverages React to manage its web interface. React's efficient rendering and component-based architecture help deliver a seamless and interactive user experience, crucial for a social media platform.
3. **Airbnb:**
- Airbnb uses React to build and maintain its web platform, benefiting from React's modularity and performance optimizations. React's component-based architecture allows Airbnb to create reusable UI components, ensuring consistency and maintainability across the application.
4. **Netflix:**
- Netflix employs React for its client-side user interface, enhancing startup speed and runtime performance. React's efficient rendering and modular architecture enable Netflix to deliver a smooth and responsive experience to millions of users worldwide.
5. **Uber:**
- Uber relies on React for its web application, utilizing its component-based structure to build scalable and maintainable user interfaces. React's performance optimizations are crucial for Uber's real-time functionalities and dynamic user interactions.
6. **WhatsApp Web:**
- WhatsApp Web, another Facebook product, utilizes React to provide a seamless messaging experience on desktop browsers. React's efficient state management and rendering capabilities ensure a responsive and reliable user interface.
## Conclusion
For lead developers, a deep understanding of React's principles and ecosystem is essential for building modern, high-performance web applications. React's component-based architecture, virtual DOM, and robust community support make it a powerful tool for developing scalable and maintainable UIs. Leveraging React's benefits allows you to build sophisticated applications and lead successful projects like those at Facebook, Instagram, Airbnb, Netflix, and Uber. With React, you can drive innovation, ensure efficient development processes, and deliver high-quality user experiences. | david_zamoraballesteros_ |
1,900,487 | Fundamental local Git not working. | For reasons beyond the scope of this discussion thread, I have found the need to install git locally... | 0 | 2024-06-25T19:31:09 | https://dev.to/xarzu/fundamental-local-git-not-working-1idm | For reasons beyond the scope of this discussion thread, I have found the need to install git locally on my work windows 10 computer. But from the command line, the basic commands are not recognized. For example:
`git config`
gets the response:
```
'git' is not recognized as an internal or external command,
operable program or batch file.
```
Can anyone please offer suggestions or next steps I should try?
| xarzu | |
1,900,486 | Senior level: Introduction to React | Overview of React What is React? React is a declarative, component-based... | 0 | 2024-06-25T19:31:02 | https://dev.to/david_zamoraballesteros_/senior-level-introduction-to-react-4224 | react, webdev, javascript, programming | ## Overview of React
### What is React?
React is a declarative, component-based JavaScript library for building user interfaces, developed and maintained by Facebook. Its primary goal is to enable developers to create large-scale, high-performance web applications that are easy to manage and scale. React encourages the development of reusable UI components that can manage their own state, allowing for a more modular and maintainable codebase.
At its core, React utilizes a virtual DOM to optimize UI rendering. This approach minimizes direct DOM manipulations, improving performance and providing a more responsive user experience.
### History and Evolution of React
React was introduced in 2013 by Facebook to address the challenges they faced with building complex user interfaces. Its revolutionary virtual DOM concept and component-based architecture quickly gained popularity among developers.
#### Key Milestones:
- **2013:** Initial release of React, introducing the virtual DOM and component-based architecture.
- **2015:** Launch of React Native, extending React's principles to mobile app development.
- **2016:** Introduction of React Fiber, a complete rewrite of React's core algorithm, enhancing performance and adding new capabilities.
- **2017:** Release of React 16 (Fiber), featuring new concepts like error boundaries, fragments, and portals.
- **2019:** Introduction of Hooks, allowing functional components to manage state and lifecycle events, simplifying component logic and enhancing code reuse.
### Comparison with Other Frameworks/Libraries
#### Angular:
- **Comprehensive Framework:** Angular, developed by Google, is a complete solution offering a rich set of built-in features such as two-way data binding, dependency injection, and a powerful templating system.
- **Opinionated and Structured:** Angular's strong conventions and structure are beneficial for large teams and complex projects, but they can be restrictive for smaller, more flexible projects.
#### Vue:
- **Progressive Framework:** Vue is designed to be incrementally adoptable, making it easy to integrate into projects of any size. It offers a blend of Angular's and React's features, with a gentle learning curve.
- **Flexibility and Simplicity:** Vue's simplicity and ease of integration make it an excellent choice for both small and large-scale applications, providing a balance between the structured approach of Angular and the flexibility of React.
### Why Choose React?
### Benefits of Using React
1. **Component-Based Architecture:**
- React promotes a modular approach to UI development by breaking down interfaces into reusable components. This encapsulation of logic and rendering within components enhances code maintainability and scalability, making it easier to manage large applications.
2. **Virtual DOM:**
- React's virtual DOM optimizes rendering performance by minimizing direct manipulations of the real DOM. By calculating the most efficient way to update the UI based on state changes, React ensures a fast and responsive user experience.
3. **Declarative UI:**
- React's declarative nature allows developers to describe what the UI should look like for any application state, abstracting away the direct DOM manipulations. This results in more predictable and easier-to-debug code, reducing the complexity of managing UI states.
4. **Rich Ecosystem and Community:**
- React boasts a vast ecosystem of tools, libraries, and community support. From state management solutions (Redux, MobX) to form handling libraries (Formik, React Hook Form), React's ecosystem provides robust solutions for various development needs.
5. **Cross-Platform Development:**
- React Native extends React's component-based approach to mobile app development, enabling code reuse across web and mobile platforms. This cross-platform capability accelerates development cycles and reduces maintenance efforts.
6. **Backward Compatibility and Stability:**
- React's commitment to backward compatibility ensures that upgrades and new features can be adopted without significant rewrites. This stability is crucial for long-term projects and enterprise applications.
### Case Studies of Successful React Applications
1. **Facebook:**
- React was initially developed for Facebook's News Feed to address performance and maintainability challenges. Today, React powers the entire Facebook web application, providing a dynamic and responsive user experience at scale.
2. **Instagram:**
- Instagram, a subsidiary of Facebook, leverages React to manage its web interface. React's efficient rendering and component-based architecture help deliver a seamless and interactive user experience, crucial for a social media platform.
3. **Airbnb:**
- Airbnb uses React to build and maintain its web platform, benefiting from React's modularity and performance optimizations. React's component-based architecture allows Airbnb to create reusable UI components, ensuring consistency and maintainability across the application.
4. **Netflix:**
- Netflix employs React for its client-side user interface, enhancing startup speed and runtime performance. React's efficient rendering and modular architecture enable Netflix to deliver a smooth and responsive experience to millions of users worldwide.
5. **Uber:**
- Uber relies on React for its web application, utilizing its component-based structure to build scalable and maintainable user interfaces. React's performance optimizations are crucial for Uber's real-time functionalities and dynamic user interactions.
6. **WhatsApp Web:**
- WhatsApp Web, another Facebook product, utilizes React to provide a seamless messaging experience on desktop browsers. React's efficient state management and rendering capabilities ensure a responsive and reliable user interface.
## Conclusion
For senior developers, mastering React and understanding its evolution and ecosystem is critical for building modern, high-performance web applications. React's component-based architecture, virtual DOM, and strong community support make it an ideal choice for developing scalable and maintainable UIs. By leveraging React's benefits, you can build sophisticated applications and contribute to successful projects like those at Facebook, Instagram, Airbnb, Netflix, and Uber, driving innovation and efficiency in your development processes. | david_zamoraballesteros_ |
1,900,484 | Mid level: Introduction to React | Overview of React What is React? React is a JavaScript library designed for... | 0 | 2024-06-25T19:25:19 | https://dev.to/david_zamoraballesteros_/mid-level-introduction-to-react-452m | react, javascript, webdev, programming | ## Overview of React
### What is React?
React is a JavaScript library designed for building user interfaces, primarily for single-page applications where a dynamic and responsive experience is essential. Developed by Facebook, React focuses on the creation of reusable UI components, which function like JavaScript functions: they take input (props) and return a visual representation (UI).
At its core, React allows developers to construct complex UIs from isolated pieces of code called components. This modularity is one of React's key strengths, enabling better organization and reusability of code.
### History and Evolution of React
React was introduced by Facebook in 2013 to address issues they encountered while building complex, high-performance applications. Its innovative approach to UI development, particularly the virtual DOM, revolutionized how developers approached front-end architecture.
#### Key Milestones in React's Evolution:
- **2015:** React Native was released, allowing developers to use React for building mobile applications on iOS and Android.
- **2016:** React Fiber was announced, providing a complete rewrite of React's core algorithm to improve performance and add new features.
- **2017:** React 16 (Fiber) was released, bringing new features such as error boundaries, fragments, and portals.
- **2019:** Introduction of React Hooks, enabling state and lifecycle management in functional components, simplifying component logic and improving code reuse.
### Comparison with Other Frameworks/Libraries
#### Angular:
- **Full-Fledged Framework:** Angular, developed by Google, is a comprehensive framework offering a rich set of features out-of-the-box, including two-way data binding, dependency injection, and a powerful templating system.
- **Opinionated and Structured:** Angular's strong conventions can be advantageous for large teams and complex projects but might feel restrictive for smaller, more flexible projects.
#### Vue:
- **Progressive Framework:** Vue is designed to be incrementally adoptable, allowing developers to use it for small parts of their project and progressively scale up.
- **Simplicity and Flexibility:** Vue combines the best aspects of Angular and React, offering an approachable core library with optional plugins for routing and state management. Its simplicity makes it easy to integrate and use.
### Why Choose React?
### Benefits of Using React
1. **Component-Based Architecture:**
- React promotes building encapsulated components that manage their own state and rendering logic. This modular approach improves code maintainability and reusability, making it easier to scale applications.
2. **Virtual DOM:**
- React's virtual DOM enhances performance by minimizing direct manipulations of the browser's DOM. It calculates the most efficient way to update the real DOM based on changes in the application's state, leading to faster and smoother user experiences.
3. **Declarative UI:**
- React's declarative paradigm simplifies UI development. By describing how the UI should look for any application state, React automatically updates the UI to reflect the current state, reducing bugs and making code more predictable and easier to debug.
4. **Strong Ecosystem and Community:**
- With a vast array of tools, libraries, and community support, React's ecosystem is robust. Developers can find solutions, components, and libraries for almost any need, from state management (Redux, MobX) to form handling (Formik, React Hook Form).
5. **Cross-Platform Development:**
- React Native allows developers to leverage their React knowledge for mobile app development, promoting code reuse and faster development cycles across web and mobile platforms.
### Case Studies of Successful React Applications
1. **Facebook:**
- React was initially developed for Facebook's News Feed. Today, it powers the entire Facebook web application, providing a dynamic and responsive user experience. Facebook's use of React demonstrates its capability to handle complex, high-traffic applications.
2. **Instagram:**
- Instagram, another Facebook product, utilizes React to manage its web application. React's component-based architecture helps Instagram deliver a seamless and interactive user experience, especially for its real-time features.
3. **Airbnb:**
- Airbnb uses React to build and maintain its web interface, benefiting from React's modularity and performance optimizations. The ability to create reusable components enables Airbnb to maintain a consistent and performant user interface across its platform.
4. **Netflix:**
- Netflix employs React for its client-side user interface, improving startup speed and runtime performance. React's efficient rendering and component architecture enable Netflix to deliver a smooth and responsive experience to millions of users worldwide.
5. **Uber:**
- Uber relies on React for its web application, utilizing its component-based structure to build scalable and maintainable user interfaces. React's performance optimizations are crucial for Uber's real-time functionalities and dynamic user interactions.
## Conclusion
For mid-level developers, understanding React's fundamental principles and its ecosystem is crucial for building modern, high-performance web applications. React's component-based architecture, virtual DOM, and strong community support make it a powerful tool for developing scalable and maintainable UIs. As you continue to grow your skills, leveraging React's benefits will enable you to build sophisticated applications like those at Facebook, Instagram, and Airbnb, and contribute to the success of your projects. | david_zamoraballesteros_ |
1,900,483 | Commit vs. Rollback: Database Transaction Essentials | In the world of databases, transactions are akin to journeys—comprising a series of steps or... | 0 | 2024-06-25T19:25:07 | https://dev.to/asifzcpe/demystifying-database-transactions-how-commit-and-rollback-ensure-smooth-data-handling-2mo2 | mysql, commit, rollback, database | In the world of databases, transactions are akin to journeys—comprising a series of steps or operations performed as a single, cohesive unit of work. Whether you're booking a flight, ordering groceries online, or transferring funds between accounts, transactions play a vital role in ensuring that database operations are reliable, consistent, and resilient. Let's take on a journey through the commit and rollback processes in database transactions, exploring each step with relatable analogies to make the journey more understandable, followed by the technical details.
## The Commit Process

### 1. Initiating the Journey: Begin Transaction
#### Analogy:
Think of it as the moment you decide to embark on a trip. You gather your essentials and map out your route before setting off. This planning phase ensures that you're prepared for the journey ahead.
#### Technical Detail:
A transaction begins with the BEGIN TRANSACTION statement. This marks the start of a series of operations that must be executed atomically. All changes made during the transaction are initially tentative and only become permanent upon commit.
### 2. Logging the Voyage: Write-Ahead Logging (WAL)
#### Analogy:
Before setting sail, it's wise to create a list of everything you're bringing along. Similarly, the WAL records all changes made by the transaction in a log before they're applied to the database. This log serves as a safety net, allowing for recovery in case of unforeseen circumstances—much like referring back to your list if you forget something during your journey.
#### Technical Detail:
Before making any changes to the database, the system writes these changes to a write-ahead log (WAL). The WAL is a sequential record of all modifications. By logging changes before they are applied, the database can ensure durability and support recovery in case of a crash.
### 3. Planning the Itinerary: In-Memory Data Modification
#### Analogy:
With your journey underway, you begin planning your itinerary and mentally preparing for the adventure. It's akin to mapping out your route and making mental notes of the places you'll visit before physically setting foot on your journey.
#### Technical Detail:
Changes are initially made in-memory, within the database's buffer cache. This allows for quick response times and reduces the immediate need for disk I/O. The in-memory data structures are updated first, and these changes are later propagated to the disk.
### 4. Securing the Record: Log Flush
#### Analogy:
Just as you ensure your list is safely stored in your backpack before hitting the road, the database flushes the log entries to disk to ensure they're durably recorded. This step guarantees that there's a persistent record of the transaction's changes, providing a safety net in case of unexpected detours or interruptions along the way.
#### Technical Detail:
The log entries recorded in the WAL are flushed to disk to ensure their durability. This means writing the log entries from memory to stable storage, ensuring that they are not lost even if there is a system crash.
### 5. Confirming the Voyage: Commit Record
#### Analogy:
As you progress on your journey and decide to commit to the adventure, you officially confirm your plans by signing your name on a travel document. Similarly, in a database, a special commit record is written to the log to mark the transaction as complete. This commitment ensures that the changes made by the transaction are finalized and applied to the database.
#### Technical Detail:
A commit record is written to the WAL to indicate that the transaction has been successfully completed. This commit record marks the point at which all changes made by the transaction become permanent.
### 6. Ensuring Durability: Data Page Flush (Deferred)
#### Analogy:
While you've committed to your journey, you may not immediately load all your belongings onto the transport. Similarly, in a database, modified data pages in the buffer cache are eventually flushed to disk, but not necessarily immediately. This delayed flushing optimizes performance while still ensuring durability, much like waiting for the right moment to load your belongings for maximum efficiency.
#### Technical Detail:
While the commit ensures the changes are durable, the actual data pages containing the changes might not be immediately written to disk. The database employs a lazy writing strategy, flushing these pages to disk at a later time, optimizing for performance.
## The Rollback Process

### 1. Identifying Uncommitted Changes: Identifying Mistakes in Your List
#### Analogy:
Suppose you suddenly realize you've forgotten to pack something essential. You identify the items you haven't packed yet. In a database, this means identifying changes made by the transaction that need to be undone.
#### Technical Detail:
If a transaction needs to be rolled back, the database first identifies all changes made by the transaction that have not been committed. This involves scanning the WAL to find all operations that need to be undone.

### 2. Undo Log Entries: Erasing Mistakes
#### Analogy:
You refer back to your packing list to see what items you haven't yet packed and need to remove. Similarly, in a database, undo log entries are used to find information to undo each change made by the transaction.
#### Technical Detail:
The database uses the WAL to undo each change made by the transaction. For each operation recorded in the WAL, a corresponding undo operation is performed to revert the data to its previous state.

### 3. Apply Undo Operations: Fixing Mistakes
#### Analogy:
You unpack the items you previously packed incorrectly, ensuring you're only taking what you need for the trip. In a database, undo operations are applied to in-memory data structures to reverse the changes made by the transaction.
#### Technical Detail:
The database applies the undo operations to the in-memory data structures, effectively rolling back the changes. This ensures that the database is returned to its state prior to the start of the transaction.

### 4. Log Rollback: Recording the Change of Plans
#### Analogy:
You make a note in your travel log that you've decided not to proceed with the trip, keeping a record of the change in plans. Similarly, in a database, a rollback log entry indicates that the transaction was rolled back.
#### Technical Detail:
A rollback log entry may be written to indicate that the transaction has been rolled back. This helps in maintaining an accurate log for recovery purposes.

### 5. Release Locks: Freeing Resources
#### Analogy:
Any reservations or bookings you made for the trip are canceled, freeing up resources for others to use. In a database, releasing locks ensures that other transactions can access the database and make changes without any problems.
#### Technical Detail:
Any locks held by the transaction on database objects are released. This allows other transactions to access these objects and proceed with their operations.

### Conclusion:
In the domain of databases, transactions are like well-planned voyages. Just as you prepare for a trip by packing your essentials and mapping out your route, databases begin transactions by organizing the changes they need to make.
During transaction’s journey, data changes are logged so that nothing gets lost along the way. For example, this log acts as a safety net for databases helping them in recovering after something unexpected happens.
When it is time for a transaction to be committed, it’s just like finalizing plans and making them official. The database ensures all changes are securely saved.
However, if there is an error and a rollback is required it’s just like changing your mind about taking a journey after all. The database cancels out any modifications made by the transaction and restores everything back to how it was before.
Releasing locks at the end of a transaction is like canceling reservations freeing up resources for others to use.
Understanding these processes will help you maintain smooth running of your database systems, reliable data, consistent operations. Whether using apps or shopping online or managing finances those background processes matter which can keep thing running smoothly. Thus next time you communicate with a data base remember committing and rolling back- ensuring you
| asifzcpe |
1,900,686 | Engineering vs Craftsmanship | In the world of software development, two terms often arise when discussing the qualities of... | 0 | 2024-07-01T09:05:26 | https://rockit.zone/post/engineering-vs-craftsmanship/ | opinion, engineering, craftsmanship | ---
title: Engineering vs Craftsmanship
published: true
date: 2024-06-25 19:25:00 UTC
tags:
- opinion
- engineering
- craftsmanship
canonical_url: https://rockit.zone/post/engineering-vs-craftsmanship/
cover_image: https://rockit.zone/post/engineering-vs-craftsmanship/cover.png
---
In the world of software development, two terms often arise when discussing the qualities of experienced professionals: engineering and craftsmanship. While we sometimes use these terms interchangeably, they represent distinct skill sets and mindsets.
Emily Bache and Dave Farley published the video [What Is A Software Engineer? | Craftsmanship Movement Was A "Step Backwards"](https://www.youtube.com/watch?v=yHCds5IbKa4). It inspired me to write this post with a different opinion: combining the two approaches leads to superior software development.
<!--more-->
## The Engineer's Mindset

Software engineers have a systematic problem-solving approach, emphasizing **precision, efficiency, and scalability**. The following are some essential qualities of a software engineer:
- **Systematic Thinking:** Engineers approach problems with a structured mindset, breaking down complex issues into manageable components
- **Measurements and Metrics:** They make decisions based on quantitative data gathered from the system
- **Efficiency and Optimization:** They strive to create efficient algorithms and optimize code to ensure optimal performance
- **Scalability:** Engineers design systems that can handle growth, ensuring that software can smoothly scale as user demands increase
- **Reliability:** They prioritize building robust and reliable systems, often employing rigorous testing and validation techniques to minimize bugs and errors
- **Documentation and Standards:** Engineers follow industry standards and best practices, maintaining comprehensive documentation for future reference and collaboration
**In other words, engineers focus on building systems that satisfy functional and non-functional requirements. They achieve this by heavily relying on theoretical knowledge.**
Unfortunately, this mindset doesn't consider a crucial human element: the developer who'll maintain or understand the code.
## The Craftsman's Touch

The software craftsmanship movement emerged as a response to the perceived decline in software quality and the industrialization of software development. It emphasizes the **importance of quality, professionalism, and pride in one's work**. Key principles of software craftsmanship include:
- **Continuous Learning:** Craftsmen commit to continuous learning and improvement, staying updated with the latest practices and technologies.
- **Professionalism:** The movement advocates for a professional attitude towards software development, where developers take pride in their work and strive for excellence. It also includes communication with clients and teammates.
- **Collaboration and Mentorship:** Experienced craftsmen mentor less experienced developers, fostering a culture of knowledge sharing and collective growth.
- **Quality Focus:** They emphasize delivering high-quality software that meets user needs and is maintainable in the long term. Their toolkit includes maintaining code quality, refactoring, and TDD.
- **Community Engagement:** Active participation in the software development community through conferences, meetups, and online forums is encouraged to promote best practices and innovation.
**In summary, craftsmen focus on pragmatism and the human element in software development.** But even the most beautifully written code won't satisfy the clients if it doesn't perform well in production.
## Orthogonal Skillsets: A Symbiotic Relationship
While engineering and craftsmanship represent different aspects of software development, they are not mutually exclusive. In fact, they complement and strengthen each other, creating a holistic approach to software development. Here’s why combining the theoretical knowledge of an engineer and the pragmatism of a craftsman is essential:
- **Balanced Approach:** Integrating the engineer’s systematic thinking with the craftsman’s attention to detail results in well-rounded solutions that are both efficient and maintainable
- **Enhanced Collaboration:** Engineers and craftsmen bring unique perspectives to the table, fostering a collaborative environment where diverse ideas lead to innovative solutions
- **Professional Growth:** Developing skills in both areas allows professionals to grow more comprehensively, enhancing their ability to tackle a wide range of challenges
- **Product Success:** Combining the strengths of engineering and craftsmanship leads to higher-quality software that meets user needs while being reliable, scalable, and maintainable
- **Continuous Improvement:** Combining measurements with the strive for quality is a powerful combination that enables keeping a codebase healthy and maintainable
## How To Grow
Education (including universities and bootcamps) worldwide has traditionally focused on the engineering aspects of software development. Computer science programs often emphasize the theoretical and technical foundations for engineering robust and scalable systems. Here are some reasons for this focus:
- **Rigorous Curriculum:** University programs are designed to provide a solid grounding in computer science theory, algorithms, data structures, and systems design
- **Industry Demand:** There is a high demand in the industry for engineers who can build scalable, efficient, and reliable systems, driving universities to prioritize these skills
- **Research and Innovation:** Academic research often focuses on pushing the boundaries of what is technically possible, fostering a mindset of innovation and engineering excellence
- **Standardization and Accreditation:** University curricula are often standardized and accredited by professional bodies, emphasizing engineering competencies to ensure graduates meet industry standards
- **Lack of Legacy Experience:** During education, students often work on green-field projects that won't teach them the importance of maintainability or prepare them for the challenges of legacy codebases
While engineering focus is essential, it sometimes leaves gaps in the practical, hands-on skills cultivated through craftsmanship. Bridging this gap requires incorporating craftsmanship principles into the educational experience.
This is easier said than done. Luckier developers work for companies with a healthy culture that fosters the necessary skills. Alternatively, they involve external coaches to evolve their employees, for example, by onboarding the [SW Craftsmanship Dojo®](https://swcraftsmanshipdojo.com/).
Unfortunately, most craftsmen aren't that lucky. They gain their knowledge by learning from colleagues, reading, and personal experience. A non-comprehensive list of recommended books:
- [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship-ebook/dp/B001GSTOAM/)
- [The Clean Coder: A Code of Conduct for Professional Programmers](https://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers-ebook/dp/B0050JLC9Y/)
- [The Pragmatic Programmer: Your journey to mastery](https://www.amazon.com/Pragmatic-Programmer-journey-mastery-Anniversary-ebook/dp/B07VRS84D1/)
- [Refactoring: Improving the Design of Existing Code](https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature/dp/0134757599/)
- [Tidy First?](https://www.amazon.com/Tidy-First-Kent-Beck-ebook/dp/B0CL7ZMLWH/)
- [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164)
- [Code That Fits in Your Head: Heuristics for Software Engineering](https://www.amazon.com/Code-That-Fits-Your-Head/dp/0137464401)
Despite every difficulty and failure, we value every drop of sweat because each is a lesson learned and a step toward becoming a better professional.
## Conclusion
Craftsmanship isn't a step backward. By embracing both the structured, efficient mindset of an engineer and the artistic, detail-oriented approach of a craftsman, we can achieve a balanced skill set that enhances our work and contributes to the success of our products. We should strive to integrate both qualities into our professional development to build better software and become more versatile, effective, and happy professionals.
| fanatixan |
1,900,482 | Junior level: Introduction to React | Overview of React What is React? React is a JavaScript library for building... | 0 | 2024-06-25T19:21:58 | https://dev.to/david_zamoraballesteros_/junior-level-introduction-to-react-4ai0 | react, webdev, javascript, programming | ## Overview of React
### What is React?
React is a JavaScript library for building user interfaces, particularly single-page applications where you need a dynamic, fast, and responsive user experience. Developed and maintained by Facebook, React emphasizes the creation of reusable components, which can be thought of as the building blocks of a user interface.
Think of React components like functions: they take inputs (called props) and return UI elements that are rendered on the page. This modular approach helps in building large-scale applications by breaking them down into smaller, manageable pieces.
### History and Evolution of React
React was first introduced by Facebook in 2013. It was developed to solve the challenges Facebook engineers faced with maintaining complex user interfaces. The initial public release of React brought a new paradigm to UI development by introducing the concept of the virtual DOM, which improved performance and made updates more efficient.
Over the years, React has evolved with significant milestones:
- **2015:** Introduction of React Native, allowing developers to build mobile apps using React.
- **2016:** Introduction of React Fiber, a complete rewrite of the React core algorithm, enhancing performance and responsiveness.
- **2019:** Introduction of React Hooks, enabling state and side-effect management in functional components, simplifying code and making components more reusable.
### Comparison with Other Frameworks/Libraries
**Angular:**
- Developed by Google, Angular is a full-fledged framework, providing everything you need out-of-the-box, including a powerful templating system, dependency injection, and comprehensive tooling.
- Angular is more opinionated and structured, which can be beneficial for large teams working on complex applications but might feel restrictive for smaller projects or teams preferring flexibility.
**Vue:**
- Vue is a progressive framework, designed to be incrementally adoptable. It combines the best features of Angular and React, offering an approachable core library that focuses on the view layer, with optional plugins for routing and state management.
- Vue is known for its simplicity and ease of integration, making it a popular choice for both small and large-scale applications.
### Why Choose React?
### Benefits of Using React
1. **Component-Based Architecture:**
- React encourages the creation of reusable UI components, which encapsulate their own logic and rendering. This modularity leads to more maintainable and scalable code.
2. **Virtual DOM:**
- React uses a virtual DOM to optimize rendering. When the state of an application changes, React updates the virtual DOM, calculates the most efficient way to update the real DOM, and applies those changes. This process significantly improves performance.
3. **Declarative UI:**
- React allows you to design your UI declaratively: you describe what the UI should look like for any state of your application, and React ensures the UI stays in sync with the state. This makes your code more predictable and easier to debug.
4. **Strong Ecosystem:**
- React has a vast ecosystem of tools, libraries, and community support. Whether you need state management, routing, or form handling, there is likely a well-maintained library available.
5. **React Native:**
- React's principles can be extended to mobile app development with React Native, enabling code reuse between web and mobile platforms.
### Case Studies of Successful React Applications
1. **Facebook:**
- React was born out of Facebook's need to handle dynamic and complex user interfaces. Today, it powers Facebook's web application, ensuring a fast and responsive user experience.
2. **Instagram:**
- Instagram, also owned by Facebook, uses React to handle its web app, benefiting from React's efficient rendering and modular architecture.
3. **Airbnb:**
- Airbnb leverages React to build dynamic and responsive interfaces. React's component-based architecture allows Airbnb to maintain a consistent user experience while rapidly iterating on new features.
4. **Netflix:**
- Netflix uses React on its platform for improved startup speed and runtime performance, making their web application more efficient and user-friendly.
## Conclusion
React has proven itself as a powerful and flexible library for building user interfaces. Its component-based architecture, efficient rendering with the virtual DOM, and strong ecosystem make it an excellent choice for developing modern web applications. As you progress in your development career, understanding and mastering React will equip you with the skills to build scalable and maintainable applications, and contribute to successful projects like those of Facebook, Instagram, and Airbnb. | david_zamoraballesteros_ |
1,900,469 | Join TemplateMonster Affiliate Program - Get up to 30% Commissions | Have a website and want to monetize its traffic? Want to promote your marketplace products? Join... | 0 | 2024-06-25T19:16:37 | https://dev.to/hasnaindev1/join-templatemonster-affiliate-program-get-up-to-30-commissions-3fnb | webdev, website, webpack, webcomponents | Have a website and want to monetize its traffic? Want to promote your marketplace products?
Join **TemplateMonster affiliate family** and convert your traffic into money.
Get up to 30% share from the sales your leads make; we will help you make it to the top!
**Sign Up URL**: https://rebrand.ly/templatemonsteraffiliate
**Why Become a TemplateMonster Affiliate?**
**TemplateMonster** has become a one-stop source of web design, development, and marketing products and services. People associate our brand name with the biggest collection of website templates, graphics, plugins, and other digital items. We are welcoming you to become a part of our affiliate community and grow together. Here is what we promise.
**How It Works?**
**TemplateMonster marketplace** provides beneficial terms and conditions for the affiliate partners. In addition to paying 30% for the initial client's purchase, we provide you with a set of free tools to help you with online promotion and marketing. The application process is easy; just follow these simple steps.
**1) Sign up for the program**
Create and verify a free account and get access to the affiliate admin panel.
**2) Share your unique referral URL**
Generate a referral URL with your affiliate ID and share it on your website, email, or social media.
**3) Check the statistics**
Track the traffic you send and see the related sales. The more leads you refer, the more profit you get.
**4) Earn commission**
Earn up to 30% commission for all new purchases, analyze your campaigns, and promote the highest-converting products.
**Sign Up URL**: https://rebrand.ly/templatemonsteraffiliate
| hasnaindev1 |
1,900,468 | Lost Ark Patch Notes Chaos Rising Update May 2024Victory | Meta Description: Lost Ark Patch Notes Chaos Rising Update brings the end-game acceleration and a... | 0 | 2024-06-25T19:14:47 | https://dev.to/saad_hassan_f60b15ba440d1/lost-ark-patch-notes-chaos-rising-update-may-2024victory-4gf2 |

Meta Description: Lost Ark Patch Notes Chaos Rising Update brings the end-game acceleration and a lot more with the May 22 Update.
KW: Lost Ark Patch Notes Chaos Rising Update, Lost Ark Chaos Rising Update, Patch Notes for Lost Ark Chaos Rising
Lost Ark Patch Notes Chaos Rising
The fresh Patch Notes for Lost Ark Chaos Rising released in May 2024 bring a lot of new content, along with the highly anticipated Thaemine After Story. With a series of new events and the endgame acceleration, the Lost Ark Patch Notes Chaos Rising Update is making the hype. So ensure you have enough lost ark gold before joining the Chaos Rising Update. In addition to that, there are some bug fixes and quality-of-life updates to make the game more fun to play. In this article, we are going to talk about everything that's coming with the Lost Ark Chaos Rising Update.
Trial Guardian Raid: Hanumatan
Even though Hanumatan may not sound like something newly introduced to the Lost Ark, the Trial Guardian would be something a bit different from what you've done for the Guardian runs. And you can always get more game coins from U7BUY to play the Trial Guardian Raid without any limitations. So here is what's included in the Trial Guardian Raid version.
This version comes with reinforced skills and patterns. Hence, you may have to prepare yourself by learning new mechanics since this trial needs skills and precision.
The entry requirements for the normal mode are level 1600 or more. If you are going for the hard mode, then the requirement changes to 1630 or more.
There is no need for any book setup to set coordination or to make any adjustments.
No matter which mode you choose to play with, you will be awarded after the first clear.
If you are clearing the difficulties for the first time, you will get gold. This opportunity is available for once only per roster.
Trial Guardian brings new achievements, titles, and trophies.
To find the Trial Guardian Raid for the normal and hard mode, you can access the Party Finder.
The Thaemine After Story
If you have bypassed the Thaemine hard mode raid, you will be able to access the quest called Shadow of the Moon. You can obtain this new quest from the Knight Oscar in Luterra Caste. To specifically access this quest even more properly, here are the requirements that you have to follow.
You will have to clear the Thaemine hard mode raid Gate Four at least once.
Complete the Adento's Legacy that represents the Voldis World Quest.
Complete the Prelude quest, Red Mist After Dusk of the Thaemine.
Upcoming New Adventure Island
The new adventure island by the name of Cruel Toy Castle Island is coming to the Lost Ark, which can be found at the Shushire coat with the help of Procyon's Compass. If you're a fan of horizontal content, then this island would be a fun place to explore for you as it will bring a new Island Soul and Mokoko Seed. In addition to that, it also brings new achievements, a new toy, and a title.
The Lost Ark Chaos Rising Update patch notes gave detailed insights about the game's upcoming sets of events and content. Hopefully, you won't miss out on the details, additions, and bug improvements brought to the game.
| saad_hassan_f60b15ba440d1 | |
1,900,466 | Introduction to Computer Vision in C# .NET | Introduction Computer vision is a transformative technology that enables machines to... | 0 | 2024-06-25T19:11:43 | https://dev.to/jwtiller_c47bdfa134adf302/introduction-to-computer-vision-in-net-160i | dotnet, computervision | ## Introduction
Computer vision is a transformative technology that enables machines to interpret and understand the visual world. By utilizing the OpenCV library through OpenCvSharp in .NET, developers can perform various image processing and computer vision tasks effectively. This guide will introduce essential image operations, providing a strong foundation for more advanced applications.
OpenCV (Open Source Computer Vision Library) is a comprehensive library for computer vision tasks that supports many popular programming languages, including Python, C++, and Java. In this article, we will focus on using the .NET wrapper, OpenCvSharp, to bring the power of OpenCV to the .NET ecosystem.
## OpenCV and OpenCvSharp
OpenCV is an open-source library designed for computational efficiency and real-time applications. It has a strong community and extensive documentation, making it a popular choice for computer vision tasks across various languages. OpenCvSharp is a .NET wrapper for OpenCV, allowing .NET developers to access OpenCV functions seamlessly.
### Setting Up OpenCvSharp
1. **Installation**: Install OpenCvSharp via the NuGet Package Manager in Visual Studio.
```bash
Install-Package OpenCvSharp4
Install-Package OpenCvSharp4.runtime.win
```
2. **Basic Project Setup**:
- Create a new .NET project.
- Add the OpenCvSharp references.
- Initialize and test OpenCvSharp with a simple code snippet.
## Basics: Image Resize, Black and White Conversion, and More
1. **Image Resizing**:
Resizing an image is crucial for various applications, such as fitting images into specific dimensions for UI elements, preparing images for machine learning models, or reducing the image size for faster processing and transmission.
```csharp
using OpenCvSharp;
var src = new Mat("path_to_image.jpg", ImreadModes.Color);
var dst = new Mat();
Cv2.Resize(src, dst, new Size(300, 300));
Cv2.ImShow("Resized Image", dst);
Cv2.WaitKey(0);
```
**Why Use Image Resizing**:
- **Performance**: Smaller images require less memory and processing power.
- **Standardization**: Ensures images fit a standard size for further processing or display.
- **Transmission**: Smaller images are quicker to upload and download.
2. **Converting to Black and White**:
Converting images to grayscale is a common preprocessing step that simplifies the image data, making it easier to detect edges, contours, and other features. It reduces computational complexity by working with a single channel instead of three.
```csharp
var gray = new Mat();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
Cv2.ImShow("Gray Image", gray);
Cv2.WaitKey(0);
```
**Why Use Grayscale Conversion**:
- **Simplicity**: Easier to process and analyze.
- **Feature Detection**: Enhances contrast between different regions.
- **Preprocessing**: Prepares the image for further operations like edge detection and thresholding.
3. **Blurring an Image**:
Blurring reduces image noise and detail, which is useful in various preprocessing tasks to enhance edge detection and reduce unwanted artifacts. It smooths the image by averaging pixel values with neighboring pixels.
```csharp
var blurred = new Mat();
Cv2.GaussianBlur(src, blurred, new Size(15, 15), 0);
Cv2.ImShow("Blurred Image", blurred);
Cv2.WaitKey(0);
```
**Why Use Blurring**:
- **Noise Reduction**: Minimizes random noise and details.
- **Preprocessing**: Improves the accuracy of edge detection and other image processing tasks.
- **Aesthetic Effect**: Produces a visually pleasing effect for certain applications.
4. **Edge Detection**:
Edge detection is fundamental in identifying the boundaries within images, which is crucial for object detection, image segmentation, and pattern recognition. It highlights the transitions in intensity, indicating object contours.
```csharp
var edges = new Mat();
Cv2.Canny(gray, edges, 100, 200);
Cv2.ImShow("Edge Detected Image", edges);
Cv2.WaitKey(0);
```
**Why Use Edge Detection**:
- **Object Detection**: Helps in identifying and localizing objects within an image.
- **Image Segmentation**: Divides an image into its constituent parts or objects.
- **Pattern Recognition**: Facilitates the identification of shapes and patterns within images.
## Additional Basic Operations
1. **Image Thresholding**:
Converts grayscale images into binary images by applying a threshold value. This is useful for separating objects from the background.
```csharp
var binary = new Mat();
Cv2.Threshold(gray, binary, 128, 255, ThresholdTypes.Binary);
Cv2.ImShow("Binary Image", binary);
Cv2.WaitKey(0);
```
**Why Use Thresholding**:
- **Segmentation**: Simplifies the image for analysis by converting it into a binary form.
- **Object Detection**: Separates objects from the background.
- **Image Simplification**: Reduces the complexity for further processing.
2. **Image Rotation**:
Rotating images can be necessary for data augmentation or aligning images for further analysis.
```csharp
var center = new Point2f(src.Width / 2, src.Height / 2);
var rotationMatrix = Cv2.GetRotationMatrix2D(center, 45, 1.0);
var rotated = new Mat();
Cv2.WarpAffine(src, rotated, rotationMatrix, src.Size());
Cv2.ImShow("Rotated Image", rotated);
Cv2.WaitKey(0);
```
**Why Use Image Rotation**:
- **Data Augmentation**: Increases the diversity of training data for machine learning models.
- **Alignment**: Corrects the orientation of images for consistency.
- **Aesthetics**: Adjusts the image for visual presentation.
3. **Drawing Shapes**:
Drawing shapes like circles, rectangles, and lines is useful for highlighting features or regions of interest in an image.
```csharp
var drawImage = src.Clone();
Cv2.Rectangle(drawImage, new Rect(50, 50, 200, 200), Scalar.Red, 3);
Cv2.Circle(drawImage, new Point(150, 150), 50, Scalar.Blue, 3);
Cv2.Line(drawImage, new Point(0, 0), new Point(300, 300), Scalar.Green, 3);
Cv2.ImShow("Shapes", drawImage);
Cv2.WaitKey(0);
```
**Why Draw Shapes**:
- **Annotation**: Marks important areas for analysis or reference.
- **Visualization**: Helps in visualizing regions of interest or detected features.
- **Debugging**: Assists in debugging image processing algorithms by showing intermediate results.
## Conclusion
This introduction to computer vision in .NET using OpenCvSharp has covered fundamental operations like image resizing, grayscale conversion, blurring, and edge detection. These basics are the building blocks for more advanced computer vision tasks. Future articles will delve deeper into complex techniques such as object detection, feature matching, and image segmentation. | jwtiller_c47bdfa134adf302 |
1,900,465 | The Essential Guide to Choosing a Supplier: Key Considerations for Business Success | In the realm of business operations, selecting the right supplier is a critical decision that... | 0 | 2024-06-25T19:09:51 | https://dev.to/bali_harvest_b61a903fde19/the-essential-guide-to-choosing-a-supplier-key-considerations-for-business-success-3ce3 | In the realm of business operations, selecting the right supplier is a critical decision that directly impacts product quality, operational efficiency, and overall profitability. This comprehensive guide explores the importance of [suppliers](https://baliharvest.com/), essential criteria for evaluating potential partners, strategic benefits of effective supplier relationships, and practical tips for optimizing supplier management to foster business growth and resilience.
Understanding the Role of Suppliers:
Supplier Definition and Scope: A supplier is a pivotal link in the supply chain ecosystem, responsible for providing goods, materials, or services necessary for business operations. Whether sourcing raw materials, components, or finished products, suppliers play a crucial role in ensuring product availability, quality assurance, and fulfillment of customer demand.
Strategic Importance: Suppliers contribute to the competitiveness and sustainability of businesses by influencing product cost, quality, and reliability. Strategic supplier partnerships enable businesses to enhance operational efficiency, mitigate supply chain risks, and capitalize on market opportunities through collaborative innovation and mutual support.
Types of Suppliers: Suppliers encompass a diverse range of entities, including manufacturers, distributors, wholesalers, and service providers. Each type of supplier offers distinct advantages in terms of pricing, scalability, geographic reach, and specialization, catering to unique business needs and market dynamics.
Key Considerations for Choosing a Supplier:
Quality and Reliability: Prioritize suppliers with a proven track record of delivering consistent quality and reliability. Evaluate their adherence to industry standards, certifications, and quality control processes to ensure compliance with regulatory requirements and customer expectations.
Cost and Pricing Structure: Compare pricing models, cost transparency, and payment terms offered by different suppliers to optimize cost-effectiveness and financial viability. Negotiate favorable terms, volume discounts, and incentives that align with budgetary constraints and long-term profitability goals.
Capacity and Scalability: Assess the supplier's production capacity, scalability, and ability to accommodate fluctuating demand levels. Ensure they possess adequate resources, infrastructure, and operational flexibility to support business growth, new product launches, or seasonal variations in market demand.
Supply Chain Resilience: Evaluate the supplier's supply chain resilience, contingency planning, and risk management strategies to mitigate disruptions, such as natural disasters, geopolitical factors, or supply shortages. Proactively address potential vulnerabilities to maintain continuity of supply and meet customer commitments.
Building Strong Supplier Relationships:
Communication and Transparency: Establish open lines of communication, clear expectations, and regular updates with suppliers to foster transparency, collaboration, and mutual understanding. Effective communication enhances responsiveness, problem-solving, and proactive resolution of issues to prevent operational disruptions.
Collaborative Innovation: Encourage collaborative innovation and continuous improvement initiatives with suppliers to drive product innovation, process optimization, and competitive differentiation. Engage suppliers as strategic partners in exploring new technologies, market trends, and sustainable practices that add value to the supply chain ecosystem.
Performance Metrics and Evaluation: Implement key performance indicators (KPIs), service level agreements (SLAs), and periodic performance reviews to monitor supplier performance, quality metrics, and compliance with contractual obligations. Use data-driven insights to identify areas for improvement, recognize top-performing suppliers, and cultivate long-term partnerships based on mutual success.
Supplier Diversity and Ethical Considerations:
Diversity and Inclusion: Embrace supplier diversity initiatives by engaging with minority-owned, women-owned, or veteran-owned businesses to promote economic empowerment, foster diversity in the supply chain, and enrich community partnerships. Emphasize inclusivity, equitable opportunities, and social responsibility in supplier selection practices.
Ethical Standards and Corporate Responsibility: Uphold ethical standards, sustainability principles, and corporate social responsibility (CSR) criteria in supplier relationships. Prioritize suppliers committed to ethical business practices, environmental stewardship, labor rights, and compliance with international standards to uphold brand reputation and mitigate reputational risks.
Technological Integration and Digital Transformation:
Digital Procurement Solutions: Leverage digital procurement platforms, supply chain management systems, and e-procurement tools to streamline sourcing processes, automate supplier collaboration, and enhance real-time visibility into supply chain operations. Embrace digital transformation initiatives to optimize efficiency, reduce costs, and drive agility in supplier management.
Data Analytics and Predictive Insights: Harness data analytics, predictive modeling, and advanced analytics techniques to derive actionable insights into supplier performance trends, market dynamics, and demand forecasting. Utilize data-driven decision-making to anticipate supply chain challenges, optimize inventory management, and capitalize on strategic opportunities for business growth.
Future Trends and Innovations in Supplier Management:
Artificial Intelligence (AI) and Machine Learning: Embrace AI-powered algorithms, predictive analytics, and machine learning capabilities to optimize supplier selection, predictive maintenance, and demand forecasting. AI-driven insights enhance decision-making agility, supply chain visibility, and operational efficiency in a rapidly evolving business landscape.
Blockchain Technology: Explore blockchain-enabled platforms for enhanced transparency, traceability, and secure transactions in supplier relationships. Blockchain solutions offer decentralized ledger technology to verify authenticity, track supply chain provenance, and ensure compliance with regulatory standards across global supply networks.
Conclusion:
In conclusion, selecting the right supplier is pivotal for achieving operational excellence, driving innovation, and sustaining competitive advantage in today's global marketplace. By prioritizing quality, reliability, collaborative partnerships, and ethical standards, businesses can optimize supplier relationships, mitigate supply chain risks, and position themselves for long-term success and resilience. | bali_harvest_b61a903fde19 | |
1,900,463 | Discover the Best Hijab Caps with Pas-e-Parda | When it comes to completing your modest fashion look, a hijab cap is an essential accessory. At... | 0 | 2024-06-25T19:08:01 | https://dev.to/pas_eparda_effaa16bfc634/discover-the-best-hijab-caps-with-pas-e-parda-34k8 | When it comes to completing your modest fashion look, a hijab cap is an essential accessory. At Pas-e-Parda, we offer a wide range of hijab caps designed to provide comfort, style, and versatility. Whether you are looking for a simple inner cap or a stylish hijab cap design, Pas-e-Parda has got you covered.
## The Importance of Hijab Caps
A **[Hijab Caps Price in Pakistan](https://pas-e-parda.com/collections/hijab-cap/)**, also known as an undercap or inner cap, serves multiple purposes. It helps to secure the hijab in place, prevents it from slipping, and adds an extra layer of comfort. Hijab caps also protect your hair from friction and keep your hairstyle intact throughout the day. Additionally, they can add a touch of elegance and sophistication to your overall look.
## Stylish Hijab Cap Designs
At Pas-e-Parda, we understand that every woman has her unique style. That’s why we offer a variety of hijab cap designs to suit different preferences and occasions. From simple, plain caps to intricately designed ones, our collection caters to all tastes.
1. Plain Hijab Caps: Ideal for everyday wear, plain hijab caps provide a clean and polished look. They are available in a range of colors to match your hijabs and outfits perfectly.
2. Embroidered Hijab Caps: For a touch of elegance, opt for our embroidered hijab caps. These caps feature delicate embroidery that adds a feminine touch to your look.
3. Lace Hijab Caps: Perfect for special occasions, lace hijab caps offer a blend of sophistication and charm. The intricate lace patterns make these caps a beautiful addition to your wardrobe.
4. Printed Hijab Caps: If you love patterns and prints, our printed hijab caps are perfect for you. These caps feature unique designs that can make a statement and add a fun element to your outfit.
## Affordable Hijab Caps Prices in Pakistan
At Pas-e-Parda, we believe that style and quality should be accessible to everyone. That’s why we offer our hijab caps at competitive prices. We understand the importance of affordability without compromising on quality. Our hijab caps are made from high-quality fabrics that are soft, breathable, and durable.
Hijab Caps Price in Pakistan: The price of hijab caps at Pas-e-Parda varies based on the design and fabric. However, we ensure that all our products are reasonably priced to cater to a wide audience. You can find simple hijab caps starting from as low as PKR 200, while more elaborate designs may be priced higher. Our goal is to provide value for money, ensuring that you get stylish and durable hijab caps without breaking the bank.
## The Perfect Hijab Inner Cap
An inner cap is an essential part of every hijabi’s wardrobe. It helps to keep your hair in place and provides a smooth base for your hijab. At Pas-e-Parda, our hijab inner caps are designed with comfort in mind. They are made from soft, breathable fabrics that are gentle on the scalp and suitable for all-day wear.
## Features of Pas-e-Parda Hijab Inner Caps:
Breathable Fabric: Our inner caps are made from materials that allow air circulation, keeping you cool and comfortable.
Secure Fit: Designed to stay in place, our inner caps ensure that your hijab stays put throughout the day.
Variety of Colors: Available in a range of colors, you can choose an inner cap that matches or contrasts with your hijab.
Easy Care: Our inner caps are easy to wash and maintain, making them a practical addition to your wardrobe.
Why Choose Pas-e-Parda?
Pas-e-Parda is committed to providing high-quality hijab caps that combine style, comfort, and affordability. Here’s why you should choose us:
Wide Range of Designs: From simple to intricate, our hijab cap collection caters to all styles and preferences.
Affordable Prices: We offer competitive prices without compromising on quality.
Comfortable and Durable: Our hijab caps are made from high-quality fabrics that are soft, breathable, and long-lasting.
Customer Satisfaction: We prioritize customer satisfaction and strive to provide the best shopping experience.
Shop the Best Hijab Caps at Pas-e-Parda
Enhance your **[hijab cap](https://pas-e-parda.com/collections/hijab-cap/)** with stylish and affordable hijab caps from Pas-e-Parda. Whether you need a basic inner cap or a fashionable design, we have something for everyone. Visit our website today and explore our wide range of hijab caps that perfectly blend style, comfort, and affordability. | pas_eparda_effaa16bfc634 | |
1,900,456 | Product idea (Feedback Required): hubhandle.com | Hey Folks, In my previous post, I shared about nightsweekends s5. ... | 0 | 2024-06-25T19:05:32 | https://dev.to/sauravshah31/product-idea-feedback-required-hubhandlecom-ell | discuss, community, startup | Hey Folks,
In my previous post, I shared about nightsweekends s5.
{% embed https://dev.to/sauravshah31/this-is-for-you-lets-build-some-cool-stuff-15kn %}
This post is about what I am building. I would love to hear from you guys and appreciate your feedback.
[hubhandle.com](https://hubhandle.com/) is an easy-to-learn and simple-to-use tool to manage all your social media needs.
The initial version of this tool will allow to publish a post across four social media platform: [Instagram](https://www.instagram.com/hubhandle/), Facebook, [LinkedIn](https://www.linkedin.com/company/hubhandle/), [X](https://x.com/HubHandleX). Over time, I plan to add more features to make [hubhandle.com](https://hubhandle.com/) a one-stop solution to for all your social media needs.
**HubXStream** will help you schedule all your posts across social media platforms.
**HubXSecure** will help you collaborate with other team members without sharing passwords.
**HubXIntellect** will help you create AI-generated posts tailored to your audience in a single click.
**HubXAnalytica** will provide real-time analytics of your posts and help you develop strategies.
**HubXAutomate** will help you automate your social media tasks with ease.
There are tools already available for these tasks, but they can be a little difficult to use. I want to make a tool that is simple to use so you can become an expert on day one.
Please share your thoughts and feedback. It will help me create a better product.
If any of you have also joined Nights and Weekends Season 5, comment on what you are building. Let's build some cool stuff together!
**Cheers🎉** ~ [sauravshah31](https://x.com/sauravshah31) | sauravshah31 |
1,900,440 | Sending website aggregate document to Kindle | Here is my experience of creating a web app which sends document to Kindle. It was something which I... | 0 | 2024-06-25T19:05:02 | https://dev.to/mihovil/sending-website-aggregate-document-to-kindle-2j71 | kindle, vercel, react, nextjs | Here is my experience of creating a web app which sends document to Kindle. It was something which I wanted to build for a long time.
The app which I built for that is in Croatian, since the document is in Croatian too. It is deployed on this site:
https://kindle-liturgija-dana.vercel.app/

## Motivation
I am a Catholic and I try to read daily scripture everyday. I prefer reading it on Kindle. In order to do that, I would use my mobile phone to go to the website with daily readings, copy it into a Word document which I would then send to Kindle. Then I would read it on Kindle. It is boring job and after I read it, I also have to delete the document which takes few clicks on Kindle. It would be a pleasure if I would get this document automatically delivered into my Kindle once a month with all readings for each day of that month.
## Technologies used
This was an opportunity for me to explore some new libraries and technologies:
* Vercel (cloud platform)
* NextJS (React framework)
* Adobe Spectrum (UI library)
## What I learned from it
Website aggregate
* I was using library _jsdom_ to extract interesting data from the website after I _fetched_ its content. I fetched several routes, one for each day. And then I would combine it all into one HTML document.
Sending document to Kindle
* each Kindle device has its own email address. You can send a document to that address and it will be downloaded to Kindle when it connects to Internet. Kindle accepts .docx, .html., .mobi and various other formats of documents
Sending emails
* the best thing seemed to be to use some cloud service like [Postmark](postmarkapp.com)
* for this kind of services you need your own registered domain. I used [one](https://www.mirogoj.com/) from my friend (thank you Nikola).
* GMail is not allowed for this kind of services
Vercel cloud platform
* they have their own service for measuring website performanse (page insights)
* they also have a Firewall for mitigating DoS attacks
* they have website analytics which can be used to track statistics of page visitors
* it can host NextJS apps and they support serverless NodeJS functions
* easy setup for building the website after push to Git repo.
* once I had an error in build. The build was not successful and I could not find the build logs with error. I only managed to find some build status with error icon on GitHub. That part did not make me happy because I did not understand what was wrong. So that could be a deal breaker for some
* logs on free plan only exist for a short time
NextJS
* I wanted to try out _server actions_. I was not very happy with all of that. The data is being sent using _FormData_ and I didn't manage to find an elegant solution for reading this data in TypeScript. E.g. I had to transform each date from a string. All in all, I feel like it would have been easier to use NextJS route handler which is just like a REST service
Dates in sever components (NextJS)
* I had troubles with transfering dates between client and server components
* if you do not need a time zone, the best thing seems to be to use UTC on server side
* I tried using _date-fns_ library which has loads of functions+
* last day of the month messed up the time zones so I didn't use their function _endOfMonth_ but I used an alternative way of calculating the last day of the month. Their function had a different time zone compared to the one for the first day of the month which is annoying because it was not consistent in that perspective
Programming with LLM
* I also wanted to try to use free versions of ChatGPT and Bard (now Gemini).
* I just got frustrated in trying to get what I needed. It means I need to practice prompt engineering and also it means that this services are not as mature as I was hoping them to be
Adobe Spectrum
* I wanted to try out this library. It looks really nice. But it feels like a framework. They do not encourage using standard CSS. Instead their system should be used where each component has a lot of attributes (for CSS) and including the ones associated with visual breakpoints (for grid system).
* they use special library for dates
## Conclusion
In the end, I managed to build the application which I needed. Every 20th of each month I get the document in Kindle with daily readings for each day of the following month.
And I got to try out some of the things which seemed to be interesting and I learned something new.
Now I have some similar ideas to build aggregate document for some other sites like daily news portal. Or for website with Catholic articles from which I would take the most popular articles of the week.
Here is the code repository:
https://github.com/mih0vil/vercel-kindle-liturgija-dana | mihovil |
1,900,462 | Updating a Record Creates a new Record | I wish to update a record in Django using a form, but instead it creates a new record. I know it has... | 0 | 2024-06-25T19:02:13 | https://dev.to/coolmike890/updating-a-record-creates-a-new-record-d7c | django | I wish to update a record in Django using a form, but instead it creates a new record. I know it has to do with using get(), but I don't know how to fix it. Here is the relevant code:
my form:
```
class AddRecordForm(forms.ModelForm):
class Meta:
model = Model2
fields = ('field1', 'field2')
```
my Models:
```
class Model2(models.Model):
id = models.CharField(primary_key=True, max_length=12)
created_at = models.DateTimeField(auto_now_add=True)
field3 = models.ForeignKey(Model3, on_delete=models.PROTECT, related_name='master')
field4 = models.PositiveSmallIntegerField()
class Meta:
ordering = ['id']
def __str__(self):
return(f"{self.field3} ")
```
```
class Model1(models.Model):
field1 = models.ForeignKey(Model2, on_delete=models.PROTECT, related_name='list')
created_at = models.DateTimeField(auto_now_add=True)
field2 = models.PositiveSmallIntegerField(null=True, blank=True)
```
and my view:
```
def update_record(request, pk):
record = Model2.objects.get(field2=pk)
form = AddRecordForm(instance=record)
if request.method == 'POST':
form = AddRecordForm(request.POST, instance=record)
if form.is_valid():
form.save()
messages.success(request, "Record updated successfully!")
return render(request, 'home', {})
context = {'form':form}
return render(request, 'update_record.html', context)
```
Any help would be very much appreciated. Thanks. | coolmike890 |
1,900,460 | Want to learn Hacking ?!! | Here is the best Website I've ever experienced in my hacking career https://tryhackme.com/ read... | 0 | 2024-06-25T19:00:22 | https://dev.to/delta02/want-to-learn-hacking--55fa | Here is the best Website I've ever experienced in my hacking career
https://tryhackme.com/
read more about it on the internet if you want, don't want to make it the most boring post, anyhow lets hack together!!
The Best Part :-
K.O.T.H
King Of The Hill
It's a legal hacking game where you hack with your friends or armatures and gain access to a machine and patch the vulnerabilities to stop others from Accessing it.
Good Luck Beating [PROOSss] + Thats All | delta02 | |
1,900,459 | API Design 101: A Comprehensive Guide to Documenting APIs for Developers | Introduction to API Design What is an API? Importance of... | 0 | 2024-06-25T18:59:47 | https://dev.to/ronakmunjapara/api-design-101-a-comprehensive-guide-to-documenting-apis-for-developers-2mlp | webdev, api, design, tutorial |

## **Introduction to API Design**
### What is an API?
### Importance of Well-Designed APIs
### Goals of API Documentation
## **Fundamentals of API Design**
### Design Principles to Follow
#### RESTful Architecture
#### Versioning and Compatibility
#### Security and Authentication Methods
## **Planning Your API Documentation**
### Understanding Your Audience
#### Developer Persona Profiles
### Setting Clear Objectives
#### Documentation Scope and Depth
#### Defining Use Cases and Examples
## **Structuring Your API Documentation**
### Choosing the Right Format
#### Markdown vs. OpenAPI Specification
#### Interactive Documentation Tools
### Essential Sections in API Documentation
#### Endpoint Reference
##### HTTP Methods and Their Usage
##### Request and Response Formats
##### Parameters and Payloads
## **Writing Effective API Documentation**
### Best Practices for Clarity and Consistency
#### Using Descriptive Language
#### Providing Code Samples
#### Including Visual Diagrams and Flowcharts
## **Testing and Iterating Your API Documentation**
### Importance of Documentation Testing
#### Review Processes and Feedback Loops
#### Version Control and Change Logs
## **Publishing and Maintaining API Documentation**
### Hosting Options and Considerations
#### Self-Hosted vs. Cloud-Based Solutions
#### Accessibility and Availability
### Continuous Updates and Maintenance
#### Handling Deprecation and Legacy Support
## **Promoting Adoption Through Documentation**
### Strategies for Developer Engagement
#### Developer Onboarding Guides
#### Community Support and Forums
## **Measuring Success of API Documentation**
### Metrics to Track
#### Usage Analytics
#### Developer Feedback and Satisfaction Surveys
## **Conclusion**
Writing thorough and accessible API documentation is crucial for developers to effectively utilize and integrate APIs into their projects. By following best practices in design, structuring, and maintenance, developers can create documentation that enhances user experience and accelerates adoption.
---
## **FAQs About API Documentation**
1. **What tools can I use to create API documentation?**
- There are several popular tools such as Swagger, Postman, and Redoc that simplify API documentation creation and management.
2. **Why is versioning important in API documentation?**
- Versioning ensures that developers can access previous versions of the API and manage changes effectively without disrupting existing integrations.
3. **How can I make my API documentation more engaging?**
- Incorporate interactive examples, use cases relevant to different industries, and provide real-world scenarios to engage developers effectively.
4. **What should I include in the introduction section of API documentation?**
- The introduction should define the API's purpose, outline its key features, and provide a brief overview of how developers can get started using it.
5. **How often should I update API documentation?**
- It's recommended to update API documentation with every significant API change or release to keep developers informed and maintain accuracy.
---
I hope you are having a wonderful day! I have a small favor to ask. I'm aiming to rank in the top 10 on the ChatGPT store, and I can't do it without your amazing support. | ronakmunjapara |
1,900,458 | ** ¡Desvela los secretos de los métodos HTTP Request con la ayuda de Malcolm el del Medio! **🧑 | ¡Hola Chiquis! 👋🏻 ¿Te apasiona el mundo de la programación web y deseas convertirte en un maestro de... | 0 | 2024-06-25T18:58:39 | https://dev.to/orlidev/-desvela-los-secretos-de-los-metodos-http-request-con-la-ayuda-de-malcolm-el-del-medio--4mm0 | webdev, requestforpost, tutorial, beginners | ¡Hola Chiquis! 👋🏻 ¿Te apasiona el mundo de la programación web y deseas convertirte en un maestro de los métodos HTTP Request? ¿Eres fanático de la icónica serie Malcolm el del Medio y te divierte analizar las locuras de la familia Wilkerson? ¡Entonces este post es para ti!

Vamos a sumergirnos en el mundo de los métodos de petición HTTP y su divertida analogía con "Malcolm el del Medio". 🌐📺
El mundo de la programación web puede ser un poco complejo, especialmente cuando se trata de entender los conceptos básicos. Pero no te preocupes, vamos a explorar el tema de los métodos HTTP Request de una manera divertida y original.
¿Qué son los métodos HTTP Request? 🕹️
Imagina que estás en la casa de los Wilkerson, la familia protagonista de Malcolm el del Medio. Cada miembro de la familia tiene una forma particular de interactuar con el resto y de conseguir lo que quiere. Lo mismo sucede con los métodos HTTP Request en el mundo web.
Los métodos HTTP Request son como las diferentes maneras en que un usuario puede interactuar con un servidor web. Cada método tiene un propósito específico y se utiliza para realizar una acción concreta. Por ejemplo, el método GET se utiliza para obtener información de un servidor, mientras que el método POST se utiliza para enviar datos a un servidor.

Los Métodos de Petición HTTP y sus Personajes 👱
1. `GET`: Francis Wilkerson 🔥 El método `GET` solicita una representación de un recurso específico. Es como cuando Francis, el hijo mayor de la familia Wilkerson, busca información sobre su próximo destino en la escuela militar. Francis solo quiere obtener datos, al igual que `GET` solo recupera información sin modificar nada.
2. `HEAD`: Dewey Wilkerson 🎡 El método `HEAD` pide una respuesta idéntica a la de una petición `GET`, pero sin el cuerpo de la respuesta. Dewey, el pequeño de la familia, siempre está curioso pero no necesita toda la información. Dewey solo quiere la cabeza (encabezado) de la respuesta, sin el cuerpo.
3. `POST`: Reese Wilkerson 🔫 El método `POST` se utiliza para enviar una entidad a un recurso específico, causando a menudo un cambio en el estado o efectos secundarios en el servidor. Reese, el hermano problemático, siempre está causando cambios y problemas. Reese envía algo nuevo al servidor, al igual que `POST` envía datos para crear o modificar recursos. Reese, es un chico manipulador y astuto. Al igual que el método `POST`, Reese sabe cómo conseguir lo que quiere utilizando la fuerza o el engaño.
4. `PUT`: Hal Wilkerson ⛸️ El método`PUT` reemplaza todas las representaciones actuales del recurso de destino con la carga útil de la petición. Hal, el padre de la familia, es un hombre de muchas facetas y puede reemplazar cualquier situación. Hal reemplaza todo, al igual que `PUT` actualiza completamente el recurso.
5. `DELETE`: Lois Wilkerson 🧺 El método `DELETE` borra un recurso en específico. Lois, la madre, siempre está limpiando y organizando la casa. Lois elimina cosas, al igual que `DELETE` borra recursos. Al igual que el método `DELETE`, Lois puede eliminar información de forma permanente, sin posibilidad de recuperarla.
6. `CONNECT`: Craig Feldspar 🤓 El método `CONNECT` establece un túnel hacia el servidor identificado por el recurso. Craig, el compañero de trabajo excéntrico de Lois , siempre está conectado con ideas extrañas. Craig crea un túnel de conexión, al igual que `CONNECT` establece una conexión directa.
7. `OPTIONS`: Ida Welker 👵🏻 El método `OPTIONS` describe las opciones de comunicación para el recurso de destino. Ida, la abuela, siempre tiene opciones y consejos. Ida proporciona opciones, al igual que `OPTIONS` describe las disponibles.
8. `TRACE`: Comandante Edwin Spangler 👮🏻♂ ️El método `TRACE` realiza una prueba de bucle de retorno de mensaje a lo largo de la ruta al recurso de destino. El Comandante, veterano militar a cargo de los cadetes en la Academia Marlin, sigue rutas y deja huellas.
9. `PATCH`: Stevie Kenarban 👨🏽🦽 El método `PATCH` se utiliza para aplicar modificaciones parciales a un recurso. Stevie, el amigo discapacitado de Malcolm, siempre encuentra soluciones creativas. Stevie aplica cambios parciales, al igual que `PATCH` modifica solo partes del recurso.

Ejemplos de Métodos de petición HTTP
+ GET:
```
Ruby
require 'net/http'
url = URI.parse('https://api.example.com/data')
response = Net::HTTP.get_response(url)
puts response.body
```
El método GET se utiliza para obtener datos de un recurso. En este ejemplo, solicitamos datos de `https://api.example.com/data`.
+ POST:
```
Ruby
require 'net/http'
require 'json'
url = URI.parse('https://api.example.com/create')
headers = { 'Content-Type' => 'application/json' }
data = { 'name' => 'John Doe', 'age' => 30 }
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url.path, headers)
request.body = data.to_json
response = http.request(request)
puts response.body
```
El método POST se utiliza para enviar datos al servidor. En este ejemplo, creamos un nuevo recurso en `https://api.example.com/create`.
+ PUT:
```
Ruby
require 'net/http'
require 'json'
url = URI.parse('https://api.example.com/update/123')
headers = { 'Content-Type' => 'application/json' }
data = { 'name' => 'Jane Smith', 'age' => 25 }
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Put.new(url.path, headers)
request.body = data.to_json
response = http.request(request)
puts response.body
```
El método PUT se utiliza para actualizar un recurso existente. En este ejemplo, modificamos el recurso con ID 123 en `https://api.example.com/update/123`.
+ DELETE:
```
Ruby
require 'net/http'
url = URI.parse('https://api.example.com/delete/456')
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Delete.new(url.path)
response = http.request(request)
puts response.body
```
El método DELETE se utiliza para eliminar un recurso. En este ejemplo, borramos el recurso con ID 456 en `https://api.example.com/delete/456`.

Más ejemplos HTTP 🛹
Los métodos de solicitud HTTP son como los personajes de la serie. Cada uno tiene su propia personalidad y función en la historia. `GET` es como Hal, el padre de la familia. Es el más básico y confiable, siempre dispuesto a obtener lo que necesitas sin causar problemas. `POST` es Lois, la madre dominante. Ella es la que hace que las cosas sucedan, enviando datos al servidor para crear o actualizar recursos. `PUT` es Reese, el hermano mayor rudo. Él reemplaza por completo los recursos existentes, sin importarle lo que haya antes. `DELETE` es Malcolm, el genio incomprendido. Él elimina recursos de manera precisa y quirúrgica cuando es necesario. `HEAD` es Dewey, el hermano menor. Él obtiene la misma información que `GET`, pero sin el contenido, solo los encabezados. `OPTIONS` es Francis, el hermano rebelde que vive lejos de casa. Él averigua qué opciones de comunicación están disponibles para un recurso. `TRACE` es Piama, la esposa de Francis. Ella rastrea el mensaje de ida y vuelta al recurso, como una prueba de concepto. `CONNECT` y `PATCH` son Polly, haciendo cosas raras que nadie entiende del todo. `CONNECT` establece un túnel y `PATCH` aplica cambios parciales. Juntos, estos métodos HTTP forman una familia disfuncional pero entrañable, cada uno con su propio papel que desempeñar en las aventuras del desarrollo web.

Conclusión:📠 Los métodos HTTP Request son una parte fundamental de la programación web. Al comprender su funcionamiento y utilizar la analogía con Malcolm el del Medio, podemos aprender de una manera más divertida y memorable.
Recuerda que, al igual que en la familia Wilkerson, cada método HTTP Request tiene su propia personalidad y función específica. ¡Explora cada uno de ellos y descubre cómo pueden ayudarte a crear páginas web increíbles! ¡Espero que esta analogía te haya divertido y ayudado a entender los métodos de petición HTTP! 😄🚀
🚀 ¿Te ha gustado? Comparte tu opinión.
Artículo completo, visita: https://lnkd.in/ewtCN2Mn
https://lnkd.in/eAjM_Smy 👩💻 https://lnkd.in/eKvu-BHe
https://dev.to/orlidev ¡No te lo pierdas!
Referencias:
Imágenes creadas con: Copilot (microsoft.com)
#PorUnMillonDeAmigos #LinkedIn #Hiring #DesarrolloDeSoftware #Programacion #Networking #Tecnologia #Empleo #HTTPRequest

 | orlidev |
1,900,457 | Carolina Carts and ATV | Carolina Carts and ATV Address: 9221 Asheville Hwy, Boiling Springs, SC 29316, United States Phone:... | 0 | 2024-06-25T18:51:43 | https://dev.to/dokhazelfiona/carolina-carts-and-atv-3k2 | carts, atv, golf | Carolina Carts and ATV
Address: 9221 Asheville Hwy, Boiling Springs, SC 29316, United States
Phone: (864) 7544598
Email: info@carolinacartsandatv.com
Website: https://carolinacartsandatv.com/
GMB Profile: https://www.google.com/maps?cid=842325918104985724
Carolina Carts and ATV, located at 9221 Asheville Hwy in Boiling Springs, SC, is your premier destination for all your recreational vehicle needs.
Specializing in carts and ATVs, we offer a diverse range of top-quality products to fuel your outdoor adventures. Our expert staff is dedicated to providing exceptional customer service, guiding you through our extensive inventory to find the perfect vehicle and accessories to suit your needs.
Whether you're a seasoned off-road enthusiast or a newcomer to the world of outdoor recreation, Carolina Carts and ATV has something for everyone. Visit us today to explore our selection or give us a call at (864) 754-4598 for personalized assistance. Embark on your next adventure with confidence, knowing you've chosen the best at Carolina Carts and ATV.
Working Hours;
Mon - Fri: 9:00 am - 5:30pm
Sat: 9:00 am - 2:00 pm
Sun: Closed
Keywords:CAROLINA CARTS & ATV, Boiling Springs Golf Cart
| dokhazelfiona |
1,900,590 | Inductor Custom Playgrounds: A developer-first way to experiment and collaborate on LLM app development | The only way to build a high-quality LLM application is to get hands-on, iterate, and experiment your... | 0 | 2024-06-27T19:49:28 | https://inductor.ai/blog/custom-playgrounds | ---
title: Inductor Custom Playgrounds: A developer-first way to experiment and collaborate on LLM app development
published: true
date: 2024-06-25 18:48:03 UTC
tags:
canonical_url: https://inductor.ai/blog/custom-playgrounds
---
The only way to build a high-quality LLM application is to get hands-on, iterate, and experiment your way to success, powered by collaboration and data; it is important to then also do rigorous evaluation.
At Inductor, we’re building the tools that developers need to do this, so that you can build and ship production-ready LLM apps far more quickly, easily, and systematically – whether you’re creating an AI chatbot, a documentation assistant, a text-to-SQL feature, or something else powered by LLMs. We’re now rolling out a new capability that we’re super-excited about: Custom Playgrounds.
[Auto-generate your custom playground by signing up here!] (https://app.inductor.ai/signup)
**Inductor Custom Playgrounds enable you to auto-generate a powerful, instantly shareable playground for your LLM app with a single CLI command - and run it within your environment.** This makes it easy to loop other (even non-technical) team members into your development process, and also accelerate your own iteration speed.
By leveraging Custom Playgrounds, you can turbocharge your development process, reduce time to market, and create more effective LLM applications and features. Watch our demo video to learn more or read on below!
{% embed https://vimeo.com/967057001 %}
##Why use Custom Playgrounds?
Inductor's Custom Playgrounds are purpose-built for developers’ needs, and offer significant advantages over traditional LLM playgrounds with respect to productivity, usability, and collaboration. Custom Playgrounds
* Integrate directly with your code and auto-generate customized UI tailored to your specific LLM application.
* Run directly against your environment, facilitating use of private data and internal systems.
* Enable robust, secure collaboration – empowering teams to share work, collect feedback, and leverage collective expertise directly within the playground (e.g., for prompt engineering and more).
* Accelerate development through features like UI auto-generation, hot-reloading, auto-logging, and integrated test suite management – streamlining the iteration process and enabling rapid prototyping and systematic evaluation.
These enhancements make Custom Playgrounds a more efficient, flexible, and powerful tool for developing and refining LLM applications or features compared to traditional LLM playgrounds and DIY interfaces.
⚠️ Creating DIY capabilities demands greater effort, entails higher risk, and results in increased long-term total cost of ownership (TCO).
##Get started with one command
Simply execute a single Inductor CLI command to auto-generate a playground UI for your LLM application. Run securely in your environment, using your data, systems, and programmatic logic.
To auto-generate a playground for your LLM app, just execute the following commands in your terminal:
<code> $ pip install inductor
$ inductor playground my.module:my_function </code>
where “my.module:my_function” is the fully qualified name of a Python function that is the entrypoint to your LLM app. (No modifications to your code required!)
If you’re building a multi-turn chat app, you can also add a single inductor.ChatSession type annotation to your LLM app’s entrypoint function before you run the playground CLI command to also get chat-specific capabilities.
See [our docs] (https://app.inductor.ai/docs/quickstart.html) for more information about how to use Custom Playgrounds.
Once generated, your playground enables you to
* Instantly share your LLM app with technical and/or non-technical colleagues to collect feedback.
* Interact with and evolve your LLM app (with hot-reloading, logging and replay of your interaction history, hyperparameters, and visibility into execution internals).
* Easily turn your interactions into repeatable test suites for systematic evaluation.
Get started for free by signing up [here](https://app.inductor.ai/signup) or simply running the terminal commands above, to instantly generate a custom playground and turbocharge your LLM app development!
| natalie_inductor | |
1,900,455 | The Innovative DevOps Philosophy at Netflix | Introduction In the realm of digital entertainment, Netflix stands as a paragon of... | 0 | 2024-06-25T18:43:34 | https://dev.to/azeem_shafeeq/the-innovative-devops-philosophy-at-netflix-528h | programming, devops, productivity, learning |
## Introduction
In the realm of digital entertainment, Netflix stands as a paragon of innovation and operational excellence. One of the critical pillars supporting Netflix's success is their unique approach to DevOps. This philosophy transcends traditional metrics and focuses on fostering a culture of freedom, responsibility, and continuous innovation. By examining Netflix's DevOps strategy, we can glean insights into how this tech giant maintains its competitive edge, delivers unparalleled user experiences, and drives business value through technical prowess.
## Netflix’s DevOps Philosophy
### Prioritizing Innovation Over Traditional Metrics
Unlike many organizations that obsess over achieving zero downtime and maintaining rigid operational metrics, Netflix prioritizes innovation. This mindset is crucial in an industry where consumer expectations and technological advancements are perpetually evolving. Instead of focusing on restrictive goals, Netflix empowers its engineers to innovate freely, even at the risk of occasional setbacks.
### Unrestricted Production Access
From the first day, Netflix engineers have full access to the production environment. This level of trust and responsibility is rare in the industry, where access is typically guarded by stringent policies and procedures. By granting this access, Netflix encourages its engineers to take ownership of their work, fostering a culture of accountability and continuous learning.
## Key Components of Netflix’s DevOps Strategy
### Continuous Integration and Delivery (CI/CD)
Netflix’s commitment to CI/CD allows them to update their software thousands of times a day. This rapid iteration cycle ensures that new features, improvements, and bug fixes reach users swiftly, enhancing their overall experience. The CI/CD pipeline at Netflix is a testament to their agility and responsiveness in software development.
### Microservices Architecture
The adoption of a microservices architecture is another cornerstone of Netflix's DevOps strategy. By breaking down applications into smaller, manageable services, Netflix can develop, deploy, and scale each component independently. This modularity enhances flexibility, allowing Netflix to innovate at a granular level without disrupting the entire system.
### Automation and Orchestration
Automation is deeply embedded in Netflix’s operational practices. From testing to deployment, automation reduces manual intervention, minimizes errors, and accelerates delivery processes. Orchestration tools further streamline these processes, ensuring that complex workflows are executed seamlessly.
### Monitoring and Feedback
Comprehensive monitoring and real-time feedback loops are vital to Netflix’s operational success. By continuously monitoring their systems, Netflix can detect and address issues proactively, maintaining high levels of service availability and performance. Feedback mechanisms enable engineers to refine their processes and improve the overall quality of their output.
## Culture of Freedom and Responsibility
Netflix’s DevOps philosophy is encapsulated in their culture of "freedom and responsibility." This cultural framework encourages engineers to experiment, take risks, and learn from failures. The emphasis on responsibility ensures that this freedom does not lead to chaos but rather to thoughtful, well-executed innovation.
### Perspectives from Netflix’s DevOps Team
- "DevOps is not just a set of tools, it's a culture." – Netflix's DevOps team
- "We want to make sure that every engineer is able to deploy code to production on their first day." – Netflix's CTO
- "We're not just deploying software, we're deploying business value." – Netflix's DevOps team
## Impact of DevOps on Netflix’s Operations
### High-Frequency Updates
The ability to update software thousands of times a day is a direct result of Netflix’s robust DevOps practices. This capability allows Netflix to be incredibly responsive to user needs and market changes, maintaining its position as a leader in the streaming industry.
### Exceptional Uptime
Netflix boasts an impressive 99.99% uptime, ensuring that their service is almost always available to users. This reliability is crucial for maintaining user trust and satisfaction, especially in an era where downtime can lead to significant customer churn.
### Scalability and Performance
Handling a massive user base and high traffic volumes requires a resilient and scalable infrastructure. Netflix achieves this through a combination of cloud services, content delivery networks, and proprietary solutions like Netflix Open Connect, their purpose-built video content delivery network (CDN).
## Technical Infrastructure
### Compute and Storage
Netflix relies on Amazon Web Services (AWS) for its compute and storage needs. This cloud-based approach provides the flexibility and scalability necessary to support their global user base.
### UI and Small Assets
For delivering UI components and small assets, Netflix leverages Akamai, a leading content delivery network. This ensures that users receive fast and reliable access to Netflix’s web and mobile interfaces.
### Netflix Open Connect
Netflix Open Connect is a specialized CDN designed to optimize the delivery of video content. By strategically placing servers close to users, Netflix minimizes latency and enhances streaming quality, providing a seamless viewing experience.
## Open Source Contributions
Netflix is not only a consumer of cutting-edge technologies but also a significant contributor to the open-source community. Many of their internal tools and systems are available on their GitHub page, providing valuable resources for other organizations looking to emulate Netflix’s success.
## Conclusion
Netflix exemplifies how a well-implemented DevOps strategy can drive business success and technological excellence. By prioritizing innovation, granting engineers full access from day one, and fostering a culture of freedom and responsibility, Netflix has created an environment where continuous improvement and agility are the norms. Their approach has set a benchmark in the industry, inspiring countless other companies to rethink their DevOps practices.
For more detailed insights into Netflix’s DevOps tools and strategies, you can explore their open-source projects on [Netflix’s GitHub](https://github.com/Netflix).
| azeem_shafeeq |
1,900,452 | Congrats to the Twilio Challenge Winners! | We're thrilled to announce the winners of the Twilio Challenge! From competitive trivia games to... | 0 | 2024-06-25T18:36:51 | https://dev.to/devteam/congrats-to-the-twilio-challenge-winners-2b1n | devchallenge, twiliochallenge, twilio, ai |
We're thrilled to announce the winners of the [Twilio Challenge](https://dev.to/devteam/join-us-for-the-twilio-challenge-5000-in-prizes-4fdi)!
From competitive trivia games to spam detectors to storytelling apps, our panel of judges were positively overwhelmed by the quality of submissions we received. Everyone did such a fantastic job, and we hope you are feeling proud and inspired by everything you learned.
As always, we can only pick a few winners.
## Congratulations To…
### Overall Prompt Winner
@ashiqsultan wins our overall prompt with the HealthLingo app! HealthLingo has the power to save lives by connecting doctors and patients across language barriers.
{% link https://dev.to/ashiqsultan/healthlingo-consult-doctors-from-whatsapp-in-your-native-language-twilio-with-gpt-544m %}
### Prize Category Winners
**Impactful Innovators**
@anshsaini built an immediately useful app that helps people answer a fundamentally confusing question: Is this recyclable?
{% link https://dev.to/anshsaini/recycling-comes-to-whatsapp-63a %}
**Twilio Times Two**
@thegeekyamit utilized multiple Twilio services in order to securely and effectively deliver its chat-based and web-based user experience for personal finance management app.
{% link https://dev.to/thegeekyamit/xpenser-ai-expense-manger-using-twilio-gemini-ai-with-whatsapp-integration-2mk0 %}
**Entertaining Endeavors**
@magodyboy built an entertaining single-player experience for the D&D enthusiasts of the world with an AI-powered dungeon master.
{% link https://dev.to/magodyboy/dungeons-and-twilio-2bm4 %}
Our four winners will receive the following prizes:
**Overall Prompt Winner**
- $2,000 USD
- Exclusive DEV Badge
- A gift from the [DEV Shop](https://shop.forem.com)
**Prize Category Winners (3)**
- $1,000 USD
- Exclusive DEV Badge
- A gift from the [DEV Shop](https://shop.forem.com)
**All Participants** with a valid submission will receive a completion badge on their DEV profile.
## Our Sponsor
We want to give Twilio a major shoutout for organizing this challenge with us. They are simplifying the immensely complex communication systems that surround us with their developer-friendly APIs, and we are so happy they decided to partner with us. @rishabk7, @anthonyjdella, and team were an absolute delight to work with!
If you have any feedback from your experience of building with Twilio, their team is all ears. <mark>Share your honest thoughts by June 30, 2024 and be entered to win a $100 USD gift card. All you have to do is fill out [this survey form](https://surveys.twilio.com/jfe/form/SV_1QZ632HyUWDnxXg).</mark>
## What’s next?
We’ll be launching the **[Wix Studio Challenge](https://dev.to/challenges/wix)** tomorrow (June 13) with our first-ever guest judge @ania_kubow. Ania is a prolific software developer, educator, and course creator best known for her [popular YouTube channel](https://www.youtube.com/@AniaKubow) with over 400,000 subscribers!
{% tag wixstudiochallenge %}
On July 10, we’ll be launching the **[Build Better on Stellar: Smart Contract Challenge](https://dev.to/challenges/stellar)**:
{% tag stellarchallenge %}
Make sure to follow each challenge tag so you don’t miss our announcements!
Thank you to everyone who participated in the Twilio Challenge. We hope you had fun, felt challenged, and maybe added a thing or two to your professional profile. See you next time!
| thepracticaldev |
1,890,492 | HTTP 468 - Keyboard Required (Meme HTTP Code) | Introduction In today's world of sleek touchscreens and voice assistants, you'd think... | 0 | 2024-06-25T18:34:58 | https://dev.to/m_midas/http-468-keyboard-required-4een | webdev, programming, opensource, jokes | ### Introduction
In today's world of sleek touchscreens and voice assistants, you'd think we've moved past the humble keyboard, right? Wrong! Some tasks still need the good ol' clackety-clack of physical keys. Enter HTTP 468 - the status code you never knew you needed, telling you to stop tapping and start typing.
<img style="width:100%" src="https://i.giphy.com/JIX9t2j0ZTN9S.webp">
### The Curious Case of Status Code 468
Why **468**? Well, let's take a time machine back to **1868** when Christopher Latham Sholes, the father of the typewriter, patented his clunky contraption that eventually led to our beloved keyboards. So, 468 is our little tip of the hat to Sholes, acknowledging that sometimes, history does repeat itself (especially if you’re a developer).
### Why HTTP 468 Makes Sense (Seriously)
Despite our futuristic tech, there are still moments when a physical keyboard is non-negotiable:
1. **Novels, Not Novellas**: Writing that epic fantasy novel on a touchscreen? Good luck. Real writers use real keyboards.
2. **Gaming Glory**: Imagine playing a game with on-screen buttons. No, thank you. Gamers know the importance of physical keys for those crucial combos.
3. **Coder’s Paradise**: Trying to code an app on a tablet? That's a no from us. Shortcuts and key commands are life.
### Bringing HTTP 468 to Life
Implementing HTTP 468 is as simple as it gets. Here's a quick example to show you how:
#### Example in Express.js
```javascript
const express = require('express');
const app = express();
function checkForPhysicalKeyboard(req) {
// Logic to determine if the client has a physical keyboard
return false; // Assuming no keyboard for demonstration
}
app.get('/requires-keyboard', (req, res) => {
const hasPhysicalKeyboard = checkForPhysicalKeyboard(req);
if (!hasPhysicalKeyboard) {
res.status(468).send('Keyboard Required');
} else {
res.send('Proceed with the function');
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
In this snippet, if your fancy device doesn’t have a keyboard, you’re getting a friendly reminder in the form of a 468 status code.
### Handling HTTP 468 on the Client Side
When your device gets a 468, it’s like the server giving you a nudge and saying, "Hey, buddy, where's your keyboard?" Here's how to handle it:
#### Example in JavaScript (Client-Side)
```javascript
fetch('/requires-keyboard')
.then(response => {
if (response.status === 468) {
alert('This function requires a physical keyboard. Please connect a keyboard and try again.');
} else {
return response.text();
}
})
.then(data => {
if (data) {
console.log(data);
}
});
```
When you get a 468, it’s time to pull out that Bluetooth keyboard or dust off the old mechanical beast.
### Conclusion
HTTP 468 (Keyboard Required) is your server's way of saying, "Stop being lazy and plug in a keyboard." It's a reminder that while our devices get smarter, sometimes, we need to go back to basics. So next time you find yourself in need of serious typing power, remember Christopher Latham Sholes and thank him for making HTTP 468 possible.
Give HTTP 468 a try in your projects, and ensure your users know that sometimes, nothing beats the tactile joy of a physical keyboard. And hey, if you like the idea, [check out the GitHub repo](https://github.com/midas-png/http-468) and give it a star! Let's spread the love for physical keyboards and better server-client interactions. | m_midas |
1,900,450 | Diving into .NET: From Confusion to Clarity | Recently, I had a conversation with my mentor, and he opened my eyes to the wealth of opportunities... | 0 | 2024-06-25T18:28:37 | https://dev.to/ganatrajay2000/diving-into-net-from-confusion-to-clarity-9ck | csharp, dotnet, beginners, learning | Recently, I had a conversation with my mentor, and he opened my eyes to the wealth of opportunities in the .NET industry. Apparently, there's a substantial number of large companies still running legacy code in .NET. Intrigued by this, I decided to dive into the .NET ecosystem. But oh boy, what a ride it has been!
<br/>
## The Initial Struggle
First things first, .NET and C# have been around for quite a while, and the numerous versions released over the years make it challenging to find beginner-friendly resources. I scoured the internet for blogs and tutorials, only to find myself more confused. It felt like navigating through a maze of outdated and fragmented information.
<br/>
## A Lifeline: The .NET Official YouTube Channel
Just when I was about to give up, I stumbled upon the .NET official YouTube channel. The playlists there were a lifesaver:
1. **[C# for Beginners](https://www.youtube.com/playlist?list=PLdo4fOcmZ0oULFjxrOagaERVAMbmG20Xe)**: This series, featuring Scott Hanselman and .NET Distinguished Engineer David Fowler, was a game-changer. They taught C# from the ground up, covering everything from "Hello World" to LINQ. The lessons were delivered at a comfortable pace, making it easy to follow along.
2. **[Back-end Web Development with .NET for Beginners](https://www.youtube.com/playlist?list=PLdo4fOcmZ0oWunQnm3WnZxJrseIw2zSAk)**: Although this course was quite fast-paced, it provided an excellent introduction to ASP.NET. It covered the hosting model, middleware, and dependency injection, along with building HTTP-based services using minimal APIs.
These playlists kickstarted my .NET journey. During the OOP concepts videos, I could reference what was taught in my Master's course, CSE687 - Object-Oriented Design: by Prof. Nadeem Ghani. It was fascinating to see how those principles applied in the C# world.
<br/>
## The API and SQL Challenge
The next hurdle was figuring out how to take the API from the second playlist and integrate it with SQL. I spent over three days sifting through various resources, only to find fragmented and inconsistent information. Was it just my bad luck? Perhaps. But finally, I discovered Sameer Saini's tutorials on YouTube:
1. **[ASP.NET Web API CRUD Operations - .NET8 and Entity Framework Core Tutorial](https://www.youtube.com/watch?v=6YIRKBsRWVI&t=214s)**: This tutorial was instrumental in helping me understand Entity Framework Core and how to perform CRUD operations.
2. **[ASP.NET Authentication using Identity in 10 Minutes - Authentication and Authorization in .NET8](https://www.youtube.com/watch?v=V-S5JZJUvvU)**: This video simplified the concepts of authentication and authorization using Identity in .NET.
These tutorials were a revelation. They introduced me to the awesome packages like Identity.EntityFrameworkCore and others. However, I noticed that many beginner courses leaned towards creating "fat controllers", which is something I wanted to avoid.
<br/>
## Seeking Best Practices (Not Beginner-Friendly)
Coming from a background in developing enterprise-level applications in Java (Spring) and JavaScript (Node.js), I was keen on finding best practices for .NET. This led me to Tim Deschryver's blog, which provided a deeper understanding of efficient project structuring and best practices:
1. **[Maybe it's time to rethink our project structure with .NET 6](https://timdeschryver.dev/blog/maybe-its-time-to-rethink-our-project-structure-with-dot-net-6)**: This post challenged me to rethink how I structure my .NET projects, introducing concepts like vertical slice architecture and modular design.
2. **[The simplicity of ASP.NET Endpoints](https://timdeschryver.dev/blog/the-simplicity-of-net-endpoints)**: This article offered insights into simplifying ASP.NET endpoints, making the development process more streamlined and efficient.
These blogs were eye-opening and helped me refine my approach to .NET development. The journey from confusion to clarity has been quite the adventure, but with the right resources and guidance, I'm beginning to find my footing in the .NET world.
So, if you're just starting out with .NET, don't be disheartened by the initial chaos. There are excellent resources out there that can guide you through the complexities. Happy coding!
This post is also available on my portfolio, so be sure to check it out at [jayganatra.com](https://jayganatra.com). | ganatrajay2000 |
1,900,449 | From Hobbyist to Professional 🚀 | Hey, DEV Community, I hope you all are doing well! My name is Sushil, and I'm at an exciting yet... | 0 | 2024-06-25T18:26:03 | https://dev.to/sushilmagare10/from-hobbyist-to-professional-3774 | programming, react, learning, javascript | Hey, **DEV Community**,
I hope you all are doing well! My name is Sushil, and I'm at an exciting yet challenging crossroads in my development journey. I've been coding for a while now and have created several projects, but I'm looking to transition from being a hobbyist to landing my first professional developer role.
Currently, I'm building a social media app with features for user authentication, profile management, a main feed, friend requests, and more.
The Github Repo: https://github.com/sushilmagare10/Bubble
While I'm proud of the progress I've made, I know there's a lot more to learn. Here are a few areas where I'm seeking guidance:
## Code Review and Best Practices 🛠️
- I'd love for experienced developers to review my code and suggest improvements, especially regarding best practices and efficient coding techniques. 🚀
- Tips on advanced 💻 JavaScript concepts and deeper insights into React for creating more dynamic and efficient components.
- Advice on structuring larger projects 🌱 and making them scalable for future growth.
- Tips on transitioning from personal projects to professional work, including resume building, job searching, and interview preparation.
- Guidance on writing more professional-level code and following best practices.📝
- Best practices for using Git effectively and professionally, including branching strategies and commit message conventions🌳.
- Advice on managing preview and production level code, including setting up and handling different environments🚦.
Any constructive feedback on my current project would be precious.
I'm committed to improving my skills and becoming a professional developer. Any advice, feedback, or resources you can provide will be greatly appreciated. Thank you for taking the time to read my post, and I'm looking forward to any guidance you can offer!
| sushilmagare10 |
1,900,447 | How to Create A Snake Game in HTML CSS & JavaScript | Snake is a classic game that millions of people have played. Have you ever thought about creating... | 0 | 2024-06-25T18:22:44 | https://www.codingnepalweb.com/create-snake-game-htm-css-javascript/ | webdev, javascript, html, css | Snake is a classic game that millions of people have played. Have you ever thought about creating your own Snake Game? Creating a Snake Game using [HTML, CSS](https://www.codingnepalweb.com/category/html-and-css/), and vanilla JavaScript is a fun and educational project that can improve your web development skills.
In this [blog](https://www.codingnepalweb.com/category/blog/) post, I’ll guide you through the steps of creating your own Snake Game from scratch. You can play this game on a PC using keyboard arrow keys or on a mobile device using touch-based arrow buttons.
If you’re excited to see how this snake game looks and works, [click here](https://codingnepalweb.com/demos/snake-game-javascript/) to play it. For a full video tutorial on creating a snake game using HTML, CSS and [JavaScript](https://www.codingnepalweb.com/category/javascript/), you can watch the given YouTube video.
## Video Tutorial of Snake Game in JavaScript
{% embed https://www.youtube.com/watch?v=K8Rh5x3c9Pw %}
Making a Snake Game is not only fun, but it can also help you develop problem-solving skills and the ability to break down complex problems into smaller ones. So, I highly recommend that you watch the above video tutorial to the end.
In the video, I tried to explain each line with comments and show which code does what in the game. But if you wish, you can skip the video tutorial and continue reading this post to create a snake game on your own.
## Steps For Creating Snake Game in JavaScript
To create a snake game using HTML, CSS, and JavaScript, follow the given steps line by line:
- Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
- Create an `index.html` file. The file name must be index and its extension .html
- Create a `style.css` file. The file name must be style and its extension .css
- Create a `script.js` file. The file name must be script and its extension .js
To start, add the following HTML codes to your `index.html` file to create the game’s basic layout. The “play-board” container is empty now, but it will be filled with snake bodies and food elements later using JavaScript code.
```html
<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Snake Game JavaScript | CodingNepal</title>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="wrapper">
<div class="game-details">
<span class="score">Score: 0</span>
<span class="high-score">High Score: 0</span>
</div>
<div class="play-board"></div>
<div class="controls">
<i data-key="ArrowLeft" class="fa-solid fa-arrow-left-long"></i>
<i data-key="ArrowUp" class="fa-solid fa-arrow-up-long"></i>
<i data-key="ArrowRight" class="fa-solid fa-arrow-right-long"></i>
<i data-key="ArrowDown" class="fa-solid fa-arrow-down-long"></i>
</div>
</div>
</body>
</html>
```
Next, add the following CSS codes to your `style.css` file to make the layout of the Snake game. Remember that control arrow keys are only shown on small devices, such as phones. If you prefer to display them on all devices, you can easily modify the media query code.
```css
/* Import Google font */
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600;700&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Open Sans', sans-serif;
}
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #E3F2FD;
}
.wrapper {
width: 65vmin;
height: 70vmin;
display: flex;
overflow: hidden;
flex-direction: column;
justify-content: center;
border-radius: 5px;
background: #293447;
box-shadow: 0 20px 40px rgba(52, 87, 220, 0.2);
}
.game-details {
color: #B8C6DC;
font-weight: 500;
font-size: 1.2rem;
padding: 20px 27px;
display: flex;
justify-content: space-between;
}
.play-board {
height: 100%;
width: 100%;
display: grid;
background: #212837;
grid-template: repeat(30, 1fr) / repeat(30, 1fr);
}
.play-board .food {
background: #FF003D;
}
.play-board .head {
background: #60CBFF;
}
.controls {
display: none;
justify-content: space-between;
}
.controls i {
padding: 25px 0;
text-align: center;
font-size: 1.3rem;
color: #B8C6DC;
width: calc(100% / 4);
cursor: pointer;
border-right: 1px solid #171B26;
}
@media screen and (max-width: 800px) {
.wrapper {
width: 90vmin;
height: 115vmin;
}
.game-details {
font-size: 1rem;
padding: 15px 27px;
}
.controls {
display: flex;
}
.controls i {
padding: 15px 0;
font-size: 1rem;
}
}
```
Finally, add the following JavaScript code to your `script.js` file to add functionality for the snake game. This code will handle the logic behind the snake’s movement, eating food, updating the score, and detecting collisions with walls or its own body.
```javascript
const playBoard = document.querySelector(".play-board");
const scoreElement = document.querySelector(".score");
const highScoreElement = document.querySelector(".high-score");
const controls = document.querySelectorAll(".controls i");
let gameOver = false;
let foodX, foodY;
let snakeX = 5, snakeY = 5;
let velocityX = 0, velocityY = 0;
let snakeBody = [];
let setIntervalId;
let score = 0;
// Getting high score from the local storage
let highScore = localStorage.getItem("high-score") || 0;
highScoreElement.innerText = `High Score: ${highScore}`;
const updateFoodPosition = () => {
// Passing a random 1 - 30 value as food position
foodX = Math.floor(Math.random() * 30) + 1;
foodY = Math.floor(Math.random() * 30) + 1;
}
const handleGameOver = () => {
// Clearing the timer and reloading the page on game over
clearInterval(setIntervalId);
alert("Game Over! Press OK to replay...");
location.reload();
}
const changeDirection = e => {
// Changing velocity value based on key press
if(e.key === "ArrowUp" && velocityY != 1) {
velocityX = 0;
velocityY = -1;
} else if(e.key === "ArrowDown" && velocityY != -1) {
velocityX = 0;
velocityY = 1;
} else if(e.key === "ArrowLeft" && velocityX != 1) {
velocityX = -1;
velocityY = 0;
} else if(e.key === "ArrowRight" && velocityX != -1) {
velocityX = 1;
velocityY = 0;
}
}
// Calling changeDirection on each key click and passing key dataset value as an object
controls.forEach(button => button.addEventListener("click", () => changeDirection({ key: button.dataset.key })));
const initGame = () => {
if(gameOver) return handleGameOver();
let html = `<div class="food" style="grid-area: ${foodY} / ${foodX}"></div>`;
// Checking if the snake hit the food
if(snakeX === foodX && snakeY === foodY) {
updateFoodPosition();
snakeBody.push([foodY, foodX]); // Pushing food position to snake body array
score++; // increment score by 1
highScore = score >= highScore ? score : highScore;
localStorage.setItem("high-score", highScore);
scoreElement.innerText = `Score: ${score}`;
highScoreElement.innerText = `High Score: ${highScore}`;
}
// Updating the snake's head position based on the current velocity
snakeX += velocityX;
snakeY += velocityY;
// Shifting forward the values of the elements in the snake body by one
for (let i = snakeBody.length - 1; i > 0; i--) {
snakeBody[i] = snakeBody[i - 1];
}
snakeBody[0] = [snakeX, snakeY]; // Setting first element of snake body to current snake position
// Checking if the snake's head is out of wall, if so setting gameOver to true
if(snakeX <= 0 || snakeX > 30 || snakeY <= 0 || snakeY > 30) {
return gameOver = true;
}
for (let i = 0; i < snakeBody.length; i++) {
// Adding a div for each part of the snake's body
html += `<div class="head" style="grid-area: ${snakeBody[i][1]} / ${snakeBody[i][0]}"></div>`;
// Checking if the snake head hit the body, if so set gameOver to true
if (i !== 0 && snakeBody[0][1] === snakeBody[i][1] && snakeBody[0][0] === snakeBody[i][0]) {
gameOver = true;
}
}
playBoard.innerHTML = html;
}
updateFoodPosition();
setIntervalId = setInterval(initGame, 100);
document.addEventListener("keyup", changeDirection);
```
In the code, you can see that the current speed of the snake is 100 milliseconds, which determines how quickly the snake moves on the game board. You can easily adjust this speed by changing the value in the “setInterval” function at the bottom of the code.
To understand the code more deeply, you can watch the above YouTube video tutorial or read the comments within the code and experiment with it.
## Conclusion and Final Words
By following the steps in this blog post, you have successfully created a classic snake game using HTML, CSS, and JavaScript which you can play on any device browser. I hope this snake game project helps you understand DOM manipulation, problem-solving skills, and other web development skills.
If you enjoyed creating your Snake Game and learned something new, you can check out my other [JavaScript Games](https://www.codingnepalweb.com/category/javascript-games/). These games are not only enjoyable to create but also provide an excellent opportunity to practice and enhance your JavaScript skills.
If you encounter any problems while creating your snake game, you can download the source code files for this game 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://codingnepalweb.com/demos/snake-game-javascript/)
[Download Code Files](https://www.codingnepalweb.com/create-snake-game-htm-css-javascript/) | codingnepal |
1,900,446 | Building a Pet Diagnosis Assistant using Lyzr SDK | In today’s tech-driven world, AI is making significant strides in healthcare, including veterinary... | 0 | 2024-06-25T18:22:11 | https://dev.to/akshay007/building-a-pet-diagnosis-assistant-using-lyzr-sdk-4p4i | ai, pet, programming, python | In today’s tech-driven world, AI is making significant strides in healthcare, including **veterinary care**. Imagine having a virtual assistant that can provide expert advice based on your pet’s breed, age, and symptoms. With **Lyzr Automata** and **Streamlit**, you can build a powerful **Pet Diagnosis Assistant**. This guide will walk you through the process step-by-step.

The **Pet Diagnosis Assistant** uses **Lyzr Automata** and **OpenAI’s GPT-4 model** to offer expert veterinary advice. By entering details about your pet, such as breed, age, and symptoms, you can receive tailored guidance and preliminary diagnoses.
**Why use Lyzr SDK’s?**
With **Lyzr SDKs**, crafting your own **GenAI** application is a breeze, requiring only a few lines of code to get up and running swiftly.
[Checkout the Lyzr SDK’s](https://docs.lyzr.ai/introduction)
**Lets get Started**
**Setting Up the Environment**
First, ensure you have Streamlit and Lyzr Automata installed. You can install these packages using pip:
```
pip install streamlit lyzr-automata
```
Start by importing the necessary libraries and setting up your **Streamlit** app:
```
import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent, Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
import os
```
**Configuring the OpenAI API Key**
Ensure your **OpenAI API key** is set. You can securely store and access it using Streamlit secrets:
```
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
```
**Input Section**
An **input field** snipped for users to provide their pet’s information:
```
st.title("Pet Diagnosis Assistant 🐶")
st.markdown("Welcome to the Pet Diagnosis Assistant! Tell us about your pet's symptoms, and we'll provide expert advice tailored to their breed and age, helping you understand and address their health concerns.")
input = st.text_input("Please enter the breed, age, and the concerns:", placeholder="Type here")
```
**Setting Up the AI Model**
Configure the **OpenAI model** for text completion:
```
open_ai_text_completion_model = OpenAIModel(
api_key=st.secrets["apikey"],
parameters={
"model": "gpt-4-turbo-preview",
"temperature": 0.2,
"max_tokens": 1500,
},
)
```
**Creating the Generation Function**
Define a **function** to generate the veterinary advice:
```
def generation(input):
generator_agent = Agent(
role="Expert VETERINARY DIAGNOSTICIAN",
prompt_persona="Your task is to ANALYZE the user-provided data on their pet's breed, age, and visible symptoms or issues observed. You MUST CAREFULLY provide the necessary diagnosis and step-by-step guidance."
)
prompt = f"""
You are an Expert VETERINARY DIAGNOSTICIAN. Your task is to ANALYZE the user-provided data on their pet's breed, age, and visible symptoms or issues observed. You MUST CAREFULLY provide the necessary diagnosis and step-by-step guidance.Follow this sequence of steps:
[Prompts here]
"""
generator_agent_task = Task(
name="Generation",
model=open_ai_text_completion_model,
agent=generator_agent,
instructions=prompt,
default_input=input,
output_type=OutputType.TEXT,
input_type=InputType.TEXT,
).execute()
return generator_agent_task
```
**Adding the Assist Button**
Add a **button** that triggers the generation function when clicked:
```
if st.button("Assist!"):
solution = generation(input)
st.markdown(solution)
```
With these steps, you can create a **Pet Diagnosis Assistant** that provides expert advice based on your pet’s details. This application not only demonstrates the capabilities of Lyzr Automata and Streamlit but also highlights how AI can be leveraged to enhance pet care.
**App link**: https://petassistant-lyzr.streamlit.app/
**Source Code**: https://github.com/isakshay007/Pet_Assistant
The **Pet Diagnosis Assistant** is powered by the Lyzr Automata Agent, utilizing the capabilities of OpenAI’s GPT-4 . For any inquiries or issues, please contact Lyzr. You can learn more about Lyzr and their offerings through the following links:
**Website**: [Lyzr.ai](https://www.lyzr.ai/)
**Book a Demo**: [Book a Demo](https://www.lyzr.ai/book-demo/)
**Discord**: [Join our Discord community](https://discord.com/invite/nm7zSyEFA2)
**Slack**: [Join our Slack channel](https://anybodycanai.slack.com/join/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw#/shared-invite/email) | akshay007 |
1,900,437 | 20 Novel AI Prompts Made Possible Only by Pieces Copilot+ | Discover 20 novel AI prompts powered by Live Context that transform your developer workflow by providing contextual assistance across your tasks. | 0 | 2024-06-25T18:12:44 | https://code.pieces.app/blog/20-novel-ai-prompts-made-possible-only-by-pieces-copilot | <figure><img src="https://d37oebn0w9ir6a.cloudfront.net/account_32099/unique-prompts_384c59116630f531fbfe87bac59cb3bb.jpg" alt="Person wearing a hat staring at an out-of-focus computer monitor."/></figure>
AI tools have significantly advanced developer productivity, but their true potential is unlocked only when they’re seamlessly integrated into your workflow and prompted properly.
[Pieces Copilot+ with Live Context](https://code.pieces.app/blog/introducing-pieces-copilot-now-with-live-context) augments the everyday developer experience by providing contextual assistance tailored to your workflow. Live Context is a groundbreaking feature that captures and processes workflow data in real time, [directly on your device for air-gapped security](https://code.pieces.app/blog/an-air-gapped-approach-to-maximizing-developer-productivity-with-pieces-copilot-and-live-context), enabling unique prompts and insights that no other AI tool can offer.
This feature can be leveraged across the three main pillars of a developer's workflow—researching and problem-solving in the browser, coding in the IDE, and collaborating with colleagues—along with broader use cases for reducing context switching and improving overall productivity. See how these novel AI prompts can 10x your workflow and [get started with our desktop app](https://docs.pieces.app/installation-getting-started/what-am-i-installing) to try it out for yourself!
## Researching and Problem Solving in the Browser
Researching and problem-solving are critical parts of a developer's day, often involving extensive browsing and information gathering. Live Context in Pieces Copilot+ can streamline this process, ensuring that valuable insights are never lost.
**1. What were the main takeaways from the research I did last week on this topic?**
**Example:** Imagine you spent several hours last week researching the latest trends in machine learning algorithms. With Live Context, you can quickly retrieve a summary of your findings, including key points and insights, without having to go through all your notes and browser history.
**Benefit:** This feature saves time and ensures that valuable insights are never lost. It allows you to focus on applying the research rather than spending time finding it again.
{% embed https://youtu.be/GFdi33oNO24 %}
**2. What from yesterday’s research can help me here?**
**Example:** Suppose you were researching optimization algorithms yesterday and today you encounter a problem related to algorithm efficiency. This prompt will help you quickly access the key points and insights from your previous research, saving you time and effort.
**Benefit:** This novel AI prompt retrieves relevant research information from the previous day, helping you quickly find useful data without retracing your steps. It ensures that valuable insights are not lost and can be applied immediately, enhancing productivity and decision-making.
**3. Summarize this research paper.**
**Example:** Suppose you have a 20-page research paper on neural networks that you need to understand quickly. Live Context can provide a concise summary of the paper, highlighting the main points, methodologies, and conclusions.
**Benefit:** This prompt saves you time and effort by distilling complex information into an easily digestible format, allowing you to grasp the essential points without reading the entire document.
**4. What are the steps to implement this tool based on their docs?**
**Example:** You are looking to integrate a new API into your project. Live Context can extract the necessary steps from the documentation and present them in a clear, actionable format.
**Benefit:** This feature provides quick and accurate integration steps, reducing the time spent on understanding and implementing new tools.
**5. Where did I find that Python script I forgot to save in my research yesterday?**
**Example:** You remember finding a useful Python script during your research but forgot to save it. Live Context can help you locate the script by searching through your recent activities and browser history.
**Benefit:** This novel AI prompt prevents the loss of valuable research findings and saves you from retracing your steps to find the same information again.
## Coding in the IDE
Live Context enhances coding efficiency by providing instant access to relevant information and context, helping you navigate and manage your codebase more effectively. The following 5 novel AI prompts can help you write better code, faster.
**6. My coworker is on vacation, can you explain this new repo I’m onboarding into?**
**Example:** You need to understand a new repository your team is working on, but the main contributor is on vacation. Live Context can provide an overview and explanation of the repository, including its structure, key files, and recent changes.
**Benefit:** Live Context helps you quickly get up to speed with new projects, reducing the dependency on other team members and enabling smoother onboarding.
{% embed https://youtu.be/vNTvxW4oVm0 %}
**7. How can I resolve this issue I just came across?**
**Example:** If you encounter a syntax error or a bug in your code, this prompt will analyze your past coding patterns and errors to suggest potential fixes, making the debugging process faster and more efficient.
**Benefit:** Identifies solutions based on past coding patterns and errors, streamlining the troubleshooting process. This feature reduces the time spent on debugging by providing quick and accurate solutions, thereby improving coding efficiency and minimizing downtime.
**8. Summarize the code changes in this PR and highlight areas that need attention based on past code reviews.**
**Example:** You are reviewing a pull request with numerous changes. Live Context can summarize the changes and highlight areas that might need closer inspection based on past code review comments.
**Benefit:** This AI prompt streamlines the code review process, making it easier to identify critical changes and potential issues, thereby improving code quality and collaboration.
**9. Adapt this boilerplate to fit into my existing code.**
**Example:** When you need to add a new feature using boilerplate code, this prompt will help you adapt the boilerplate to match your project's coding style and structure, ensuring a smooth integration.
**Benefit:** Modifies boilerplate code to seamlessly integrate with your existing codebase, enhancing efficiency. This ensures that the new code adheres to your project's standards and reduces the risk of integration issues, saving time and effort in the development process.
**10. Identify if this error has occurred before in this project and suggest the previous fix.**
**Example:** If you encounter an error message that looks familiar, this prompt will check your project's history to see if the same error has occurred before and suggest the fix that was previously applied, saving you time and effort.
**Benefit:** Detects recurring errors and provides previous fixes, reducing repetitive debugging efforts. This feature helps maintain a historical record of issues and solutions, making it easier to resolve similar problems in the future and improving overall project stability.
## Collaborating with Colleagues
Effective collaboration is essential for successful project development. Live Context helps you stay synchronized with your team, ensuring smooth communication and task management.
**11. Generate action items based on the ongoing conversation in Google Chat.**
**Example:** During a team chat about an upcoming machine learning project, several tasks and action items are discussed. Live Context can automatically generate a list of these action items, ensuring nothing is missed.
**Benefit:** This feature enhances team productivity by capturing and organizing tasks in real time, reducing the risk of overlooking important action items.
{% embed https://youtu.be/1Pa3WxSrC2w %}
**12. Summarize this active channel in Slack / what my coworker was just explaining.**
**Example:** If you were away from your desk and missed an active discussion in a Slack channel, this prompt will provide a concise summary of the conversation, helping you quickly get up to speed.
**Benefit:** These novel AI prompts generate real-time summaries, ensuring you stay updated without constant monitoring. This allows you to quickly grasp the context of ongoing conversations, making it easier to contribute effectively and stay informed about important developments.
**13. Write a concise recap of my team meeting based on the transcript.**
**Example:** After a team meeting, this prompt will generate a concise recap based on the transcript, highlighting key points and action items, and ensuring that all team members are aligned and informed.
**Benefit:** Creates succinct recaps, helping everyone stay on the same page and informed. This feature highlights key points and action items, ensuring that all team members are aligned and aware of their responsibilities, which enhances team collaboration and productivity.
**14. When’s the best time to set up a sync with my team based on our shared calendars?**
**Example:** When you need to schedule a team sync, this prompt will analyze the availability of all team members based on their shared calendars and suggest the best time for the meeting, making scheduling more efficient.
**Benefit:** Analyzes shared calendars to suggest optimal meeting times, simplifying scheduling. This reduces the back-and-forth communication typically involved in scheduling, making it easier to find a time that works for everyone and improving overall meeting efficiency.
**15. Summarize the open Jira tasks along with IDs, descriptions, names, and due dates.**
**Example:** When planning your work for the week, this prompt will provide a summary of all open Jira tasks, including IDs, descriptions, assignees, and due dates, helping you prioritize and manage tasks more effectively.
**Benefit:** Provides a comprehensive summary of open tasks, facilitating better task management and prioritization. This feature helps you keep track of all ongoing tasks, ensuring that nothing falls through the cracks and that deadlines are met, thereby improving project management.
## Context Switching Across Various Tools and Improving Productivity
[Reducing context switching](https://code.pieces.app/blog/minimizing-the-cost-of-context-switching-for-developers) and improving productivity are key goals for any developer. Live Context ensures a seamless transition between tasks and tools, maintaining workflow continuity.
**16. Can you help me pick up where I left off before lunch?**
**Example:** After a lunch break, you need to resume your work on a complex coding task. Live Context can remind you of your last activities, including open files, recent edits, and pending tasks.
**Benefit:** Ensures a seamless transition back to your work by recalling your last activities, which minimizes disruption and helps you quickly regain focus, thereby enhancing overall productivity.
{% embed https://youtu.be/hcGQBpJkHTE %}
**17. What was I working on yesterday?**
**Example:** After a weekend or a day off, this prompt will remind you of the tasks and projects you were working on the previous day.
**Benefit:** Helps you quickly pick up from where you left off, reducing the time spent on regaining focus. This feature provides a seamless transition between work sessions, ensuring that you can maintain momentum and productivity without having to spend time recalling previous tasks.
**18. Summarize what I did today for my PM.**
**Example:** At the end of the workday, this prompt will generate a summary of your activities, including completed tasks and progress made, which you can share with your project manager for better tracking and reporting.
**Benefit:** Generates daily summaries of your activities, aiding in effective project management and reporting. This feature ensures that your project manager is kept informed of your progress, helping to maintain transparency and accountability within the team.
**19. What are the main roadblocks for this release based on open GitHub issues?**
**Example:** When preparing for a software release, this prompt will analyze open GitHub issues to identify and summarize the main roadblocks, helping you address them proactively and ensure a smooth release process.
**Benefit:** Identifies and summarizes key blockers, enabling proactive resolution. This feature helps you address potential issues before they become critical, ensuring a smoother release process and reducing the risk of delays or failures.
**20. Analyze my recent workflow and suggest ways to reduce context switching.**
**Example:** You feel that frequent context switching is affecting your productivity. Live Context can analyze your recent activities and suggest ways to streamline your workflow, such as batching similar tasks or minimizing interruptions.
**Benefit:** This feature helps improve productivity by identifying and mitigating factors that cause context switching, allowing you to maintain better focus on your tasks.
## Conclusion
Live Context in Pieces Copilot+ is a powerful tool that enhances developer productivity by providing contextual assistance tailored to different aspects of your workflow. Whether you are researching, coding, collaborating, or trying to reduce context switching, Live Context ensures you have the right information at the right time, helping you work more efficiently and effectively.
[According to Greg Brockman](https://x.com/gdb/status/1634708489078706179?lang=en) at OpenAI, “Prompt engineering is the art of communicating eloquently to an AI.” With Pieces Copilot+, you can pose less specific queries because it simply has access to more information. Please remember that results vary according to [which LLM you’re using](https://code.pieces.app/blog/best-llm-for-coding-cloud-vs-local) within Pieces.
Try out these unique use cases in our [desktop app](https://docs.pieces.app/installation-getting-started/what-am-i-installing) so you too can **remember anything and interact with everything**. | get_pieces | |
1,899,846 | Deploy Laravel application using Vercel | Hello Artisans, In this blog post, we will see how to deploy the laravel application on Vercel. It... | 0 | 2024-06-25T18:10:44 | https://dev.to/snehalkadwe/deploy-laravel-application-using-vercel-42de | laravel, php, vercel, womenintech | **Hello Artisans,**
In this blog post, we will see how to deploy the laravel application on Vercel. It is a popular serverless platform.
**Step 1:** First, we create a new laravel application.
```php
composer create-project laravel/laravel laravel-vercel-project
```
**Step 2:** Create `api` folder, within that folder create `index.php` file, and add the code below.
```php
<?php
require __DIR__ . "/../public/index.php";
```
It is an entry point that will forward the control to `public/index.php` file which normally gets called when we visit our laravel application.
**Step 3:** Create `.vercelignore` file and add the below line in it.
```php
/vendor
```
**Step 4:** Now create `vercel.json` file and add the below code
```php
{
"version": 2,
"framework": null,
"functions": {
"api/index.php": { "runtime": "vercel-php@0.6.0" }
},
"routes": [
{
"src": "/(.*)",
"dest": "/api/index.php"
}
],
"env": {
"APP_ENV": "production",
"APP_DEBUG": "true",
"APP_URL": "https://your.url.from.vercel.app",
"APP_KEY": add API key here from your .env file",
"APP_CONFIG_CACHE": "/tmp/config.php",
"APP_EVENTS_CACHE": "/tmp/events.php",
"APP_PACKAGES_CACHE": "/tmp/packages.php",
"APP_ROUTES_CACHE": "/tmp/routes.php",
"APP_SERVICES_CACHE": "/tmp/services.php",
"VIEW_COMPILED_PATH": "/tmp",
"CACHE_DRIVER": "array",
"LOG_CHANNEL": "stderr",
"SESSION_DRIVER": "cookie"
}
}
```
- In the above code `routes` array will forward all incoming URIs to our newly set serverless function which we created in `Step 2`.
```php
"routes": [{
"src": "/(.*)",
"dest": "/api/index.php"
}],
```
- `env` will be our Vercel's env file.
**Step 4:** The last step is to create `dist` folder in the project directory.
- Now save all the files and push your repository to GitHub. Now login to your Vercel application.
- On the right side click `Add New` then select `Project` option. After that import your laravel application from GitHub.

- Now we will configure our project by giving a name to the project.
- Then select the `other` option from `Framework Preset`.

- The next step is to add the required env.
If your deployment has failed go to the home page select the project then go to settings

- In the General section go to `Node.js version` section and select the node version as `18x`, save the changes, and trigger to re-deploy the application.
- Tada!! Your application is live now.
**Happy Reading**
:unicorn: :heart:
| snehalkadwe |
1,900,434 | Guia para Iniciantes: Contribuindo em Projetos Open Source Passo a Passo | Um exemplo prático de como contribuir em projetos open source Dar os primeiros passos no universo... | 0 | 2024-06-25T18:06:15 | https://dev.to/oigorleal/guia-para-iniciantes-contribuindo-em-projetos-open-source-passo-a-passo-1fd8 | ruby, opensource, github, contributorswanted | > Um exemplo prático de como contribuir em projetos open source
Dar os primeiros passos no universo do código aberto pode ser intimidante. Desde quando comecei a programar, meu desejo sempre foi contribuir para projetos que fossem impactantes e desafiadores. Compartilho aqui um caminho acessível e prático para ajudar outros aspirantes a desenvolvedores a superarem esse desafio inicial e começarem a contribuir efetivamente para projetos open source.
## Começando Pequeno, Aprendendo Grande
Contribuir para projetos open source pode parecer assustador à primeira vista, mas a chave é começar com algo pequeno. Não se preocupe se for algo extremamente simples. São dessas pequenas mudanças que você aprenderá mais sobre o projeto e se familiarizará com seu código.
## Escolhendo o Projeto Adequado
O primeiro passo é escolher um projeto! E aqui vão algumas dicas de quais critérios usar para escolher o seu:
1. Pesquise por projetos com temas de seu interesse
2. Priorize tecnologias com as quais você esteja familiarizado.
Sites como GitHub e GitLab são excelentes plataformas para descobrir projetos que aceitam contribuições.
Para demonstrar esse processo, escolhi um projeto que achei muito interessante: o Meybe, um gerenciador de finanças open source desenvolvido em Ruby. Escolhi esse projeto pois já tive alguma experiência com Ruby anteriormente e me identifiquei com seu objetivo.

https://maybe.co/
## Explore o projeto
Com o projeto selecionado, mergulhe de cabeça: instale-o e explore todas as funcionalidades possíveis. Experimente ajustar configurações, inserir dados significativos, executar testes rigorosos, mergulhar na documentação detalhada e investigar o código-fonte para entender completamente sua estrutura e as possibilidades que oferece.
## Encontrando um problema simples
A maior parte dos projetos tem uma lista de problemas a serem resolvidos. Busque por problemas simples que possa você possa resolver. Evite o erro comum de tentar desenvolver sozinho uma nova funcionalidade muito complexa do projeto, especialmente quando ainda não conhece completamente o código. Comece com problemas pequenos, como correções de bugs ou pequenas melhorias.
Por exemplo, ao procurar as issues do projeto encontrei o seguinte problema: A issue #861 do projeto descreve um bug onde, durante a importação de transações, ao voltar para a etapa "mappings", todas as colunas do formulário são redefinidas.

https://github.com/maybe-finance/maybe/issues/861
## Resolvendo o Problema
Depois de algumas boas horas investigando e compreendendo a causa do problema, descobri que a questão estava na função:
```ruby
def get_selected_header_for_field(field)
column_mappings&.dig(field) || field.key
end
```
O método `dig` estava recebendo o objeto `field` inteiro ao invés do atributo `field.key`. A solução foi ajustar para:
```ruby
def get_selected_header_for_field(field)
column_mappings&.dig(field.key) || field.key
end
```
Este simples ajuste resolveu o problema e pude verificar a correção localmente antes de submeter minha contribuição.
## Faça um Pull Request da Solução
Depois de identificar e corrigir o problema, é hora de enviar suas alterações para o repositório original através de um pull request. Esse processo envolve criar uma nova branch, commit suas alterações, e então abrir o pull request no GitHub.
Certifique-se de descrever claramente as mudanças que você fez e porque elas são necessárias. Inclua detalhes específicos sobre como testou a solução para garantir que o bug foi realmente corrigido. A revisão e aceitação desse pull request pelos mantenedores do projeto são as etapas finais para ver sua contribuição ser integrada ao projeto.
## Conclusão
Contribuir para projetos open source não só amplia seu conhecimento técnico, mas também é uma oportunidade de se conectar com uma comunidade global de desenvolvedores. Começar com passos pequenos e alcançáveis é a melhor maneira de mergulhar nesse mundo colaborativo. Com perseverança e disposição para aprender, você pode transformar pequenas contribuições em um impacto significativo no projeto. Agora é sua vez de começar e explorar o vasto mundo dos projetos open source! | oigorleal |
1,899,718 | Master JavaScript “this” keyword to pass job interview | Glossary Lexical scope aka lexical context or scope. Determines which variables and... | 27,851 | 2024-06-25T18:00:00 | https://javascript.plainenglish.io/javascript-this-keyword-in-simple-words-893827076eb2 | javascript, interview, webdev, beginners | ## Glossary
**Lexical scope** aka _lexical context_ or _scope_.
Determines which variables and functions can be accessed by a part of a code. For example, `const` variable, defined inside a code block can’t be accessed outside that block.
```js
{
const blockScopedVar = 1
}
console.log(blockScopedVar) // Error. blockScopedVar is not defined
```
In this example, _lexical scope_ of `console.log()` does not contain `blockScopedVar`.
Under the hood, _lexical scope_ is defined by _lexical Environment chain._
**Execution context**
In simplified terms, it is an environment, in which the current function is running. JavaScript code is executed by dividing the code into ‘pieces’ and running them sequentially. These ‘pieces’ are execution contexts. Execution context created for global context and per each function call. When a function being invoked, execution context is created. Execution context contains a value of `this`, _lexical scope,_ and other internal stuff required to run this function.
**"this" keyword**
`this` keyword is usually used in methods or classes, making it easy to point the function to an object’s properties we want to use. `this` in JS is just a reference to an object. This reference can be set:
- implicitly (when a new _execution context_ is being created)
- explicitly (with `call()`, `apply()`, `bind()` methods).
The implicit value of `this` is determined by where in the code `this` is being used (in what context). This is causing most confusion and the way to sort this out is to know what `this` contexts exist and how they affect the value of `this`.
## Implicit contexts
At the creation phase of _execution context,_ the value of `this` is assigned automatically, based on where `this` in code is being used. Sometimes this is called `this` _context_ (not to be confused with _execution context_ or _lexical context_)
``` js
function executionContext1 () {
console.log(this.a) // `this` is used in globally invoked function context
}
const obj1 = {
a: 1,
executionContext2() {console.log(this.a)} // `this` is used in method context
};
executionContext1() // execution context with `this` pointing to global object being created to execute this function
executionContext2() // execution context with `this` pointing to `obj1` being created to execute this function
```
`this` contexts, determining its value:
- Global context (when this placed outside of functions or classes): this -> global object
- Function context (when this placed inside the function)
- Globally invoked function: this -> global object
- Method: this -> object, on which method being called
- Constructor function: this -> instance object
- Arrow function: Exception. Do not have this. this -> inherited from outer function scope
- Event handler context
- Class context
### Global context
If `this` is used outside of functions or classes, it will be pointing to the global environment (`window` in a browser or `global` in NodeJS)
```js
console.log(this) // [object Window]
```
### Function context
`this` is determined by how the function is called, not how it is declared.
Except for an _arrow function_, when a value of `this` is determined by where an arrow function is declared.
#### Globally invoked function
If a function is called In a global context, `this` refers to the _global object_.
```js
function printThis() {
console.log(this)
}
printThis() // Window // or undefined in strict mode
```
Notice that the value of `this` in a globally invoked function can be altered by the `"use strict"` directive.
#### Method
If a function is called as a method of an object, `this` will refer to that object (on the left side of the dot before a method). For `a.b.c.func()` `this` will be `c`
```js
const obj1 = {
a: 1,
log() {console.log(this.a)}
};
const obj2 = {
a: 2,
log: obj1.log
};
obj2.log(); // 2, because method is being called on `obj2`
```
#### Constructor Function
If `this` is used inside a constructor function, it points to the created instance of this constructor.
```js
function Person(name, birthYear) {
this.name = name // `this` will reference the instanse, so `name` will be added to `beatrix`
this.birthYear = birthYear // `this` will reference the instanse, so `birthYear` will be added to `beatrix`
this.describe = function() { // `describe()` will be added to `beatrix`
console.log(`${this.name} was born in ${this.birthYear}.`)
// `this` will be pointing to the object on which `describe` will be called (method context)
}
}
const beatrix = new Person('Beatrix', 2005)
beatrix.describe() // "Beatrix was born in 2005."
console.log(beatrix.name) // "Beatrix"
```
#### Arrow Function
Arrow functions are a special case, which makes `this` more tricky. They do not have their own `this` and inherit `this` value from the closest enclosing function scope. `this` value depends on how a function is declared, not how it is called (like with “normal” functions). In other words, `this` in arrow functions will point to the ‘owner’ of a function, despite where this function is being invoked. It means, that calling arrow functions as methods might result in an unexpected behavior:
```js
const obj = {
a: 1,
arrow: () => console.log(this.a), // there is no enclosing function, so this will point to global object
arrowNested:
function() {
return () => console.log(this.a) // will inherit the value of this from arrowNested() function, so it will point to `obj`
}
}
obj.arrow() // undefined
obj.arrowNested()() // 1
// value of `this` in arrow function is determined by where function being declared
```
In some cases, such a behavior of arrow functions might be handy, i.e. when used in event handlers.
### Event Handler
In the browser, there is a special `this` context for event handlers. In an event handler called by `addEventListener`, `this` will refer to the element, on which a listener is placed. In other words, `this` is pointing to `event.currentTarget`
```js
const button = document.createElement('button')
button.textContent = 'Click me'
document.body.append(button)
button.addEventListener('click', function(event) {
console.log(this) // <button>Click me</button>
})
```
Sometimes it is not convenient and _arrow functions_ being used to ‘preserve’ `this` value, no matter what ‘caller’ is:
```js
const person = {
name: "Beatrix",
sayHello: function() {
document.getElementById("myButton").addEventListener("click", () => {
console.log("Hello, " + this.name); // `this` inherited from `sayHello` and always will point to `person`, no matter where it will be invoked (arrow function context)
});
}
};
person.sayHello(); // "Hello, Beatrix"
```
### Class
When `this` is used inside a class, its value depends on what type of methods and field initializer it’s being used in:
- In public and private methods and field initializers `this` behaves like in constructor functions: pointing to an instance
- Static methods cannot be accessed via instance’s `this`. It must be called on class itself
```js
class C {
instanceField = this;
static staticField = this;
}
const instance = new C();
console.log(instance.instanceField === instance); // true
console.log(instance.staticField); // undefined because static methods cannot be accessed via instance's `this`
console.log(C.staticField === C); // true
```
## Explicit Context of this
The value of `this` can be set manually by using special function methods. Note, that _Arrow functions_ do not have their own `this`, so these methods can’t be used with them.
`.call()` and `.apply()` are used to call the function with a specified value of `this`:
```js
const obj1 = {
a: 1,
log() {console.log(this.a)}
};
const obj2 = {
a: 2,
};
obj1.log.apply(obj2); // 2, because `this` explicitely set to `obj2`
obj1.log() // 1
```
`.bind()` is used to create a constant binding of `this` to a specified object:
```js
const obj1 = {
a: 1,
log() {console.log(this.a)}
};
const obj2 = {
a: 2,
};
const getObj2Var = obj1.log.bind(obj2);
getObj2Var() // 2, because getObj2Var `this` binded to obj2
```
## Self-check
```js
const obj = {
a: 1,
b: function() {
console.log(this.a)
},
c: () => {
console.log(this.a)
},
d: function() {
return () => {
console.log(this.a);
}
}
}
// what the output will be?
console.log(obj.a)
obj.b()
const b = obj.b
b()
obj.b.apply({a: 2})
obj.c()
obj.c.apply({a:2})
obj.d()()
obj.d.call({a:2})()
obj.d().call({a:2})
```
### Answer
```js
console.log(obj.a) // 1
obj.b() // 1 // method context
const b = obj.b
b() // undefined // This is globally invoked function, not a method, so `this` is pointing to global object
obj.b.apply({a: 2}) // 2
obj.c() // undefined // Arrow function do not have outer function, so `this` reference global object
obj.c.apply({a:2}) // undefined // Arrow functions can't use .call() .apply() or .bind()
obj.d()() // 1 // first obj.d() being executed (method context)
// and returned arrow function. Then arrow function being executed in global context,
// but `this` in arrow function always points to the `this` of the encapsulating function.
// In this case `this` of `d()` pointing to `obj`, so `this` in arrow function
// will always reference `obj`, no matter where it called
obj.d.call({a:2})() // 2 // same as above, but here `this` of `d()` was explicitely set
obj.d().call({a:2}) // 1 // `call()` method was applied to arrow function, which is not making any sense.
```
### References
1. [this — JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
2. [Object methods, this](https://javascript.info/object-methods)
Happy coding! Feedback is appreciated. | skorphil |
1,884,802 | Docker for Beginners (Windows) | What is Docker Docker is a platform that allows us to package and run applications inside... | 0 | 2024-06-25T17:59:03 | https://dev.to/rifat87/docker-for-beginners-windows-434i | docker, container, aws, devops | ##What is Docker
Docker is a platform that allows us to package and run applications inside lightweight, isolated environments called containers. These containers include all the necessary dependencies and code needed to run our app consistently across different machines. Unlike traditional virtual machines, Docker containers share the same host operating system, making them efficient and portable. Docker simplifies version control, dependency management, and ensures consistent environments for development and production. It’s a powerful tool for streamlining software deployment and scaling. 🚀
---
###Before

###After
1. Own isolated environment and own operating system which is linux based.
2. Packed with all configuration
3. One command to install the app

###Application deployment
1. So before docker , the configuration of the server needed
2. There might dependencies conflict
3. Misunderstandings
4. Text doc for deployment
so after the containers,
1. No environmental configuration on the server - except docker runtime
2. Developers and Operations works together to the package the application in a container
##What is a container
- The container is a layer of images.
- Mostly linux base image, because small in size[ alpine: 3.10]
- And the application image is on top.
##Lets install Postgres:9.6
1. 1st go to [DockerHub](https://hub.docker.com/search?q=postgres)
2. Search postgres

3 . Choose your desired version, i choose 9.6

4 . For windows, open wsl and run `docker run postgres:9.6`

##Difference between Image and Container
1. Image is an actual package or software that we want to run. It can be moved around
2. Actually when we start the application is called container. And when we run the image, then it first bring to a container and then we run it and called container
##Difference between Docker and Virtual machine
1. Docker image is much smaller like couple of megabytes and vm might be couple of gigabytes
2. Docker container start and runs faster but the vm is much slower
3. If we want to run some linux based application on windows then it will not run, because the the OS kernel is not same. Thats why we need to use the Docker tool box
##Basic Docker commands
1. docker pull
2. docker run
3. docker start
4. docker stop
5. docker ps
6. dokcer exec-it
7. docker logs
#### Installing redis image
1. Just go to docker hub
2. Search redis

3 . open wsl , run command `docker pull redis`

4 . Now we have to put the redis image to a container to run it. For that just give the command, `docker run redis`
5. To check the running images, open a new terminal and give, `docker ps`
6. To stop the running image give `ctrl + c`
7. `docker run`, command runs new container when we use it.
8. Here are some key differences between the two commands:
**Attached vs Detached Mode:** The main difference is that docker run attaches to the container, while docker run -d runs the container in detached mode.
**Output:** With docker run, you will see the output of the container in your terminal. With docker run -d, you will not see the output.
Container Management: With docker run, you can manage the container directly from your terminal. With docker run -d, you will need to use other commands like docker ps and docker stop to manage the container.
In summary, docker run is used to start a container and attach to it, while docker run -d is used to start a container in detached mode, allowing it to run in the background.
**Attached mode**

Here the container is attached with the terminal
**Detached mode**

9 . Now in detached mode, to stop the container for some reason we can use, `docker stop <id>`

10 . To start again use , `docker start <id>`

11 . Suppose we stops the container for today and came back tomorrow and want to start from where left, to do that we can use, `docker ps -a` which will show all the running and not running container logs
12 . Now if want to run 2 redis of different versions, we have to use `docker run redis:version` , here the version is- which version image we want to run in our container. `docker run` pulls image and runs the container.
So the docker run does two command in one, one is **docker pull** and the other one is **docker run**


Here we can see, both redis versions are running on port: 6379/tcp, which is also the container port number.
But the problem is in tcp we can not use single port for multiple application in our localhost . To solve this issue we have to bind port.
13 . To bind the port at first we have to stop all the running redis images.

Then run,
`docker run -p6000:6379 -d redis` for 1st one,

for the second one we will run it on port 6001 same way but remember 6379 is the container port.

We can see 2 different redis application runnig on 6001, 6000.
##docker log & docker exec -it
To check why one container is not working properly , using the docker log
1. `docker logs <id>`
2. or `docker logs <name>`

but it is difficult to remember the container name. To solve this problem we can name the container as we like.
3 . So we have two container currently running,

- at first we have to stop one using, `docker stop <id>`
- Now give the command , `docker run -d -p6001:6379 --name redis-older redis:7.0`

- then we can use docker logs by the given name
`docker logs redis-older`
##Docker exec -it
1. We can easily open the terminal of the current container using, `docker exec -it`
2. We have container named redis-old
3. now give, `docker exec -it redis-old /bin/bash`
note: we can use the container id also instead of name(redis-old)
4. Then we went to home directory and run env command
5. To exit we simply give `exit`

##Developing with containers
1. Install express, mongo-express by,
- `docker pull mongo`
- `docker pull mong-express`
###We are going to create a new network
1. To create a new network, give: `docker network create mongo-network`
2. to check the network list: `docker network ls`

### Run mongo containers
1. The default container port for mongo is 27017
2.
`docker run -d -p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
--name mongodb \
--net mongo-network \
mongo
`
id: 74bd46402e9cebdf13c2265a01b072807dd7d97bb83ae569193e35c191f67f60

3 . Same way run the mongo-express,
1. `docker run -d -p 8081:8081 \
-e ME_CONFIG_MONGODB_ADMINUSERNAME=admin \
-e ME_CONFIG_MONGODB_ADMINPASSWORD=password \
-e ME_CONFIG_MONGODB_SERVER=mongodb \
--net mongo-network \
--name mongo-express \
mongo-express
`
id: 6847ec9032c3673c6c61fc0f89e1b2baa5cbb44bea27eeedf0d67a1e384ec109

4 . Now we can easily check , if mongo-express is connected or not by, `docker logs <id>`

5 . Now go to browser and search, `localhost:8081`
and give username: admin,
password: pass

And you will see the home page,

---
##Docker Compose
Previously we use run commands to start our containers and created a network to communicate between them. But what if we need to run 10 containers at a time and create a network to communicate them, it will be very difficult to run 10 commands for each containers. To solve this issue we can use **Docker Compose File** , which will contain all the commands in a structured way.

1 . Version: 3 // version of docker compose
2 . Services: // here all the container names goes
3 . mongodb: // container name
4 . image: mongo // which image we are using here mongo
5 . port:
-27017:27017 // this is the tcp port number host:container
6 . environment:
-MONGO_INITDB_ROOT_USERNAME=admin MONGO_INITDB_ROOT_PASSWORD=password // environment variables
7 . mongo-express: // new container name
8 . image: mongo-express // image
9 . ports: -8081:8081 // port number
10. environment: .... // environment variables
But there is one thing is missing that is **Docker Network**, Actually in docker compose file we don't need that, docker compose itself takes care of creating a common network.
##Let's create a docker compose file
In docker compose file(yaml file) the indentation is important. We have a demo project where we have the docker compose file,

```
version: '3'
services:
mongodb:
image: mongo
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=password
mongo-express:
image: mongo-express
ports:
- 8081:8081
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
- ME_CONFIG_MONGODB_ADMINPASSWORD=password
- ME_CONFIG_MONGODB_SERVER=mongodb
```
save it as, mongo.yaml
- Now the question is how to run the compose file !!.
- At first we go to the location where we save the compose file using the terminal.

- The docker compose is also installed with docker is installed. Its a package
-

now give, `docker-compose -f mongo.yaml up`
Here, the command **`-f`** means the mode of the document is **file**
-

Here we can see new network has been created and two new containers also.

- Previously to stop the containers we have to use docker stop, but in docker compose we can use
`docker-compose -f mongo.yaml down`
And it will shutdown all the container in the compose file, and also the network that had been created by docker compose.

after shutdown,


**NOTE**: The command is used for downing the compose file is actually a container restart and we will lost every data that we worked in previous container.
---
## Dockerfile - Building our own Docker Image

1 . FROM: node // which gives us the installed node
2 . ENV: // which are the environment variable
3 . RUN : // executes any linux commands , here the directory will be created using mkdir
4 . COPY: // It executes on the HOST machines
5 . CMD: // entry point command
- To create our own image we need two thigs, 1. name, 2. Tag
- At first go to the folder that contains Dockerfile, run the command-> docker build -t my-app:1.0 .

**Dockerfile:**
```
FROM node:22.3-alpine3.19
ENV MONGO_DB_USERNAME=admin \
MONGO_DB_PWD=password
RUN mkdir -p /home/app
COPY ./app /home/app
# set default dir so that next commands executes in /home/app dir
WORKDIR /home/app
# will execute npm install in /home/app because of WORKDIR
RUN npm install
# no need for /home/app/server.js because of WORKDIR
CMD ["node", "server.js"]
```
To check, give docker images,

- We can run the image using, `docker run my-app:1.0` and see the logs, `docker logs <id>`
- to open it exec mode,

##Privet Docker Registry
1. Create and account on aws.amazon.com
2. Serach ECR service
3. Create a repository
4. Named the repo my-app

5 . Now we are going to push the docker image that we created.

6 . At first we need to create an account on aws.amazon.com.
7 . Install AWS CLI, [CLI installer](https://aws.amazon.com/cli/) .

verify installation using, `aws --version`
8 . Now we need to do aws configure, before that we need to create a IAM account.

From the user we have to create a user and click on the user and create an access key,


Now we can configure the aws cli using , `aws configure` and put the access key id there.
9. Now we are going to create an ECR repository which is a private registry,
- In services search ECR and go to private portion and click on **create repository**

Now , give name to your repo, i gave my-app and keep the other things as it is,

10 . Now Click on the created repo , my-app,

Then view push command,


11. Copy The first command and paste it to powershell,
if you get this error,

then, go to IAM user,

- Them Add permission

Create Inline policy

- Select JSON,

- And remove all code and add this,
```
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ECRLogin",
"Effect": "Allow",
"Action": "ecr:GetAuthorizationToken",
"Resource": "*"
}
]
}
```
Now the error must be solved. And give this command,,

it will show you,

LOGIN Successful
Now we will come back later and we see the
---
##Image Naming in Docker Registry

Normally in docker hub, we have the short name of the docker image but in aws ECR we have write the full mode.
- So we are going to use this, `docker tag my-app:1.0 339712908553.dkr.ecr.eu-north-1.amazonaws.com/my-app:1.0`
- By giving this we create a duplicate image with different name because of the tag,

-

Now we are going to use the 4th command but we will the latest with 1.0.
[Some images are taken from Tech with nanas YT channel]
| rifat87 |
1,900,433 | Setting Up Local Kubernetes Cluster with Kind | Hello everyone! Welcome back to the blog series on Mastering Kubernetes in this post, I’ll guide you... | 0 | 2024-06-25T17:54:15 | https://dev.to/jensen1806/setting-up-local-kubernetes-cluster-with-kind-19m4 | kind, kubernets, containers | Hello everyone! Welcome back to the blog series on Mastering Kubernetes in this post, I’ll guide you through setting up Kubernetes on your local system using Kind.
### Why Local Kubernetes Installation?
Before diving into managed Kubernetes services like EKS, AKS, or GKE, installing Kubernetes locally allows you to gain a deep understanding of its components and how they interact. Managed services abstract away many details, which limits your learning and troubleshooting capabilities.
### Tools for Local Kubernetes Installation
There are several tools available for installing Kubernetes locally:
- Minikube
- K3s
- K3d
- Kind
In this guide, we’ll use Kind (Kubernetes IN Docker), one of the most popular tools for local Kubernetes installations.

### Prerequisites
Ensure you have the following installed on your system:
- Go (1.17.5 or later)
- Docker
If you followed my previous posts, you should already have Docker installed. If not, please refer to those posts for installation instructions.
## Installing Kind
Let’s start by installing Kind. Depending on your operating system, you can use a package manager:
#### For MacOS:
```
brew install kind
```
#### For Windows:
```
choco install kind
```
To create a Kubernetes cluster with Kind, use the following command:
```
kind create cluster --image <image-name> --name <cluster-name>
```
For this tutorial, we'll use Kubernetes version 1.30:
```
kind create cluster --image kindest/node:v1.30.2 --name cka-cluster-one
```
This command will pull the specified node image and create a cluster named cka-cluster-one.
### Verifying the Cluster
To ensure your cluster is up and running, use the kubectl command-line tool. If you don't have kubectl installed, follow these steps:
```
// For MacOS
brew install kubectl
// For windows
choco install kubernetes-cli
```

## Creating a Multi-Node Cluster
For more advanced setups, you might want to create a cluster with multiple nodes. Here's how you can do it:
1. Create a configuration file config.yaml with the following content:
```
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker
```
2. Apply this configuration to create the cluster:
```
kind create cluster --config config.yaml --image kindest/node:v1.30.2 --name cka-cluster-two
```
3. Verify the nodes:
```
kubectl get nodes
```
You should see three nodes: one control-plane and two worker nodes.
## Switching Contexts Between Clusters
When you have multiple clusters, you need to switch contexts to interact with the correct one. Use the following commands:
List all contexts:
```
kubectl config get-contexts
```
Switch context:
```
kubectl config use-context kind-cka-cluster-one
```
### Conclusion
Setting up Kubernetes locally using Kind is a crucial step in understanding the core components and operations of Kubernetes. In the next post, we’ll dive into creating simple pods, understanding the difference between imperative and declarative commands, and learning the basics of YAML.
Happy learning!
For further reference, check out the detailed YouTube video here:
{% embed https://www.youtube.com/watch?v=RORhczcOrWs&list=WL&index=14 %}
### References:
1. Kind Documentation - https://kind.sigs.k8s.io/
2. Install Kubectl - https://kubernetes.io/docs/tasks/tools/
3. Kubernetes Documentation - https://kubernetes.io/docs/home/ | jensen1806 |
1,900,431 | Optimizing Inventory with AI: Say Goodbye to Overstocking and Stockouts! | In the fast-paced world of retail, efficient inventory management is crucial for maintaining... | 0 | 2024-06-25T17:51:23 | https://dev.to/seoqcstechs_a09da5d24db26/optimizing-inventory-with-ai-say-goodbye-to-overstocking-and-stockouts-7m5 | inventory, ai, tutorial | In the fast-paced world of retail, efficient inventory management is crucial for maintaining operational efficiency, reducing costs, and enhancing customer satisfaction. Leveraging artificial intelligence (AI) for inventory optimization is transforming how retailers predict demand and manage stock levels. Let’s dive into this innovative AI use case and explore how it can revolutionize your retail business.
ACCURATE DEMAND FORECASTING
Accurate demand forecasting is the cornerstone of effective inventory management. AI algorithms analyze historical sales data, market trends, and external factors such as seasonal fluctuations and economic conditions to predict future demand with high accuracy.
For example, a clothing retailer can use AI to forecast increased demand for winter coats during colder months. By anticipating this surge, the retailer can ensure adequate stock levels, preventing stockouts and lost sales. This precise forecasting not only enhances inventory management but also boosts customer satisfaction by ensuring the right products are available when needed.
DYNAMIC STOCK REPLENISHMENT
AI-powered systems enable dynamic stock replenishment by continuously monitoring inventory levels and sales patterns. This real-time monitoring allows retailers to adjust stock levels promptly and efficiently.
Consider a grocery store that uses AI to automatically reorder perishable items based on real-time sales data and shelf life. This ensures fresh products are always available without the risk of overstocking. The dynamic nature of this system helps maintain optimal inventory levels, reducing waste and improving overall store efficiency.
REDUCING HOLDING COSTS
Holding costs associated with excess stock can be a significant financial burden for retailers. AI helps minimize these costs by optimizing inventory levels based on accurate demand predictions.
For instance, an electronics retailer can use AI to predict the optimal stock level for fast-moving gadgets. By maintaining just the right amount of inventory, the retailer can reduce the need for large storage spaces and lower associated costs. This efficiency translates into direct cost savings and better financial management.
ENHANCING SUPPLIER COLLABORATION
AI provides valuable insights into supplier performance, delivery times, and reliability, enabling retailers to collaborate more effectively with their suppliers.
A furniture retailer, for example, can use AI to identify the best suppliers based on their delivery efficiency and product quality. This information allows the retailer to ensure timely restocking of popular items, improving product availability and customer satisfaction. Enhanced supplier collaboration also fosters better business relationships and streamlined supply chain operations.
MITIGATING THE RISK OF STOCKOUTS
Stockouts can severely impact customer satisfaction and loyalty. AI-driven inventory optimization reduces the risk of stockouts by maintaining optimal stock levels based on accurate demand predictions.
Imagine a pharmacy using AI to ensure essential medicines are always in stock. By predicting demand accurately, the pharmacy can provide reliable service to its customers, enhancing their shopping experience and boosting brand loyalty. This proactive approach to inventory management ensures that customers always find what they need, when they need it.
REAL-WORLD EXAMPLE
A large retail chain implemented AI-powered inventory optimization across its stores, leading to a 15% reduction in stock holding costs and a 10% increase in sales due to better product availability. By predicting demand more accurately and optimizing stock levels, the chain improved its overall efficiency and customer satisfaction. This real-world example illustrates the tangible benefits of AI-driven inventory management.
CONCLUSION
AI is revolutionizing inventory management in retail by providing accurate demand forecasts and optimizing stock levels. This technology helps retailers avoid the pitfalls of overstocking and stockouts, leading to cost savings, improved efficiency, and enhanced customer experiences.
Are you ready to explore how AI can optimize your inventory management? Visit our website at [QCS Techs](https://qcstechs.com) or contact us at marketing@qcstechs.com to learn more.
Additional Resources:
[Vision Pro: The Future of Retail](https://qcstechs.com/vision-pro-future-of-retail.html)
[Leveraging AI for Retail](https://qcstechs.com/leveraging-AI-for-retail.html)
 | seoqcstechs_a09da5d24db26 |
1,900,430 | 🌟 Exciting Machine Learning Journey Ahead! 📊 | Hey Dev.to community! 👋 I'm starting a 10-day journey to delve into project focused on Customer... | 0 | 2024-06-25T17:50:22 | https://dev.to/divyansh_gawri/exciting-machine-learning-journey-ahead-3h8n | machinelearning, programming, python, ai |
Hey Dev.to community! 👋 I'm starting a 10-day journey to delve into project focused on Customer Segmentation using ML techniques and to understand consumer behavior better.
📅 Follow my progress every 2 days as I explore data insights and prediction of spending behaviors. 🧠
🤝 Are you passionate about diving deep into data and want to collaborate on this project?
Let's work together to uncover valuable insights!
Drop me a message here or via email at dishugawri@gmail.com . | divyansh_gawri |
1,900,429 | Intern level: Introduction to React | Overview of React What is React? React is a JavaScript library for building... | 0 | 2024-06-25T17:49:42 | https://dev.to/david_zamoraballesteros_/intern-level-what-is-react-a-beginners-guide-16mc | react, javascript, webdev, programming | ## Overview of React
### What is React?
React is a JavaScript library for building user interfaces, particularly for single-page applications where you need a fast, interactive user experience. Think of React as the LEGO blocks of web development: you build small, reusable pieces (components) and put them together to create a complex interface.
### History and Evolution of React
React was developed by Facebook and first released in 2013. It was created to address challenges in building complex user interfaces with high performance. Over the years, React has evolved significantly, introducing powerful features like Hooks and Concurrent Mode, which make it easier to manage state and improve app performance.
### Comparison with Other Frameworks/Libraries
**Angular:** Developed by Google, Angular is a full-fledged framework, offering a complete solution for building web applications. It's more opinionated and comes with a lot of built-in features.
**Vue:** Vue is a progressive JavaScript framework. It's known for being easy to integrate into projects and offers a blend of features from both Angular and React, with a gentle learning curve.
## Why Choose React?
### Benefits of Using React
1. **Component-Based Architecture:** React allows you to build encapsulated components that manage their own state, then compose them to make complex UIs. This makes the code more maintainable and reusable.
2. **Virtual DOM:** React uses a virtual DOM to optimize updates. Instead of directly manipulating the browser's DOM, React updates a virtual representation, making the updates faster and more efficient.
3. **Declarative UI:** React allows you to describe how your UI should look based on the application's state. When the state changes, React efficiently updates the UI to match.
4. **Strong Community and Ecosystem:** With a large community and extensive ecosystem, finding solutions, tools, and libraries for React is easier.
### Case Studies of Successful React Applications
1. **Facebook:** React was initially developed for Facebook's News Feed. It now powers the entire Facebook web application, providing a fast and responsive user experience.
2. **Instagram:** Another application built with React is Instagram, which benefits from the performance and maintainability advantages of React's component-based architecture.
3. **Airbnb:** Airbnb uses React to build dynamic, responsive user interfaces, ensuring a seamless experience for users browsing listings and making bookings.
## Conclusion
React is a powerful and flexible JavaScript library for building user interfaces, favored for its performance, maintainability, and strong community support. Whether you're building a small widget or a complex web application, React provides the tools and structures to help you create efficient and interactive UIs. As an intern, understanding React's basics will set a strong foundation for your web development journey. | david_zamoraballesteros_ |
1,900,421 | Initialize a Go project with “go-blueprint” | Step-by-step guide to initiating a Go project. Make sure you have Go installed on your machine. You... | 0 | 2024-06-25T17:47:18 | https://dev.to/hieunguyendev/initialize-a-go-project-with-go-blueprint-2bd1 | go, beginners, initgo, goblueprint |

Step-by-step guide to initiating a Go project. Make sure you have Go installed on your machine. You can download it from the official Go website 👉 [https://golang.org/dl/](https://golang.org/dl/)
**Step 1: Open terminal:**

**Step 2: Install go-blueprint with the following command:**
```
go install github.com/melkeydev/go-blueprint@latest
```

**Step 3: Open the "go-blueprint" tool on the browser with the following link:**
```
https://go-blueprint.dev/
```
**Step 4: Fill in the necessary information of the project into the form such as projectName, database, framework, and some advanced options if used:**

- From the information we filled in the form, we will receive an order as shown in the picture.

**Step 5: Copy the command, paste it into the terminal and press enter:**
```
go-blueprint create --name my_project --framework gin --driver mongo
```

- If you encounter the "command not found" error as below, follow the next steps in step 5. Otherwise, you can proceed to step 6

**Step 5.1: Run command:**
```
GOPATH=$HOME/go
```
**Step 5.2: Run command:**
```
PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
```

So it's already fixed. You can refer to the error at the link: [here](https://github.com/Melkeydev/go-blueprint/issues/166)
**Step 5.3: Then run the command:**
```
go-blueprint create --name my_project --framework gin --driver mongo
```
**Step 6: When run successfully, we will get results as shown:**

**Step 7: Open the project with Visual Studio Code**
- Enter the "my_project" directory using the command
```
cd my_project
```
- Open the project quickly with Visual Studio Code using command
```
code .
```

- This is the result received

- That's a great tool. So we have successfully initiated a Go project with "go-blueprint". To continue running the project we just initiated, we perform the following steps
**Step 8: Open the main.go file in the cmd/api folder and add the following line:**
```
fmt.Println("Hello, World!")
```

**Step 9: Open terminal and run command:**
```
make run
```

We have finally completed the initialization of the Go project and successfully ran the project.
You can refer to "Go-blueprint" here 👉 [Go-blueprint](https://github.com/Melkeydev/go-blueprint)
**If you found this article useful and interesting, please share it with your friends and family. I hope you found it helpful. Thanks for reading** 🙏
Let's get connected! You can find me on:
- Medium: [Quang Hieu (Bee) -- Medium](https://quanghieudev.medium.com/)
- Dev: [Quang Hieu (Bee) -- Dev](https://dev.to/hieunguyendev)
- Linkedin: [Quang Hieu (Bee) -- Linkedin](https://www.linkedin.com/in/hiếu-nguyễn-1a38132bb/)
- Buy Me a Coffee: [Quang Hieu (Bee) -- buymeacoffee](https://buymeacoffee.com/quanghieudev)
| hieunguyendev |
1,900,427 | What Googlers can teach you about Security part 2 | [TL;DR, I'm a Web Dev and I don't care about Cybersec] - go and read Open Worldwide Application... | 0 | 2024-06-25T17:40:10 | https://dev.to/cyber_zeal/what-googlers-can-teach-you-about-security-part-2-1ko1 | cybersecurity, certification, google | [TL;DR, I'm a Web Dev and I don't care about Cybersec] - go and read Open Worldwide Application Security Project (OWASP) [Top 10 Web Application Security Risks](https://owasp.org/www-project-top-ten/) you **must** know this stuff, if your web app runs on anything else than http://127.0.0.1
Previously I wrote about Google's Cybersecurity Professional program and why I enrolled into it. If you haven't already, go and read it [here](https://dev.to/cyber_zeal/what-googlers-can-teach-you-about-security-515m).
If you've already read it - we continue with the second course in the series - "Play It Safe: Manage Security Risks"
Again, I only focus on some of the key points, course has a lots of content and hands on exercises - if you are interested how Cybersecurity industry works, explained through real life examples from Google, you should definitely take the course.
Even if you are developer and have no interest in working in Cybersec, this will give you a better picture of how your organization operates.
And who knows, maybe along the way you fall in love with Cyber. :heart:
## Module 1
First module goes in depth with CISSP’s eight security domains that were mentioned in the previous course/post. I will list them again because they show how vast is the Security industry. Also, you can see the Roles and some of the responsibilities associated with them.
1. **Security and Risk Management**:
- Roles: Chief Information Security Officer (CISO), Risk Manager, Compliance Officer.
- Responsibilities:
- Develop security policies and procedures.
- Assess and manage risks.
- Ensure compliance with regulations and standards.
- Align security practices with organizational goals.
2. **Asset Security**:
- Roles: Data Owners, System Administrators, Privacy Officers.
- Responsibilities:
- Manage information assets (data, hardware, software).
- Define access controls and ownership.
- Protect sensitive data and enforce privacy rules.
3. **Security architecture and engineering**
- Roles: Security Architects, Systems Engineers.
- Responsibilities:
- Design secure systems and networks.
- Implement encryption, firewalls, and access controls.
- Evaluate security technologies.
4. **Communication and Network Security**:
- Roles: Network Administrators, Security Analysts.
- Responsibilities:
- Secure network infrastructure (routers, switches).
- Implement VPNs, firewalls, and intrusion detection systems.
- Ensure secure data transmission.
5. **Identity and Access Management (IAM)**:
- Roles: IAM Managers, Access Control Administrators, System Administrators.
- Responsibilities:
- Manage user identities and access rights.
- Implement authentication and authorization mechanisms.
- Monitor user activity.
6. **Security Assessment and Testing**:
- Roles: Penetration Testers, Vulnerability Assessors.
- Responsibilities:
- Conduct security assessments (penetration testing, vulnerability scanning).
- Identify weaknesses and recommend improvements.
- Validate security controls.
7. **Security Operations**:
- Roles: Security Analysts, Incident Responders.
- Responsibilities:
- Monitor security events and incidents.
- Investigate breaches and coordinate responses.
- Manage security incidents and recovery.
8. **Software Development Security**:
- Roles: Software Developers, Security Champions.
- Responsibilities:
- Write secure code.
- Perform code reviews for vulnerabilities.
- Ensure software remains free of flaws.
### Risk management
You must keep your assets secure! Assets can be digital or physical - personal information of customers, trade secrets, servers, confidential documents…
The [**NIST Risk Management Framework (RMF)**](https://csrc.nist.gov/projects/risk-management/about-rmf) is a comprehensive, flexible, and repeatable 7-step process that organizations can use to manage information security and privacy risk.
The 7 steps are:
1. **Prepare**: Talk to key stakeholders, prepare a broad risk management strategy
2. **Categorize**: Analyze the system, categorize the data, and do an impact analysis.
3. **Select**: Choose NIST SP 800-53 controls based on risk assessment.
4. **Implement**: Deploy controls and document their deployment.
5. **Assess**: Verify control effectiveness.
6. **Authorize**: Senior management authorizes the whole thing.
7. **Monitor**: Continuously monitor control implementation and risks.
You can see list of cybersecurity risks [here](https://www.nist.gov/itl/smallbusinesscyber/cybersecurity-basics/cybersecurity-risks).
Also there is a famous [OWASP top 10 security risks](https://owasp.org/www-project-top-ten/) for web applications. **<u>If you are a web dev you should really really get acquainted with this list.</u>**
You can see how the top list changes through time.

_Image credit Google Cybersecurity Professional Program_
## Module 2
We already mentioned CIA in previous post, but it’s so crucial that we will expand a bit here. The way I see it is whatever assessment you do in security, be it Application Threat Modeling or Infrastructure Security Review or Risk Assessment you are thinking about these three things:
**Confidentiality** - Who can access what? We need to ensure only authorized users can access specific parts of the system.
**Integrity** - No one should tamper with your system. And if someone does you should know about it.
**Availability** - Systems should be available to the authorized users.
Rest of the module goes in depth with OWASP and NIST CyberSecurity Framework. Also first hand on exercise is here - you conduct a security audit of a fictional small company that had a recent increase in business. It really well made and you see how everything you learned so far is applied in the real world.
## Module 3
This module goes in depth on Security Information and Event Management (SIEM) tools. SIEM tools aggregate all event streams in the organization, like network logs, app logs and so on. And if something weird starts happening they sound the alert.
A picture is worth a thousand words, and video is.. thousand words per frame, I guess... So you can go and check IBM’s 4min [video](https://www.youtube.com/watch?v=9RfsRn7m7OE) about this, if you are interested. Or do a web search on Splunk to see how the most popular SIEM solution looks like.
There is also a thing called **Security orchestration, automation, and response (SOAR)** which is considered to be a future of SIEM - or at least it can be used to automate some repetitive tasks generated by SIEMs. More about it [here](https://www.youtube.com/watch?v=k7ju95jDxFA).
## Module 4
So, your SIEM detected an intrusion, what do you do? Don’t panic, if you work in serious organization you have a Playbook. If you don’t have a Playbook? Well, than you can panic. :sweat_smile:
Last module is about Playbooks. But what is a Playbook you ask?
A Playbook is a manual which tells you what exactly you need to do and with what tools in response to a security incident.
Playbooks ensure a consistent list of actions is followed, regardless of who is handling the case.
Different types of playbooks exist, including those for incident response, security alerts, team-specific, and product-specific purposes.
Here, we'll focus on a commonly used cybersecurity playbook called an incident response playbook. Incident response involves quickly identifying an attack, containing damage, and correcting the effects of a breach. An incident response playbook includes six phases to help manage security incidents from start to finish. Now while I think theory has it’s place, these type of things are best explained using real world examples. Here is how each step would look like for some concrete scenario:
1. :memo: **Preparation**: An organization creates an incident response plan that outlines specific procedures for different types of incidents (e.g., data breaches, DDoS attacks, malware outbreaks). They identify key personnel responsible for incident response, establish communication channels, and conduct regular tabletop exercises to ensure everyone knows their roles.
2. :mag: **Detection and Analysis**: A security operations center (SOC) detects unusual network traffic patterns indicating a potential intrusion. Analysts investigate the incident, analyze logs, and use threat intelligence feeds to determine if the activity is malicious. They identify the affected systems and assess the impact.
3. :lock: **Containment**: Upon confirming a data breach, the incident response team isolates compromised servers from the network to prevent further spread. They disable compromised user accounts and block malicious IP addresses. The goal is to limit the attacker’s access and prevent additional damage.
4. :facepunch: **Eradication and Recovery**: After identifying a ransomware attack, the organization removes the malware from affected systems. They restore data from backups and patch vulnerabilities that allowed the initial infection. The recovery process involves verifying system integrity and ensuring all services are operational.
5. :coffee: **Post-Incident Activity**: The incident response team conducts a postmortem analysis of a successful phishing attack. They document the attack vector, identify gaps in security controls, and recommend improvements. Leadership reviews the findings, and the organization updates its security policies and provides additional user training.
6. :phone: **Coordination**: This involves reporting incidents and sharing information throughout the response process based on established standards. Coordination ensures compliance requirements are met and allows for a coordinated response and resolution.
Again, there were a lots of other things, but you can get the idea. Feel free to ping me in the comments.
Stay safe! | cyber_zeal |
1,900,426 | Mistakes we all make in FOSS | Hi Beautiful Dev community, I'm Antonio, CEO & Founder at Litlyx. Today i want to share with you... | 0 | 2024-06-25T17:38:30 | https://dev.to/litlyx/mistakes-we-all-make-in-foss-3f68 | discuss, opensource, beginners, webdev | Hi **Beautiful Dev community**, I'm Antonio, CEO & Founder at [Litlyx](https://litlyx.com).
Today i want to share with you my experience on Open-Source. In particularly on very common mistakes that can be avoided.
---
### Leave a **star** on our open-source [repo](https://github.com/Litlyx/litlyx) on git if you like it!
---
**Now let's dive in!!! **
---

## Common Mistakes in FOSS Development
In the development of Free and Open Source Software (FOSS), developers often encounter several common pitfalls. Understanding and avoiding these mistakes can lead to more successful and sustainable projects. Here are the five most common mistakes:
## 1. **Lack of Clear Documentation**
### Problem
Many FOSS projects suffer from poor or non-existent documentation, making it difficult for new contributors to get started and for users to understand how to use the software effectively.
### Solution
- **Write comprehensive documentation**: Include installation guides, usage instructions, and contribution guidelines.
- **Update regularly**: Ensure documentation is kept up-to-date with the latest changes in the project.
- **Encourage contributions**: Welcome improvements and additions to documentation from the community.
## 2. **Ignoring Community Feedback**
### Problem
Failing to listen to the community can lead to dissatisfaction and a decrease in contributions. Developers may become isolated from the needs and wants of their user base.
### Solution
- **Engage actively**: Regularly participate in forums, issue trackers, and other community channels.
- **Solicit feedback**: Encourage users to provide feedback and report issues.
- **Act on feedback**: Prioritize and address community feedback in a timely manner.
## 3. **Poor Project Management**
### Problem
Without proper project management, FOSS projects can become chaotic, with unclear goals, missed deadlines, and a lack of coordination among contributors.
### Solution
- **Set clear goals**: Define short-term and long-term objectives for the project.
- **Use tools**: Utilize project management tools like issue trackers, kanban boards, and milestone planners.
- **Regular updates**: Keep the community informed about project progress and upcoming releases.
## 4. **Neglecting Code Quality**
### Problem
In the rush to add features, developers might overlook code quality, leading to bugs, security vulnerabilities, and difficult-to-maintain codebases.
### Solution
- **Follow best practices**: Adhere to coding standards and guidelines.
- **Code reviews**: Implement a code review process to catch issues early.
- **Automated testing**: Use continuous integration and automated tests to ensure code quality.
## 5. **Inadequate License Understanding**
### Problem
Misunderstanding or misapplying open source licenses can lead to legal issues and restrictions on how the software can be used and distributed.
### Solution
- **Educate yourself**: Learn about different open source licenses and their implications.
- **Choose the right license**: Select a license that aligns with the goals of your project.
- **Comply with licenses**: Ensure your project complies with the terms of its chosen license and any third-party dependencies.
By being aware of these common mistakes and taking steps to address them, developers can create more robust, user-friendly, and successful FOSS projects.
---
### Leave a **star** on our open-source [repo](https://github.com/Litlyx/litlyx) on git if you like it!
---
*I hope you like it!!*
Share some love in the comments below.
Author: Antonio, CEO & Founder at [Litlyx.com](https://litlyx.com) | litlyx |
1,900,424 | How I Explored Recursion by Building a Simple Chatbot Using Python | This time, I decided to dive deeper into the concept of recursion by building a simple chatbot using... | 0 | 2024-06-25T17:35:34 | https://dev.to/codecounsel/how-i-explored-recursion-by-building-a-simple-chatbot-using-python-2mc4 | beginners | This time, I decided to dive deeper into the concept of recursion by building a simple chatbot using Python. This post details my journey in developing the chatbot and reflects on the learning opportunities it presented.
The "Simple Recursive Chatbot" interacts with users by asking questions and navigating through a decision tree based on their responses. This project was a great way to practice and understand recursion, a fundamental programming concept.
- What is Recursion?
Recursion occurs when a function calls itself to solve smaller instances of the same problem. It is a powerful tool in a programmer's arsenal, especially useful for tasks that can be broken down into repetitive sub-tasks.
- Building the Chatbot:
To create the chatbot, I used a decision tree, where each node represents a question or a final response. The chatbot navigates through this tree based on user input, using recursion to process each step. Here's a breakdown of the key steps:
Defining the Tree Structure:
I created a class DecisionNode to represent each node in the tree. Each node has a question and two possible branches (yes_branch and no_branch).
Constructing the Decision Tree:
I built the tree by linking nodes together, creating a path for the chatbot to follow based on user responses.
Implementing the Recursive Function:
The core of the chatbot is a recursive function that asks the current node's question and calls itself with the next node based on the user's response.
- Key Features
Recursive Decision Making: The chatbot navigates through a decision tree using a recursive function, making it an excellent example of practical recursion.
Expandable Design: The decision tree can be easily expanded by adding more nodes and branches, making it versatile for different applications.
- Challenges and Learnings
During the development of the chatbot, I encountered challenges in designing the decision tree and ensuring the recursive function handled user input correctly. One significant learning point was the importance of defining clear base cases in the recursive function to prevent infinite loops and stack overflow errors.
- Future Enhancements
The "Simple Recursive Chatbot" is a foundational project that can be expanded in various ways:
Increasing Complexity: Adding more levels and branches to the decision tree for more detailed interactions.
Enhanced NLP: Implementing natural language processing to handle a broader range of user inputs.
User Interface: Creating a graphical user interface to improve user experience.
I invite everyone to check out the code on my GitHub repository (https://github.com/codecounsel/recursivechatbot/tree/main) and contribute suggestions for improvements or new features. Your feedback is crucial for the evolution of this project!
Developing the "Simple Recursive Chatbot" was an enriching experience that deepened my understanding of recursion. I am eager to continue enhancing the chatbot, adding features, and improving its design. I look forward to any feedback that can help take this project to the next level! | codecounsel |
1,564,203 | A Developer's Guide to Using Custom Basemaps in Your Web Apps | Integrate your basemaps in Leaflet, MapLibre GL JS, ArcGIS JS maps, and More Over the past few... | 0 | 2024-06-25T17:35:13 | https://dev.to/c_yatteau/a-guide-to-using-custom-basemaps-in-your-web-apps-4aea | javascript, webdev, programming, tutorial | ***Integrate your basemaps in Leaflet, MapLibre GL JS, ArcGIS JS maps, and More***
Over the past few months, I’ve demonstrated how to create custom vector basemap styles with [quick edit options](https://dev.to/c_yatteau/map-styling-for-web-developers-quick-editing-2bbh) and [advanced techniques](https://dev.to/c_yatteau/creative-map-styling-techniques-for-web-developers-25lc). Now, let’s take those custom basemaps and integrate them into different web mapping applications, including Leaflet, MapLibre GL JS, ArcGIS Maps SDK for JavaScript, and a self-hosted JSON example.
## Table of Contents
· [Steps](#steps)
· [ID](#id)
· [Leaflet](#leaflet)
· [MapLibre](#maplibre)
· [ArcGIS](#arcgis)
· [Hosting](#hosting)
· [Conclusion](#conclusion)
## Steps
#### Common Integration Steps
Regardless of the library you choose, the fundamental steps for integrating vector basemaps are consistent. You will typically need to:
* Include the necessary library files (CSS and JavaScript) in your project.
* Initialize a map object and set its view to a specific location and zoom level.
* Add a vector tile layer to the map, specifying the item ID and/or URL to your vector tile source.
## ID
#### Getting the Item ID of your Basemap
Before integrating your custom vector basemap into different mapping applications, you need to obtain the item ID from the ArcGIS Vector Tile Style Editor (VTSE). This item ID uniquely identifies your custom basemap and allows you to reference it in your mapping applications.
### Steps to Get the Item ID
1. **Access the VTSE**: Go to the ArcGIS Vector Tile Style Editor and log in with your ArcGIS account.
2. **Open a Custom Style**: Open your existing style that you have previously customized (or create and save a new one).
3. **Save the Style**: If you created a new style or made any changes, be sure to save the style. After saving, a unique item ID is generated for your custom basemap.
4. **Locate the Item ID**: The item ID can be found in the URL of the VTSE page.
With the item ID in hand, you are now ready to integrate your custom basemap into various mapping applications.
## Leaflet
The lightweight, open-source Leaflet library is easy to use and supports a wide range of plugins for added functionality. Whether you need to add complex features like heatmaps, marker clustering, or geolocation, there’s likely a plugin available that fits your needs.
Let’s look at how to use your custom basemap built with the VTSE in a Leaflet application.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>
<script src="https://unpkg.com/esri-leaflet@3.0.12/dist/esri-leaflet.js"></script>
<script src="https://unpkg.com/esri-leaflet-vector@4.2.3/dist/esri-leaflet-vector.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
height: 100vh;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = L.map("map").setView([38.9, -78.9], 4);
L.esri.Vector.vectorBasemapLayer("YOUR_BASEMAP_ID", {
apiKey: "YOUR_API_KEY"
}).addTo(map);
</script>
</body>
</html>
In this example, include the Leaflet CSS and JS files along with the Esri Leaflet and Esri Leaflet Vector JS files in the head of the file. Set the CSS styling for the body to have no predetermined margins or padding, and ensure the map takes up the entire page (100% of the view height). Next, in the HTML body, create a div where the map will be placed and give it an id value that you’ll reference in the JS section.
In the JS section, initialize the map with the L.map function from Leaflet, referencing the id value you created in your HTML div. Set the view to the desired location (latitude, longitude), and a zoom level between 1 and 19 (0 is world view and ~18 is max zoom). Finally, use the vector basemap layer plugin from Esri Leaflet with the basemap ID or your custom basemap and an ArcGIS API Key, which you can get by signing up for free [here](https://developers.arcgis.com/sign-up).

## MapLibre
#### MapLibre GL JS
MapLibre GL JS is an open-source fork of Mapbox GL JS. It provides robust support for vector tiles and offers powerful capabilities for rendering interactive maps using WebGL. Additionally, it is particularly suited for applications requiring high performance and detailed, interactive maps.
Let’s look at how to use your custom basemap built with the VTSE in a MapLibre GL JS application.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<script src=https://unpkg.com/maplibre-gl@4.0.0/dist/maplibre-gl.js></script>
<link href=https://unpkg.com/maplibre-gl@4.0.0/dist/maplibre-gl.css rel="stylesheet" />
<style>
body {
margin: 0;
padding: 0;
}
#map {
height: 100vh;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new maplibregl.Map({
container: "map",
zoom: 4,
center: [-78.5, 38.9],
style: `https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles/items/YOUR_BASEMAP_ID?token=YOUR_API_KEY`
});
</script>
</body>
</html>
Just like in Leaflet, the first few steps are the same. The setup for MapLibre GL JS involves including the necessary CSS and JS files, setting the CSS for the body, and then creating a div with an id for the map.
In the JS section, initialize a MapLibre GL JS map using the maplibregl.Map instance. Set its container to the HTML id value, its zoom level to a value between 0 and 24, and its center to the longitude and latitude you wish to position the map over. Finally, set its style to a vector tile style URL with your custom basemap ID and your API key attached at the end.

## ArcGIS
#### ArcGIS Maps SDK for JavaScript
ArcGIS Maps SDK for JavaScript, formerly known as ArcGIS API for JavaScript, is a toolkit that lets you develop web applications with maps. It provides tools to create interactive 2D and 3D maps, conduct spatial analysis, and integrate with other ArcGIS services. You can use it to visualize your data and build informative mapping experiences.
Let’s look at how to use your custom basemap built with the VTSE in an ArcGIS Maps SDK for JS application.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://js.arcgis.com/4.29/esri/themes/light/main.css">
<script src="https://js.arcgis.com/4.29/"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
height: 100vh;
}
</style>
<body>
<div id="map"></div>
</body>
<script>
require([
"esri/Map",
"esri/views/MapView",
"esri/Basemap",
"esri/layers/VectorTileLayer",
], function (Map, MapView, Basemap, VectorTileLayer) {
const view = new MapView({
container: "map",
center: [-100, 40],
zoom: 3,
map: new Map({
basemap: new Basemap({
baseLayers: [
new VectorTileLayer({
portalItem: {
id: "YOUR_BASEMAP_ID"
}
})
]
}),
}),
});
});
</script>
</head>
</html>
Again like with Leaflet and MapLibre GL JS, the starting setup for this map is basically the same. First, we include the ArcGIS Maps SDK for JavaScript CSS and JS files. Then set the CSS styling for the body to have no predetermined margins or padding and have the map take up the entire page (100% of the view height). Next, in the HTML body, create a div for where the map will be placed. Give it an id value that you’ll reference in the JS section.
In the JS section, unlike the open-source libraries, the setup is just a bit more involved. You’ll first need to require the modules needed which include Map, MapView, Basemap, and VectorTileLayer. The Map is the placeholder for what the map will hold, and the MapView is the general holder for everything visual about the map. In the MapView, we set the container (the HTML id value), the center (to a longitude, latitude), and the zoom level to a value as low as 0 and as high as anything around 22/23 (depending on the basemap detail).
Now, within the MapView, you set the map value. This is set by using the Basemap and VectorTileLayer together. Within the VectorTileLayer is where you reference your custom basemap id.

## Hosting
#### Self-Hosting and Using JSON in Another Mapping App
Now, each of the previous examples has required an ArcGIS API key. However, when creating your custom basemap style in the VTSE, you can take the JSON file and use it for free. Thus, if you prefer to host your own vector tile style, you can! You can access the JSON within the VTSE left-side button labeled “Edit JSON”. Once you click the “Edit JSON” button on the left side in the VTSE, you will be able to view and edit the JSON code for your map style. You can modify this directly if further customizations are needed. After making your changes, remember to save your edits. After editing, you’ll need to download the JSON style file. To do this, manually copy the JSON code into a text editor and save it with a .json extension.
Before uploading to the web, you’ll need to add a few additional things to the JSON style file, per Mapbox style specification as the file only contains the layers styles. Label the style array “layers”, then above this include the following code below.
{
"version": 8,
"name": "Name your style",
"metadata": {},
"sources": {
"source name": {
"type": "vector",
"url": "https://example.com/data/v3.json"
}
},
"sprite": "https://example.com/sprites/sprite",
"glyphs": "https://example.com/fonts/{fontstack}/{range}.pbf",
"layers": [
...
]
}
Next, host the style file on a web server to make it accessible for your applications. You could use cloud services like AWS S3, Google Cloud Storage, or even GitHub Pages, depending on your preferences and requirements. This step is crucial as the location of your JSON file will need to be referenced in the applications that use the map style.
To integrate the custom style into your mapping application, use the URL where your style file is hosted. This is done by specifying the style URL when setting up the map in most mapping libraries such as Leaflet or Mapbox GL JS. For instance, in MapLibre GL JS, you would set the style by providing the URL to the style property during the map initialization, as shown in the example above.
## Conclusion
Integrating vector basemaps into your web applications is a powerful way to enhance their visual appeal and functionality. By leveraging libraries like Leaflet, MapLibre GL JS, and ArcGIS Maps SDK for JavaScript, you can create highly interactive and customized maps tailored to your specific needs.
---
*This article was written by Courtney Yatteau, a Developer Advocate at [Esri](https://www.esri.com/en-us/home). The opinions in this article are solely Courtney’s opinions and do not necessarily represent the postings, strategies, or opinions of her employer. If you have any feedback, please like and/or comment. Also, if you have any questions or comments that you’d prefer to send privately, you can contact Courtney through [LinkedIn](https://www.linkedin.com/in/courtneyyatteau/), [Twitter](https://twitter.com/c_yatteau)*, *or [email](mailto:DeveloperOutreach@esri.com). If you’re considering a career switch, looking to get into tech, or curious about what it’s like to work at Esri, then please stay tuned for my future posts! You can also check out [Esri’s careers page](https://www.esri.com/en-us/about/careers/job-search) or [this video](https://youtu.be/nV4Ec_Qe4AQ) for more information.* | c_yatteau |
1,900,423 | Buy a devin ai account or participate in one account | Hello everyone. First of all, excuse me if there are spelling errors. I tried to create an account on... | 0 | 2024-06-25T17:33:28 | https://dev.to/mohamed_aliyounes_a3f0db/buy-a-devin-ai-account-or-participate-in-one-account-16m4 | devin | Hello everyone. First of all, excuse me if there are spelling errors. I tried to create an account on devin ai, but the company is very late in responding. Therefore, if any of you have an account on devin ai, I want to buy it or be a partner in it. | mohamed_aliyounes_a3f0db |
1,889,058 | Molecules of business logic from tiny atoms | Some people asked me how to design their business logic after reading my article on keeping your... | 0 | 2024-06-25T17:32:07 | https://dev.to/seasonedcc/molecules-of-business-logic-from-tiny-atoms-36mh | architecture, typescript, productivity, cleancode | Some people asked me how to design their business logic after reading my article on [keeping your business code separate from the rest](https://dev.to/seasonedcc/keep-your-business-code-separate-from-the-rest-4ek2). Here's an example of how we do it.
Imagine we have an online shop with a page for our Magical T-Shirt. On that page, we want to show all the product variants (small, medium, large) plus product information, like name. Your customer has applied a coupon code to their cart, so we must also show the discounted price.
## Functions with a verb in their name
At [Seasoned](https://www.seasoned.cc/), we prefer functions with verbs in their name to classes and objects. So the first thing we'll do is create a function called `getProductPageData` that gathers all the information we need.
It will look completely different by the end of this article, but this is how it starts:
```ts
function getProductPageData(productId: string, couponCode: string) {
// This would come from your database
const product = { id: productId, name: 'Magical T-Shirt' }
// This would come from your database
const variants = [
{ productId, sku: 'small', name: 'Small', price: 8.99 },
{ productId, sku: 'medium', name: 'Medium', price: 10.99 },
{ productId, sku: 'large', name: 'Large', price: 12.99 },
]
// This would come from your database
const coupon = { code: couponCode, discount: 10 }
return {
product,
coupon,
variants: variants.map((variant) => ({
...variant,
priceWithDiscount: variant.price * (1 - coupon.discount / 100),
})),
}
}
```
## A folder dedicated to business logic
This code lives in a `business` folder and it should not have any knowledge about the framework you're using. Ideally, it should work as well for a mobile app as it does for a website. All the code dealing with platform-specific APIs or framework-specific implementation should live elsewhere.
## Dealing with errors
Our `getProductPageData` function could fail. For instance, every query we make to our database can throw an error. So far, our code does nothing to deal with that.
Instead of adding multiple `try/catch` statements, we'll establish a pattern to deal with exceptions. For that, let me introduce you to [Composable Functions](https://github.com/seasonedcc/composable-functions), a library we created to make function composition easy and safe.
Composable functions do much more, but they help us deal with errors by doing the `try/catch` for us and returning the result in a type-safe way. Imagine this silly function call:
```ts
const getLength = (text: any) => text.length
getLength(null)
// TypeError: Cannot read properties of null (reading 'length')
```
If you wrap it with `composable`, it will never throw an error. Instead, it will return the result with the exception, like:
```ts
const getLength = composable((text: any) => text.length)
const result = await getLength(null)
// result equals
// {
// success: false,
// errors: [<Error object>]
// }
```
If it succeeds, it will return the result of the function inside `data`:
```ts
const getLength = composable((text: any) => text.length)
const result = await getLength('abc')
// result equals
// {
// success: true,
// data: 3,
// errors: []
// }
```
This pattern forces us to remember to deal with errors. To access `result.data`, we must first check if `result.success` is true. Otherwise, TypeScript will give us an error.
This is how our `getProductPageData` function looks like when wrapped with `composable`:
```ts
const getProductPageData = composable(
(productId: string, couponCode: string) => {
// This would come from your database
const product = { id: productId, name: 'Magical T-Shirt' }
// This would come from your database
const variants = [
{ productId, sku: 'small', name: 'Small', price: 8.99 },
{ productId, sku: 'medium', name: 'Medium', price: 10.99 },
{ productId, sku: 'large', name: 'Large', price: 12.99 },
]
// This would come from your database
const coupon = { code: couponCode, discount: 10 }
return {
product,
coupon,
variants: variants.map((variant) => ({
...variant,
priceWithDiscount: variant.price * (1 - coupon.discount / 100),
})),
}
},
)
```
## Extracting smaller functions
Over time, as we get to know our needs for reusing specific parts of code, we start to extract smaller functions. However, be careful not to extract them too early, as [the wrong abstraction is worse than code duplication](https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction). In other words, [avoid hasty abstractions](https://kentcdodds.com/blog/aha-programming) and only extract smaller functions when the right abstraction emerges.
In our example, let's imagine we have to get product info in multiple places of our codebase. We also need to list a product's variants, get coupon info, and apply a discount to a list of variants on several occasions for different business purposes.
With that, the following tiny atoms of business logic emerged:
```ts
const getProduct = composable(({ productId }: { productId: string }) => {
// This would come from your database
return { id: productId, name: 'Magical T-Shirt' }
})
const getVariants = composable(({ productId }: { productId: string }) => {
// This would come from your database
return [
{ productId, sku: 'small', name: 'Small', price: 8.99 },
{ productId, sku: 'medium', name: 'Medium', price: 10.99 },
{ productId, sku: 'large', name: 'Large', price: 12.99 },
]
})
// Usually, this type would come from your database lib
// You don't need to understand it now, but it's the type for
// an individual variant.
type Variant = UnpackData<typeof getVariants>[number]
const getCoupon = composable(({ couponCode }: { couponCode: string }) => {
// This would come from your database
return { code: couponCode, discount: 10 }
})
const applyDiscountToVariants = composable(
({ variants, discount }: { variants: Variant[]; discount: number }) =>
variants.map((variant) => ({
...variant,
priceWithDiscount: variant.price * (1 - discount / 100),
})),
)
```
> **Aside**
>
> — Why are we using a single object as the argument for our small functions? Why is it `{ productId }: { productId: string }` instead of simply `productId: string`?
>
> — Thank you for noticing! We'll get to that soon :)
## Using our atoms
Now let's rewrite `getProductPageData` to use these atomic functions instead of duplicating their code. An initial version looks like this:
```ts
const getProductPageData = composable(
async (productId: string, couponCode: string) => {
// Notice that composable functions are always async
const productResult = await getProduct({ productId })
if (!productResult.success) {
throw new Error('Could not find product')
}
const product = productResult.data
const variantsResult = await getVariants({ productId })
if (!variantsResult.success) {
throw new Error('Could not find variants')
}
const variants = variantsResult.data
const couponResult = await getCoupon({ couponCode })
if (!couponResult.success) {
throw new Error('Could not find coupon')
}
const coupon = couponResult.data
return { product, coupon, variants }
},
)
```
Well, it's not looking that good yet. The good part is that composable functions force us to deal with error cases, so we _had_ to make all the checks above. But there is a better way. If we rewrite the function to use [fromSuccess](https://github.com/seasonedcc/composable-functions/blob/main/API.md#fromsuccess), it looks much cleaner:
```ts
const getProductPageData = composable(
async (productId: string, couponCode: string) => {
const product = await fromSuccess(getProduct)({ productId })
const variants = await fromSuccess(getVariants)({ productId })
const coupon = await fromSuccess(getCoupon)({ couponCode })
return { product, coupon, variants }
},
)
```
It's starting to look better! `fromSuccess` does the check and throws the error for us when a function fails.
## Going molecular
We could consider our work done with the code we have so far. It is doing what it is supposed to do, it's broken down into tiny atoms of business logic, and it's dealing with errors properly.
But we believe there's an even better way to bond our atoms. Right now, they're not truly bonded. They are being used separately, one at a time, and we're manually piecing together their results. If we use [function composition](https://www.freecodecamp.org/news/function-composition-in-javascript/), we can bond our atoms to create molecular functions.
Before we get back to our online shop, let's go over the basics of composition with our silly `getLength` example from the beginning of the article.
Imagine you want to get the length of a string but return it as a string. This is the result we're expecting:
```ts
const result = await getLengthAsString('abc')
// result equals
// {
// success: true,
// data: '3', ⬅️ Notice this is a string 👀
// errors: []
// }
```
Our initial implementation of `getLengthAsString` could be:
```ts
const getLengthAsString =
composable((text: string) => String(text.length))
```
But we already have a `numberToString` composable function that converts a number to a string, so we want to use it:
```ts
const numberToString = composable((number: number) => String(number))
const getLengthAsString = composable((text: string) =>
fromSuccess(numberToString)(text.length),
)
```
Now it's time to add composition. For composing functions, we need [combinators](https://github.com/seasonedcc/composable-functions/blob/main/API.md#combinators). Combinators are functions that receive composable functions as input and return another composable function.
We're going to talk about a few combinators in this article, and the first one is [pipe](https://github.com/seasonedcc/composable-functions/blob/main/API.md#pipe). `pipe` creates a chain of composable functions that will be called in sequence, always passing the result of the last function called as the input to the next.
Here's our `getLenghAsString` using pipe:
```ts
const getLength = composable((text: string) => text.length)
const numberToString = composable((number: number) => String(number))
const getLengthAsString = pipe(getLength, numberToString)
const result = await getLengthAsString('abc')
// result equals
// {
// success: true,
// data: '3', ⬅️ It is a string 🎉
// errors: []
// }
```
## Why is it better this way?
There are a few reasons why the version with `pipe` is better than the one with `fromSuccess`:
First, it's easier to change. Want to return both the numeric and the string versions of the result? Just add a [map](https://github.com/seasonedcc/composable-functions/blob/main/API.md#map) to the composition:
```ts
const getLengthAsStringAndNumber = pipe(
getLength,
map(numberToString, (result, input) => ({
asNumber: input,
asString: result,
})),
)
const result = await getLengthAsStringAndNumber('abc')
// result equals
// {
// success: true,
// data: { asNumber: 3, asString: '3' },
// errors: []
// }
```
Notice how we didn't have to change anything in our atomic functions. They remained the same. Only the composition (our molecule) changed.
Second, it's easier to test. You can write one set of tests for `getLength`, another one for `numberToString`, and just enough tests on `getLengthAsString` to make sure the composition worked.
Lastly, all compositions are type-safe from end to end. For example, if we try to `pipe` a function that returns a string into a function that expects a number, the composition will fail.
## Back to our online store
Now it's time to create our `getProductPageData` with compositions. Here's one way of doing it:
```ts
const getRawData = collect({
product: getProduct,
variants: getVariants,
coupon: getCoupon,
})
const getRawDataWithDiscount = map(getRawData, (data) => ({
...data,
discount: data.coupon.discount,
}))
const getRawDataWithDiscountedVariants = sequence(
getRawDataWithDiscount,
applyDiscountToVariants,
)
const getProductPageData = map(
getRawDataWithDiscountedVariants,
([{ product, coupon }, variants]) => ({ product, coupon, variants }),
)
```
It looks daunting, I know. But let's walk through it together, one step at a time.
First, we [collect](https://github.com/seasonedcc/composable-functions/blob/main/API.md#collect) all the raw data we need on `getRawData`. This function receives `{ productId: string; couponCode: string }` and returns an object with `product`, `variants`, and `coupon`.
Then we [map](https://github.com/seasonedcc/composable-functions/blob/main/API.md#map) the raw data on `getRawDataWithDiscount`. This function receives the same `{ productId: string; couponCode: string }` input and returns an object with `product`, `variants`, `coupon`, and `discount`.
The reason we add the `discount` to the root of our object is because our `applyDiscountToVariants` takes a list of `variants` and the `discount` as input, not the `coupon`. In the real world, it's very common to have an atomic function that does what you need but require you to "massage your input" a little in before you can call it.
Next, we [sequence](https://github.com/seasonedcc/composable-functions/blob/main/API.md#sequence) getting the raw data with discount and applying the discount to our variants on `getRawDataWithDiscountedVariants`. It also receives `{ productId: string; couponCode: string }`. Then, it returns a [tuple](https://www.w3schools.com/typescript/typescript_tuples.php) with the result of `getRawDataWithDiscount` as the first element, and the result of `applyDiscountToVariants` as the second.
Finally, we map the result of `getRawDataWithDiscountedVariants` to get rid of the tuple and return an object with the final data structure we want on `getProductPageData`.
## Calling our function
Now you can call your business function from the outside world. This usually means calling it from inside a controller, a loader, or any other method for gathering data.
```ts
const result = await getProductPageData({
productId: '123',
couponCode: '10OFF',
})
if (!result.success) {
// 🚨 Any errors thrown in any of the composed functions
// will be on result.errors
result.errors.forEach(error => console.log(error))
return
}
console.log(result.data)
// {
// product: { id: '123', name: 'Magical T-Shirt' },
// coupon: { code: '10OFF', discount: 10 },
// variants: [
// {
// productId: '123',
// sku: 'small',
// name: 'Small',
// price: 8.99,
// priceWithDiscount: 8.091000000000001
// },
// {
// productId: '123',
// sku: 'medium',
// name: 'Medium',
// price: 10.99,
// priceWithDiscount: 9.891
// },
// {
// productId: '123',
// sku: 'large',
// name: 'Large',
// price: 12.99,
// priceWithDiscount: 11.691
// }
// ]
// }
```
As you can see, this version of `getProductPageData` receives an object with the product id and the coupon code instead of two arguments like we had on our initial version.
We commonly do that because it makes it easier to compose the functions. That's why our atomic functions also receive an object. For example, on `getRawDataWithDiscountedVariants` we can get the result of `getRawDataWithDiscount` and pass it to `applyDiscountToVariants` without transforming it, even if returns an object with more keys than what `applyDiscountToVariants` needs.
If our atomic functions expected multiple arguments instead of an object, we could transform our data at every stage to be exactly what the next function needs. But I think this is a good pattern that leads to more readable compositions.
## Thinking in composition
It takes a while to adjust our thought process to think of compositions instead of a sequence of function calls and if statements. To be honest, I'm not totally there yet. But the more I use composition, the more I write code that's maintainable and easy to test.
It will take you and your team some time and learning curve but once you start thinking in compositions, you can skip the intermediate functions above and write your compositions inline:
```ts
const getProductPageData = map(
sequence(
map(
collect({
product: getProduct,
variants: getVariants,
coupon: getCoupon,
}),
(data) => ({
...data,
discount: data.coupon.discount,
}),
),
applyDiscountToVariants,
),
([{ product, coupon }, variants]) => ({ product, coupon, variants }),
)
```
That's it. I hope this method of writing business code helps you give business logic the priority it deserves and create more resilient codebases 🤓
Let me know how it works for you! | danielweinmann |
1,900,420 | Eres el amor de mi vida. | Check out this Pen I made! | 0 | 2024-06-25T17:28:02 | https://dev.to/juan_serrano_d7813a72ad4e/eres-el-amor-de-mi-vida-3e64 | codepen | Check out this Pen I made!
{% codepen https://codepen.io/cottonbabe/pen/gOLbJVa %} | juan_serrano_d7813a72ad4e |
1,900,402 | Flat Fee Real Estate Marketing Agency | Company In Singapore | We have Your real Dream Home like Real Estate Advertising Real Estate Marketing Agency Singapore,... | 0 | 2024-06-25T17:16:44 | https://dev.to/jomejourney/flat-fee-real-estate-marketing-agency-company-in-singapore-26of | webdev | We have Your real Dream Home like Real Estate Advertising Real Estate Marketing Agency Singapore, Flat Fee Real Estate Marketing Agency, Company In Singapore with Jome Journey. We are always your Welcome to the jome journey world. We always offer **[Real Estate Advertising in Singapore](https://jomejourney.com/services/real-estate-marketing-agency/)**, where dreams meet reality and Jome Journey is your trusted companion on the path to finding your perfect home. JomeJourney to be your guiding light. Let us now is your turn your real estate aspirations into reality, one home at a time. just call only jome journey.
| jomejourney |
1,900,401 | Create an AWS S3 bucket using Terraform | Install Terraform: Ensure that you have Terraform installed. You can download it from the Terraform... | 0 | 2024-06-25T17:15:37 | https://dev.to/devops_den/create-an-aws-s3-bucket-using-terraform-49f9 | webdev, devops, devopsden, beginners | **Install Terraform:** Ensure that you have Terraform installed. You can download it from the Terraform website.
**Create a Directory for Your Terraform Configuration:** Create a directory for your Terraform configuration files.
```
mkdir terraform-s3
cd terraform-s3
```
**Create a Terraform Configuration File:** Create a file named main.tf and add the following content:
```
# main.tf
# Specify the provider
provider "aws" {
region = "us-west-2" # Change this to your preferred region
}
# Create an S3 bucket
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-unique-bucket-name" # Change this to your preferred bucket name
acl = "private"
tags = {
Name = "MyBucket"
Environment = "Dev"
}
}
# Optionally, add a bucket policy
resource "aws_s3_bucket_policy" "my_bucket_policy" {
bucket = aws_s3_bucket.my_bucket.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "s3:GetObject"
Effect = "Allow"
Principal = "*"
Resource = "${aws_s3_bucket.my_bucket.arn}/*"
}
]
})
}
```
Initialize Terraform: Initialize your Terraform configuration. This will download the AWS provider plugin.
```
terraform init
```
Apply the Configuration: Apply the Terraform configuration to create the S3 bucket.
```
terraform apply
```
Thank You
Read More About [S3 Bucket](https://devopsden.io/article/what-is-s3-bucket-in-aws)
| devops_den |
1,899,196 | I'm looking for a FullStack Software Developer Role | Hey y'all, hope you've been doing and feeling great! My name is Cherry Ramatis, and I'm currently... | 0 | 2024-06-25T17:09:10 | https://dev.to/cherryramatis/im-looking-for-a-fullstack-software-developer-role-417m | programming, career, webdev, coding | Hey y'all, hope you've been doing and feeling great! My name is Cherry Ramatis, and I'm currently looking for opportunities as a FullStack software developer.
I'm passionate about learning new things and being an active figure in the community to democratize knowledge as I find this the key to being a better professional and knowing cool people at the same time (win-win situation). I'm managing to do that by attending meetups, presenting talks, giving mentorship to junior and mid-level devs, producing friendly yet resourceful articles, and overall being an accessible and helpful figure with anyone.
On the personal side I have three beautiful dogs that I adore to walk by the beach and I love hanging out to karaoke pubs with my friends (great opportunity for a cool happy hour 👀)
## A little bit to know me
- **Name:** Cherry Ramatis
- **Currently living in:** São Paulo Brazil
- **Technologies that I actively work with professionally:**
- Typescript/Javascript
- React
- Nextjs
- Angular
- Nestjs
- Docker
- Github Actions
- PostgreSQL
- MongoDB
- **Technologies that I would love to work with:**
- Ruby
- Ruby on Rails
- Elixir
- Phoenix
- **Time coding in total:** About 10 years
- **Time coding professionally:** Currently in my 6 year
- **Number of talks performed both online and in person:**
- 3 online talks presented at the [He4rt Developers](https://discord.gg/he4rt) community
- 1 in person talk presented at the [ElixirDays](https://x.com/elaine_nw/status/1795459111678570643)
- **Number of published articles:** Currently at 21 articles published with around 67k views and 11k reached people
## Achievements that I'm proud of
- **Participation for a brazilian podcast "Elixir em Foco":** https://www.youtube.com/watch?v=zYl6ec4G4k8
- **Mention as one of the top 7 authors of 2023 by dev.to:** https://dev.to/devteam/top-7s-top-authors-of-the-year-120m
- **Open source contribution to a big database company:** https://cloud-getting-started.scylladb.com/stable/build-with-ruby
## My favorite projects
- **Regexer - A compiler from a single line language to regex:** https://github.com/cherryramatisdev/regexer
- **Modular architecture for HTTP Server with dependency injection using Ruby:** https://github.com/cherryramatisdev/api-with-dry-ruby
- **A compiler from a pseudo language to a valid byte code BEAM file in rust and elixir:** https://github.com/cherryramatisdev/beam_studies
- **A experiment with ruby to transform exceptions into Result monads:** https://github.com/cherryramatisdev/monadic-exceptions
## How you can reach me
- **Linkedin:** https://www.linkedin.com/in/cherryramatis/
- **Twitter:** https://x.com/cherryramatis
- **Dev.to:** https://dev.to/cherryramatis | cherryramatis |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.