teleren/devto huggingface dataset:
Learn SwiftUI (Day 13/100)
Tags: swift
Published: 2024-05-02 16:02:29

## Swift

* protocols
* extensions
* protocol extensions

```swift
import Cocoa

// ## protocol

// {get set} -> no comman in between
// {get} or {get set}, not possible for just {set}

protocol Vehicle {
    var name: String { get }
    var currentPassengers: Int { get set }
    func estimateTime(for distance: Int) -> Int
    func travel(distance: Int)
}

struct Rocket: Vehicle {
    let name = "rocket"
    var currentPassengers = 0
    
    func estimateTime(for distance: Int) -> Int {
        return distance / 100
    }
    
    func travel(distance: Int) {
        print("\(name) traveled \(distance) already")
    }
}

var r = Rocket()
r.travel(distance: 12)

// opaque return type
/*
 they let us hide information in our code, but not from the Swift compiler.
 This means we reserve the right to make our code flexible
 internally so that we can return different things in the future,
 but Swift always understands the actual data type being returned
 and will check it appropriately.
 */

func getRandomNumber() -> some Equatable {
    Int.random(in: 1...6)
}

/*
 when you see some View in your SwiftUI code, it’s effectively us telling
 Swift “this is going to send back some kind of view to lay out, but I don’t
 want to write out the exact thing – you figure it out for yourself.”
 */

// ## Extentions
/*
 Extensions let us add functionality to any type, whether we created it or 
 someone else created it – even one of Apple’s own types.
 */

extension String {
    func trimmed() -> String {
        self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}
let a = " hello world   "
print(a.trimmed())

/*
 If want to change the string itself, use:
 mutating func trim() {
     self = self.trimmed()
 }
 */

// ## can add computed property extension to a type
/*
 var lines: [String] {
     self.components(separatedBy: .newlines)
 }
 */

// ## put custom init in extension
/*
 if we implement a custom initializer inside an extension, then Swift won’t
 disable the automatic memberwise initializer.
 extension Book {
     init(title: String, pageCount: Int) {
         self.title = title
         self.pageCount = pageCount
         self.readingHours = pageCount / 50
     }
 }
 */

// ## protocol extensions
extension Collection {
    var isNotEmpty: Bool {
        isEmpty == false
    }
}

// use extension to implement a default method in protocol
protocol Person {
    var name: String { get }
    func sayHello()
}

extension Person {
    func sayHello() {
        print("Hi, I'm \(name)")
    }
}
```
Learn SwiftUI (Day 17/100)
Tags: swift
Published: 2024-05-02 20:46:14

## Swift UI

* TextField
* Picker
* Picker style
* NavigationStack
* Focus mode
* Toolbar

```swift
import SwiftUI

struct ContentView: View {
    @State private var checkAmount:Double = 0
    @State private var numOfPeopleIndex:Int = 0
    @State private var tipsPercent:Int = 10
    @FocusState private var isFocused: Bool
    
    private let minPeopleCount = 2
    private let tipsPercentList: [Int] = [10, 15, 18, 20, 25, 0]
    
    
    var amountPerPerson: Double {
        checkAmount * (1.0 + Double(tipsPercent) / 100.0) / Double(numOfPeopleIndex + minPeopleCount)
    }
    
    var body: some View {
        NavigationStack {
            Form {
                Section{
                    TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
                        .keyboardType(.numberPad)
                        .focused($isFocused)
                    Picker("Number of people", selection: $numOfPeopleIndex) {
                        ForEach(2..<20) {
                            Text("\($0) People")
                        }
                    }
                    .pickerStyle(.navigationLink)
                }
                
                Section("Tip") {
                    Picker("Tip Percentage", selection: $tipsPercent) {
                        ForEach(tipsPercentList, id: \.self) {
                            Text("\($0)%")
                        }
                    }
                    .pickerStyle(.segmented)
                }
                
                Section("Amount per person") {
                    Text(amountPerPerson, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
                }
                
            }
            .navigationTitle("We Split")
            .toolbar {
                if isFocused {
                    Button("Done") {
                        isFocused = false
                    }
                }
            }
        }
    }
}
```

