teleren/devto huggingface dataset:
Converting Callback-based SDK methods to Coroutines in Kotlin
Tags: kotlin, android
Published: 2023-07-07 13:00:02

---
title: Converting Callback-based SDK methods to Coroutines in Kotlin
published: true
date: 2023-07-07 12:59:26 UTC
tags: Kotlin,Android
canonical_url: https://www.rockandnull.com/convert-callbacks-coroutines-kotlin/
---

 ![Converting Callback-based SDK methods to Coroutines in Kotlin](https://images.unsplash.com/photo-1535231540604-72e8fbaf8cdb?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fHRyYW5zZm9ybXxlbnwwfHx8fDE2ODg3MzQ2MDR8MA&ixlib=rb-4.0.3&q=80&w=2000)

Kotlin's coroutines are an excellent feature of the language that makes asynchronous programming enjoyable and easy to understand.

However, even if you have organized your project neatly and extensively use coroutines, you may encounter a third-party library at some point that still uses old-fashioned callbacks. Combining callbacks and coroutines can be unpleasant, to say the least.

Luckily, there is a solution to this problem. You can wrap these callbacks and "transform" them into coroutines. It's generally a good practice to wrap your external dependencies and provide a consistent coroutine-style interface, regardless of the interface offered by the third-party libraries.

Below is a short code example that demonstrates how to quickly convert a library that uses callbacks into a coroutine interface, so you can start using it promptly.

```
    suspend fun callCallbackBasedSdkSomeMethod(): String {
        
        return suspendCancellableCoroutine { continuation -> // 1.
        
            CallbackBasedSdk.getInstance().someMethod( // 2.
                object : Callback {
                    override fun onSuccess(result: String) {
                        continuation.resume(result) // 3.
                    }
                    
                    override fun onFailure(e: TerminalException) {
                        continuation.resumeWithException(e) // 4.
                    }
                },
            )

            continuation.invokeOnCancellation { // 5.
                CallbackBasedSdk.getInstance().stopSomeMethod()
            }
        }
    }
```

1. Use Kotlin's `suspendCancellableCoroutine` to convert calls from a callback-based SDK to a coroutine-based one.
2. Inside the `suspendCancellableCoroutine`'s`block` parameter call the callback-based SDK method as you would normally do.
3. Use the `continuation.resumt()` to resume the execution of the coroutine and provide results.
4. Optionally, use `continuation.resumeWithException()` to throw an exception in the context of the coroutine.
5. In case the coroutine is canceled, you can define if any action needs to be taken to cancel the request in flight.

Hopefully, this help you maintain a consistent coroutine-based codebase in your Kotlin project.

Happy coding!
DEMO - AWS API Gateway Serverless WebScokets
Tags: aws, apigateway, webscokets, serverless
Published: 2023-07-07 12:58:40


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

**This tutorial explains what WebScokets are how the communication flow happens in WebScokets with a demo on how you can use Web Sockets in API Gateway.**

[Navigate to the link to watch the demo](https://www.youtube.com/watch?v=Tpg4r2cKQ24&t=5s)
Illustrate your comments
Tags: documentation, programming
Published: 2023-07-07 12:56:48

I remember the day structural sharing in data structures "clicked" for me. It was illustrated by a drawing of boxes and arrows.

An image is a powerful way to communicate relationships between objects, distance, size, time, all of which are relevant in a program.


![Unflattening, Nick Sousanis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hluhee1va5b2x9wskkha.png "In “Unflattening”, Nick Sousanis illustrates how shape, distance, repetition, separation, negative space and other visual tools can communicate relationships.")

Comments in code are communication tools: they explain an abstraction, an implementation, or give context to complex technical problems. They are the documentation closest to the code, where we need it most.  

We should use images in comments more often.   

We should not, however, lose the convenience of plain text: it can be checked in version control, shows up in diffs and works out-of-the-box in any text editor.   
Nor should we entirely remove sentences, because phrases can be searched for in a search engine and can be read by accessibility tools or people who don't like visual communication.

Text-based diagrams are, to me, a good compromise. Look at this example:

```

            No data duplication

┌───────────┐                 ┌───────────┐
│ Version A │                 │ Version B │
└───────────┘                 └───────────┘
      │                             │
      ├─────────────┬───────────────┘
      │             │
┌─────▼────┐  ┌─────▼────┐
│ Data A 1 │  │ Data A 2 │
└──────────┘  └──────────┘
              ──────────────
           With data duplication

┌───────────┐                 ┌───────────┐
│ Version A │                 │ Version B │
└───────────┘                 └───────────┘
      │                             │
      ├─────────────┐               ├─────────────┐
      │             │               │             │
┌─────▼────┐  ┌─────▼────┐    ┌─────▼────┐  ┌─────▼────┐
│ Data A 1 │  │ Data A 2 │    │ Data B 1 │  │ Data B 2 │
└──────────┘  └──────────┘    └──────────┘  └──────────┘
```

I generated this diagram with [monodraw](https://monodraw.helftone.com) a paid (but not expensive) macos app, which can export text-based drawings with options to easily paste into common comment formats.  


![Monodraw text export menu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otaaomm70ya8gdevds7j.png "A list of common comment formats in the monodraw export menu.")

Communicating ideas with pictures seems to be obvious everywhere, from art to education and marketing. Why not use it in comments?

> Meaning is thus conveyed not only by what's depicted, but through structure:
> the size, shape, placement, and relationship of components - what they're next to, and what they're not, matters.
> <cite><u>Unflattening</u>, Nick Sousanis</cite>

[Original article on my blog](https://camillehdl.dev/illustrate-your-comments/)
Deployment of Next.js Flask app
Published: 2023-07-07 12:54:22

Hello,

For the first time I am trying to deploy nextjs app with flask as backend.

I used flask in my pages/api directory.

If I run "npm run build" It will just be running "info Creating an optimized production build" for a while and nothing happens.

The script code in pacakge.json:
`  "scripts": {
    "flask-dev": "python -m flask --app pages/api/index run -p 8080 --reload",
    "next-dev": "next dev",
    "dev": "concurrently \"pnpm run next-dev\" \"pnpm run flask-dev\"",
    "build": "next build"
  },`

I am not sure if python will be running if I just build next js app, but since I havent deployed any app like this I appreciate any anwer and help.

My question is:
Will python be running on my hosted web site if I just persist and wait for the npm build to be finished?
100 Days Code Challenge: Frontend Engineers
Tags: 100daysofcode, javascript, typescript
Published: 2023-07-07 12:30:00

Hey fellow frontend engineers!

I'm excited to announce the launch of the 100 Days Code Challenge tailored specifically for frontend developers. If you're looking to level up your skills in JavaScript, TypeScript, Angular, React, and want to dive into handy tricks and interview problems, this challenge is perfect for you!

## What is the 100 Days Code Challenge?

The 100 Days Code Challenge is a self-paced, immersive coding journey designed to help you strengthen your frontend engineering skills. Over the course of 100 days, we'll embark on a collective effort to explore various aspects of frontend development, share knowledge, and support each other throughout the process.

## Who can join?

This challenge is open to frontend engineers of mid level, whether you're a beginner or an mid developer. It's a fantastic opportunity for those looking to sharpen the JavaScript and TypeScript skills and gain confidence in tackling real-world coding problems.

## What to expect?

Throughout the challenge, we'll cover a wide range of topics and areas of interest, including:

- JavaScript best practices and advanced concepts
- TypeScript fundamentals and type system mastery
- Building robust applications with Angular
- Harnessing the power of React and its ecosystem
- Handy frontend tricks and tips
- Interview problems and strategies

## How does it work?

- **Daily prompts**: Each day, a new prompt or coding problem will be posted on dev.to. You can find it under the challenge's dedicated tag or feed.
- **Code and share**: Code your solutions and share them with the community. You can publish your progress on your dev.to profile using the challenge's tag, allowing others to follow your journey and provide feedback.
- **Engage and support**: Connect with fellow participants, share ideas, ask questions, and offer support. We have a dedicated Discord channel for all participants to collaborate and learn from one another.
- **Track your progress**: Use the #100DaysCodeChallenge hashtag on social media platforms to share your progress outside of dev.to. It's a great way to connect with a broader developer community and celebrate milestones together.



If you have any questions or need assistance, feel free to reach out in the comments section.

Let's code, learn, and grow together! 🚀💻
Vertical Scaling vs Horizontal Scaling
Tags: design, javascript, programming, webdev
Published: 2023-07-07 12:20:21

## Vertical Scaling
Vertical scaling is accomplished by upgrading the hardware. It is often the simplest solution for short term scalability, as it doesn't require any architectural changes to your application.

**Ways to scale vertically**

- Improving I/O access by switching to SSDs.
- Reducing I/O operations by increasing RAM.
- Improving network throughput by upgrading network interfaces. → if the server is streaming a lot of video/media content.
- Switching to servers with more cores or processors. : more cores → less CPU context switches

**Benefits**

- You have to upgrade the hardware only.
- You do not have to rearchitect anything.
- Perfect for small applications.

**Limitations**

- Vertical scaling becomes extremely expensive beyond a certain point.
- After a certain limit, hardware upgradation is not possible.
- OS limitations: lock contention bottleneck.

## Horizontal Scaling

Horizontal Scaling is used to distribute the traffic among many servers.

We can add as many servers as we need. There is no upper limit as it was in vertical scaling.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1bbhanvm7lhj9xmz5x7e.png)
Next Auth for Stable App Router
Tags: nextjs, nextauth
Published: 2023-07-07 12:07:07

Please go to the [Live Demo](https://next-auth-implementation-phi.vercel.app/) deployed url & check if everything is working as expected. [Create issue](https://github.com/iambstha/next-auth-implementation/issues) if any bug/issue found. Thank you in advance.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7610adv76lsv39w2hipy.jpg)
[Github](https://github.com/iambstha/next-auth-implementation)
[Live Demo](https://next-auth-implementation-phi.vercel.app/)

Detailed post on how to build this step by step is coming soon.
Define ObjectId for Pydantic 2.x compatible
Tags: pydantic, mongodb, python, objectid
Published: 2023-07-07 12:06:52

I will update later.

For now, use this code.

## Test Versions
* FastAPI: 0.100.0
* python: 3.11.4
* pydantic: 2.0.2
* pymongo: 4.4.0
* pyhumps: 3.8.0

## ✨ Add new type PydanticObjectId
```python
from collections.abc import Callable
from typing import Annotated, Any

import humps
from bson import ObjectId
from pydantic import BaseModel, ConfigDict, GetJsonSchemaHandler
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema


class _ObjectIdPydanticAnnotation:
    @classmethod
    def __get_pydantic_core_schema__(
        cls,
        _source_type: Any,
        _handler: Callable[[Any], core_schema.CoreSchema],
    ) -> core_schema.CoreSchema:
        def validate_from_str(v: str) -> ObjectId:
            return ObjectId(v)

        from_str_schema = core_schema.chain_schema(
            [
                core_schema.str_schema(),
                core_schema.no_info_plain_validator_function(validate_from_str),
            ]
        )

        return core_schema.json_or_python_schema(
            json_schema=from_str_schema,
            python_schema=core_schema.union_schema(
                [
                    core_schema.is_instance_schema(ObjectId),
                    from_str_schema,
                ]
            ),
            serialization=core_schema.plain_serializer_function_ser_schema(lambda v: str(v)),
        )

    @classmethod
    def __get_pydantic_json_schema__(
        cls, _core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
    ) -> JsonSchemaValue:
        return handler(core_schema.str_schema())


PydanticObjectId = Annotated[ObjectId, _ObjectIdPydanticAnnotation]


class BaseODM(BaseModel):
    model_config = ConfigDict(
        alias_generator=humps.camelize,
        arbitrary_types_allowed=True,
        frozen=True,
        from_attributes=True,
        populate_by_name=True,
        str_strip_whitespace=True,
    )

    id: PydanticObjectId

```

## :necktie: You don't have to convert data in FastAPI

With `from_attributes=True`, formerly known as `orm_mode=True`, you don't have to use the `model_validate` method.

```python
import humps
from pydantic import BaseModel, ConfigDict


class EmbeddedBaseModel(BaseModel):
    model_config = ConfigDict(
        alias_generator=humps.camelize,
        arbitrary_types_allowed=True,
        frozen=True,
        from_attributes=True,  # 🪄 This is magic
        populate_by_name=True,
        str_strip_whitespace=True,
    )


class BaseODM(BaseModel):
    model_config = ConfigDict(
        alias_generator=humps.camelize,
        arbitrary_types_allowed=True,
        frozen=True,
        from_attributes=True,  # 🪄 This is magic
        populate_by_name=True,
        str_strip_whitespace=True,
    )

    id: PydanticObjectId
```


## Reference
* https://docs.pydantic.dev/latest/usage/types/custom/#handling-third-party-types
Laravel Validation: Tips and Tricks for Building Secure Applications
Tags: laravel, php, security
Published: 2023-07-07 12:04:31

---
title: Laravel Validation: Tips and Tricks for Building Secure Applications
published: true
description: 
tags: Laravel, php, security
# published_at: 2023-07-07 11:28 +0000
---
If you are taking any data from the user, pay attention to validations.

Unfortunately, I see some tutorials that takes data directly from the user, which allows the user to pass any inappropriate data or even guess the names of the database tables and send data to other fields that are not in the form.

Therefore, pay attention to the following:

1- Start with HTML... Your validations should start from the first HTML.
You should make sure that the required fields are marked as "required".

These required fields should be validated on the server-side but if the user leaves them empty... Why waste server requests on empty fields?

2- If you have MultiSelect/Select or Hidden fields, It's important to validate the value entered in them because it is easy for the user to inspect and change the data sent to the database.

3- Prevent Mass assignment, in laravel you can use one of these into your model ( fillable or guarded), The `guarded` property specifies which attributes should not be mass assignable, while the `fillable` property specifies which attributes are allowed to be mass assignable." 

4- It's very important to validate any type of image or file that will be uploaded.

5- Do not use `$request->all()` and take the validated data.

You are dealing with all kinds of users, so expect the worst.

If you have read this far, thank you for your time ❤️
Who's looking for open source contributors? (week 49)
Tags: discuss, opensource, contributorswanted, codenewbie
Published: 2023-07-07 12:00:00

---
title: Who's looking for open source contributors? (week 49)
series: Looking for Contributors
published: true
description: Discover which open source projects are actively seeking contributors. Learn how you can make a meaningful contribution to the open source community and gain valuable experience. Find out who's looking for open source contributors now.
tags: discuss, opensource, contributorswanted, codenewbie
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
published_at: 2023-07-07 12:00 +0000
---
Open Source thrives on community collaboration. Whether you're a seasoned contributor or just starting out, we're here to foster those connections and support your journey through these weekly posts!

## Tell us about your project
_Promote your project by providing a link to the repo. Everyone who posted in previous weeks is welcome back this week, as always 😄_

Open Source should be a welcoming space for contributors. The README is the front door of your project. If you'd like to check out an example of a README, here's our [OpenSauced/insights README](https://github.com/open-sauced/insights).

If you submit please have the following in your repo to make it welcoming and helpful for contributors:

1. README.md
2. CONTRIBUTING.md

Feel free to drop your issues and repos in the [OpenSauced Discord](https://discord.gg/opensauced) #:eyes:-looking-for-contributors channel at any time! 

If you're new to open source, and you're not sure where to start, check out our [Intro to Open Source course](https://github.com/open-sauced/intro). 

Finally, consider reading the [Best Practices for Maintainers](https://opensource.guide/best-practices/).

Just a note to say, we've restarted this post from something Ben was doing for a while :star-struck: 

Let's bring collaboration and inspiration to every open source contributor!
Join the AI revolution today! | Odin AI
Tags: beginners, programming, tutorial, react
Published: 2023-07-07 11:28:17


![Unleash the Power of Odin AI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hyi836ptsdz4ymw9hy7u.jpg)
Enhance your business operations, improve customer experiences, and unlock new opportunities. Sign up for [Odin AI ](https://getodin.ai/)now and get 50 free credits! No credit card required.
Data lakes and AWS
Tags: aws, database, cloud, cloudcomputing
Published: 2023-07-07 11:05:47


A data lake is a centralized repository that allows you to store all your structured and unstructured data at any scale. It is a SDAtool that can help you to store, analyze, and process large amounts of data.

Benefits of Using AWS for Data Lakes

There are many benefits to using AWS for data lakes, including:

Scalability: AWS is a highly scalable platform, so you can easily scale your data lake as your needs grow.
Durability: AWS offers a number of durable storage services, such as Amazon S3, that can help you to ensure that your data is safe and secure.
Security: AWS offers a number of security features, such as encryption and access control, that can help you to protect your data.
Cost-effectiveness: AWS offers a number of cost-effective storage and compute services that can help you to reduce the cost of your data lake.
How AWS Can Help You Build a Data Lake

AWS offers a number of services that can help you to build and manage a data lake. These services include:

Amazon S3: Amazon S3 is a scalable, durable, and secure object storage service that can be used to store all your data in a data lake.
Amazon EMR: Amazon EMR is a managed Hadoop and Spark platform that can be used to process data in a data lake.
Amazon Athena: Amazon Athena is a serverless query engine that can be used to query data in a data lake without the need to manage any infrastructure.
Amazon Redshift Spectrum: Amazon Redshift Spectrum is a fully managed, petabyte-scale analytics data warehouse that can be used to query data in a data lake without the need to move the data to Amazon Redshift.
AWS Lake Formation: AWS Lake Formation is a service that can help you to automate the management of your data lake.

Conclusion
AWS is a powerful platform that can help you to store, analyze, and process large amounts of data. If you are considering building a data lake, I highly recommend using AWS.
A tip to get a nice git history: let git tell your code story
Tags: career, beginners, programming, tutorial
Published: 2023-07-07 11:03:56


If you're new to git, it can be overwhelming to manage your code changes and keep your git history clean. In this post, we'll explore some tips to help you get a nice git history that tells your code story effectively.

## Avoid merge commits

Merge commits can make your git history messy and hard to follow. Instead, you can use git rebase to keep your git history linear and make it easier to understand. With git rebase, you can merge changes from one branch onto another and create a clean and concise git history.

## All in one, interactive rebase

To use git rebase, you can use the interactive mode (`-i`) to squash multiple commits into a single commit with a new message. For example, you can run the command `git rebase -i HEAD~3` to squash the last 4 commits into a new one with a new message. This will open up an editor where you can choose which commits to squash and edit the commit message. [GitHub](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/incorporating-changes-from-a-pull-request/about-pull-request-merges#squash-and-merge-your-commits) and [GitLab](https://docs.gitlab.com/ee/user/project/merge_requests/squash_and_merge.html) also support squash and merge operation to create a single commit with all your Pull/Merge Request changes.

## Use conventional commit

Conventional commit is a specification for adding human and machine-readable meaning to commit messages. By using a conventional commit format, you can make your commit messages more informative and easier to understand. To learn more about conventional commit, you can check out [this post](https://www.conventionalcommits.org/en/v1.0.0/) which explains what it is and how to use it effectively.

{% embed https://dev.to/juanvegadev/convetional-commit-a-meaningful-commit-message-proposal-4n1o %}

With these tips, you can create a clean and informative git history that tells the story of your code changes effectively. Happy coding!


[cover from pexels](https://www.pexels.com/photo/depth-of-field-photography-of-brown-tree-logs-923167/)
Why to use Testing Daily Application?
Tags: testing, beginners, tutorial, javascript
Published: 2023-07-07 10:47:56

To acquire the testing updates, one needs to open several platforms, such as YouTube, linkedin, Medium , etc., which is kind of tough to do every day and time consuming.

[This is where Testing Daily, come into the Picture]

[Follow the link for more detail](https://qaautomationlabs.com/why-to-use-testing-daily-application/)

Testing Daily For Android-
https://play.google.com/store/apps/details?id=info.testingdaily

Testing Daily for iPhone-
https://apps.apple.com/in/app/testing-daily/id1661612332