Running:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58c8wrz75pt4kgkrs1nd.png)
Taming the Warehouse Chaos: Unleash Growth with a Warehouse Management Website
Tags: python, programming, freelance, javascript
Published: 2024-05-02 20:46:04

## Taming the Warehouse Chaos: Unleash Growth with a Warehouse Management Website

Hey DEV Community!  As a freelancer, I see countless businesses struggling with disorganized warehouses and inefficient inventory management. This chaos hinders growth and profitability. But what if I told you a dedicated warehouse and inventory management website could be your secret weapon?

**Imagine a world where your warehouse runs like a well-oiled machine.**  From tracking stock levels to optimizing picking and packing, a warehouse management website empowers you to take control. Here's how it fuels your business growth:

* **Inventory Visibility at Your Fingertips:**  Say goodbye to manual stock checks and hello to real-time inventory tracking.  Never run out of stock again, and avoid costly overstocking.
* **Streamlined Order Fulfillment:**  Optimize picking and packing processes with automated workflows.  Reduce fulfillment times, improve accuracy, and keep your customers happy.
* **Goodbye Guesswork, Hello Data-Driven Decisions:**  Gain valuable insights into inventory trends and demand forecasting.  Make informed purchasing decisions and optimize your warehouse layout for maximum efficiency.
* **Reduced Operational Costs:**  Minimize labor costs associated with manual inventory management. Automate repetitive tasks and free your team to focus on higher-value activities.
* **Collaboration Made Easy:**  Improve communication and transparency across departments.  Real-time data ensures everyone is on the same page, fostering a smoother workflow. 

**Think a warehouse management website is just for big corporations? Think again!** 

As a freelancer, I specialize in building custom warehouse management solutions at minimal cost.  Here's how I can help:

* **Identify Your Needs:**  We'll work together to understand your specific warehouse operations and challenges.
* **Choose the Right Platform:**  I'll help you select a user-friendly and affordable warehouse management software (WMS) platform.
* **Website Integration:**  I'll seamlessly integrate the WMS with your existing website, ensuring smooth data flow and centralized control.
* **Mobile-Friendly Solutions:**  Your team can access and manage inventory on the go with mobile-friendly website interfaces. 

**Stop letting your warehouse hold you back!**  Let's chat about how a dedicated website can transform your inventory management and propel your business forward.  Feel free to reach out through DEV Community or the contact information in my profile. 

Together, let's build a system that tames the warehouse chaos and unlocks explosive growth for your business!
What is Container Scanning?
Published: 2024-05-02 12:15:36


![What is Container Scanning?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qd4udwkgrs6syldx61ai.jpg)


Traversing the intricate domain of container security is crucial in today's digital era, where the implementation of applications within containers has become pervasive. However, alongside the benefits of mobility and compatibility, lie the shadows of vulnerabilities, poised to be exploited by cyber adversaries.

Enter container scanning, a guiding light in the realm of containerized application development. But what exactly does it entail? Container scanning involves the meticulous examination of images within containers, conducted by automated tools. These tools serve as vigilant sentinels, comparing container contents against a repository of known vulnerabilities, ready to raise the alarm at the slightest irregularity.

Yet, container scanning is not merely about identifying vulnerabilities; it represents a proactive stance against potential threats. By integrating container scanning into the DevSecOps pipeline, organizations can ensure adherence to industry standards, identify misconfigurations, and bolster their defenses against cyber assaults.

The varieties of container security scanning technologies are as diverse as the threats they guard against. From assessing network configurations to enforcing access controls and crafting tailored security policies, each plays a pivotal role in fortifying containerized applications.

So, how does container scanning wield its influence? It operates through three pivotal stages: scrutinizing base images, examining third-party resources, and evaluating application source code. By traversing these stages, container scanning unveils vulnerabilities lurking within the container ecosystem.

Nevertheless, challenges abound in the realm of container scanning. From the caliber of machine learning to the perennial issue of false positives and negatives, organizations must navigate these obstacles to realize the benefits of robust container security.

Enter CloudDefense.AI, an avant-garde solution for container security scanning. With its comprehensive suite of tools, CloudDefense.AI empowers organizations to scrutinize, secure, and monitor containers with unparalleled precision. By harnessing AI-driven vulnerability assessment and seamlessly integrating into the CI/CD pipeline, CloudDefense.AI offers a holistic approach to container security.

In conclusion, as the march towards cloud-based environments gains momentum, the significance of container scanning cannot be overstated. It's not just about shielding against vulnerabilities; it's about fostering a culture of security in an ever-evolving digital landscape. And with CloudDefense.AI leading the charge, organizations can embark on this journey with confidence, knowing that their containerized applications are fortified by the finest defenses.
Website Powerhouse: How the Right Portal Fuels Business Growth
Tags: web3, website, javascript, python
Published: 2024-05-02 20:15:42

##  Building Your Business Fortress: Why a Website is Your Growth Engine

Hey DEV Community! As a freelancer, I witness businesses of all sizes struggle with limited online presence. But what if I told you a well-designed website could be the cornerstone of your growth strategy? 

**Forget expensive brick-and-mortar limitations. A website is your 24/7 storefront, a hub for customer engagement, and a powerful tool to streamline internal processes.** Here's why a website tailored to your specific needs is a game-changer:

**Choose Your Weapon: The Power of Portal Platforms**

* **CRM Portal:**  Boost customer relationships with a Customer Relationship Management (CRM) portal. Manage leads, nurture interactions, and close deals efficiently, all within your website.  Happy customers lead to business growth!
* **CMS Portal:**   Empower yourself with a Content Management System (CMS) portal.  Easily update website content, showcase new products or services, and keep your audience informed.  A dynamic website fosters trust and engagement.
* **Logistics Portal:**  Optimize your operations with a Logistics portal.  Track inventory, manage deliveries, and provide real-time order updates to your customers.  Efficiency translates to faster growth.

**Beyond the Portal: Website Advantages for All Businesses**

* **Global Reach:**  Expand your market reach beyond geographical boundaries.  A website makes you accessible to anyone with an internet connection.
* **Enhanced Brand Image:**  A professional website creates a positive first impression, building trust and credibility with potential customers.
* **24/7 Sales & Marketing:**  Your website works tirelessly, even while you sleep.  It provides product information, captures leads, and drives sales around the clock.
* **Data-Driven Insights:**  Track website analytics to understand customer behavior and preferences.  Use these insights to refine your marketing strategies and maximize ROI.

**The best part? I can help you build this growth engine at a minimal cost!** 

As a freelancer, I specialize in creating custom business websites tailored to your specific needs and budget.  Whether you need a robust CRM portal, a user-friendly CMS platform, or a streamlined logistics solution, I can leverage my web development skills to bring your vision to life.

**Ready to unlock the power of a business website?** Let's chat!  I offer flexible freelance packages to fit any budget, and I'm passionate about helping businesses flourish online.  Feel free to reach out through DEV Community or the contact information in my profile.

Together, let's build a website that propels your business towards a future of growth and success!
GIT and GITHUB
Tags: webdev, css, opensource
Published: 2024-05-02 20:11:07

Hey, everyone

Imagine you're at a music festival, but instead of guitars and drums, everyone's carrying laptops and coding. That's basically what it's like to be part of a distributed team working on a project with Git and GitHub.

We're like a virtual band, coming from different parts of the country, but jamming together on the same project. We write the same code, solve challenges, and pursue one goal - to create something amazing.

But, have you ever wondered how we manage to work together seamlessly, like a well-rehearsed orchestra? That's where Git and GitHub come in - the conductors of our coding symphony.

Let me introduce you to the world of Git and GitHub, where version control and collaboration meet. It's a game-changer for developers, and I'm excited to share it with you."

This opening aims to:

- Use a relatable and humorous analogy (the music festival) to explain the concept of distributed teamwork
- Emphasize the importance of collaboration and version control
- Set the tone for an engaging and accessible article



**Content**
Introduction:

- Briefly explain what Git and GitHub are
- Mention the importance of version control and collaboration in software development

What is Git?

- Define Git and its purpose
- Explain key Git concepts:
    - Repositories (repos)
    - Commits
    - Branches
    - Merging
    - Pull requests

What is GitHub?

- Explain what GitHub is and its relationship to Git
- Describe GitHub features:
    - Repos
    - Issues
    - Pull requests
    - Code review
    - Collaboration tools

Setting up Git and GitHub:

- Guide readers through installing Git and creating a GitHub account
- Explain how to link local Git repositories to GitHub

Basic Git Commands:

- Cover essential Git commands:
    - git init
    - git add
    - git commit
    - git log
    - git branch
    - git merge

GitHub Workflow:

- Describe the typical workflow:
    - Creating a new branch
    - Making changes and committing
    - Creating a pull request
    - Reviewing and merging code

Tips and Best Practices:

- Offer advice on:
    - Writing clear commit messages
    - Using branches effectively
    - Code review etiquette
    - Collaborating with team members

Conclusion:

- Summarize the importance of Git and GitHub in software development
- Encourage readers to practice and explore further


Stay tuned 🔔
Gmail and ChatGPT in your Dock
Tags: softwaredevelopment, chatgpt, macos
Published: 2024-05-18 18:23:44

---
title: Gmail and ChatGPT in your Dock
published: true
date: 2024-05-02 20:06:17 UTC
tags: SoftwareDevelopment,chatgpt,macos
canonical_url: https://blog.jonathanflower.com/software-development/gmail-and-chatgpt-in-your-dock/
---

Did you know you can add web apps like ChatGPT to your dock in Sonoma?

I absolutely love this feature. Hands down, my favorite feature of Sonoma.

This means I can Command + Tab to select the Gmail app!


![Gmail, ChatGPT, and Claude in Mac Dock](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fcn0eo9dmfyp19doasr4.png)

![Gmail macos app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/81rc66ix58dp0jonj28m.png)





## How to add a web app to your dock

1. Open Safari
2. Navigate to the website you want to add to your dock
3. Click: File -> Add to Dock…


![add to dock](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ec4yu7hzrsghzbxehnbs.png)
Computer Vision Meetup: Who needs RLHF When You Have SFT?
Tags: computervision, ai, machinelearning, datascience
Published: 2024-05-02 19:49:34

This talk will center around Reinforcement Learning from Human Feedback, and more importantly, “Why” is it even needed over Supervised Fine-Tuning? We will also understand in easy terms some current open problems in RLHF as far as research in academia is concerned.

Speaker: [Srishti Gureja](https://www.linkedin.com/in/srishti-gureja-a51841171/) is an ML engineer and researcher broadly interested in two things: ML efficiency techniques, including but not limited to designing algorithms that make maximum use of the hardware at hand, and the alignment in LLMs using literature from RL. She is currently researching better, simpler methods for aligning language models with Eleuther AI and Alex Havrilla from Georgia Tech. her full-time job is as an ML Engineer at Writesonic, a YC-backed startup.

Not a Meetup member? Sign up to attend the next event:

https://voxel51.com/computer-vision-ai-meetups/

Recorded on May 2, 2024 at the AI, Machine Learning and Data Science Meetup.
Implementing repeating-key XOR
Tags: 100daystooffload, cryptopals, challenge
Published: 2024-05-02 19:45:10

This is the fifth crypto challenge in set 1 from [cryptopals](cryptopals.com), which is the qualifying set. 

The difficulty level is relatively easy, to solve this problem I have used the programming language Go.

# Problem description

Here is the opening stanza of an important work of the English language:

```text
Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal
```

Encrypt it, under the key "ICE", using repeating-key XOR.

In repeating-key XOR, you'll sequentially apply each byte of the key; the first byte of plaintext will be XOR'd against I, the next C, the next E, then I again for the 4th byte, and so on.

It should come out to:

```text
0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f
```

# Solution

Lets start with trying to implement the repeating key XOR function. In this function we would like to loop over each byte in the plaintext.

```golang
for i, v := range plaintext {
    ...
}
```

For each byte we need to XOR with a the "current" byte in the key. So for index, `i = 0` we want to XOR with the first letter in the key, `key index = 0`, and so on.

| i   | key index |
| --- | --------- |
| 0   | 0 (I)     |
| 1   | 1 (C)     |
| 2   | 2 (E)     |
| 3   | 0 (I)     |
| 4   | 1 (C)     |
| 5   | 2 (E)     |
| ... | ... (x)   |

Here we can use the modulus operator, `%`, to calculate the key index. By using the length of the key we can use these expressions.

```golang
keyLength := len(key)
keyIndex := i%keyLength
```

If we then put these pieces together into a function called, `RepeatingKeyXOR`, we would get this function.

```golang
func RepeatingKeyXOR(plaintext, key []byte) []byte {
	result := make([]byte, len(plaintext))
	keyLength := len(key)

	for i, v := range plaintext {
		result[i] = v ^ key[i%keyLength]
	}

	return result
}
```

To verify that it's working as expected we can create the following unit test with the information from the problem description.

```golang
func TestRepeatingKeyXOR(t *testing.T) {
	plaintext := []byte("Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal")

	result := basics.RepeatingKeyXOR(plaintext, []byte("ICE"))

	expected, _ := hex.DecodeString("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f")

	if !bytes.Equal(result, expected) {
		t.Errorf("Expected: %v, Got: %v", expected, result)
	}
}
```

The output of running this test is, `PASS`.

# Conclusion

The key to solve this solution is to find a good way to rotate the bytes in the given key, and this is done with the modulus operator, `%`, in Go.

I also had some issues to format the expected value correct, since I thought it was expected to keep the newline from the plaintext without encrypting it.

The complete solution can be found on [GitHub](https://github.com/stefanalfbo/cryptopals).
 
# References

* [Set 1 - Challenge 5](https://cryptopals.com/sets/1/challenges/5)
Earning the first bucks on Upwork
Tags: career, upwork, freelance, devops
Published: 2024-05-02 19:44:11

Getting started with side gigs can be quite a hassle at first, but I think they just depend on few simple factors. I believe following through them should get you started rather quickly. My first advice is actually lays in the title: focusing on one major platform: Upwork. In the last several years, I've tried multiple platforms, and got the most interaction there. So, I will leave my focus for this article on Upwork only.

## Who am I

I am a 22 years old who do DevOps & Linux administration work on the office and occasionally freelance as well. 

I'm sure there are lots of successful freelancer 16 year olds out there, but when I was 16, things didn't work out as wished them to be on Upwork. That made me focus on my skills rather than keep trying on the market, but I wish I stuck around longer while I was working on. 


## Having the right portfolio

Being clear on the description is the key: what are your daily responsibilities, what have you worked on, tech stack, maybe some future goals and that should be it. This brief and precise description is more than enough. 


## Choosing the right jobs

You should be selective of your jobs to apply for a lot of reasons: you don't want to pay for connects, you actually want to get hired for the project, better the gig better the pay, etc. My criteria is usually: 

 - Less than 5 applicants
 - Well-rated client
 - Payment verified
 - Precise description of the job

The money mostly doesn't matter, you should focus on having satisfied clients. Even if you spend much time than you expected at first, making the client happy will have your profile rated better and they WILL want to work with you again, in the future.

## Proposals

Proposals maybe play the biggest role on getting the job or not. I have friends who are great in what they do but simply don't get much action just because they're not expressing themselves the right way.

Read the job post thoroughly. Understand the objective clearly. I believe the ideal proposal looks something like this (what worked well for me so far):

> Hi!

> I have worked with X before, and manage Y at my full time job. I believe this should take 2-3 depending on your other environmental factors and my availability. We can have a meet and I can start immediately.

> Thanks! 


## Having a blog & media presence

Well, this is what I currently work on.  I think it'd People want to work with people who share their expertise in various media channels. So putting in the time to create blog posts that show technical skills won't hurt. This also being my first blog post!