teleren/devto huggingface dataset:
Embeddings and Vector Database
Published: 2024-01-28 16:07:06

**Embeddings and Vector Database**


    Creating an Embedding using OpenAI API for testing (Postman):

   POST Request:
   URL: api.openai.com/version1/embeddings
   Headers: 
   - Content-Type: application/json
   - Authorization: Bearer <API_KEY>
   Body:
   {
     "model": "ada002",
     "input": "hello world"
   }

    Creating a Workspace and Database in SingleStore:

   Create a workspace with the desired cloud platform and region:
   - Workspace Name: open AI Vector database
   - Cloud Platform: AWS (or Google/Microsoft Azure)
   - Region: US West (or the desired region)

   Create a database with a table for embeddings:
   - Database Name: open AI database
   - Table Columns:
      - Text (type: text)
      - Vector (type: blob)

    SQL Query to add to the Vector Database in SingleStore:

INSERT INTO myvectortable (text, vector) VALUES ('Hello World', JSON_ARRAY_PACK('[***]'));

    SQL Query to Search the Vector Database in SingleStore:

select text, dot_product (vector, JSON_ARRAY_PACK("[***]")) as score from myvectortable order by score desc limit 5;

    Fetching Embeddings using JavaScript (Node.js):

   JavaScript Code:
   // Assuming fetch is available (for modern browsers or Node.js with appropriate polyfills)
   const response = await fetch('api.openai.com/version1/embeddings', {
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
       'Authorization': 'Bearer <API_KEY>',
     },
     body: JSON.stringify({
       model: 'ada002',
       input: 'hello world',
     }),
   });
   const data = await response.json();
   console.log(data);

Please note t

hat some specific values like <API_KEY> and <EMBEDDING_TO_SEARCH> are placeholders and should be replaced with actual API keys and embedding values as needed in your implementation. Also, some parts of the transcript might be cut off or incomplete, so there may be additional commands that were not provided in the given text.
first time
Published: 2024-01-29 09:12:56

##anyways
**we can lead all of them** 
[click me join to the my site] (https://www.wikipedia.org/)
_asdfasfda_
**afdsfasdaf**
~~dont put my on the black dash~~
***its important file***

> clcik heresdfgafdsadfasiojvnasnjvasnijdvjasnv

`afdasfasf`
![image deskription] (https://twitter.com/IMG)
```js
fdfsdsaa
```
adsFasdf
`asdfasf`
[Tiny] Partition map in Kotlin
Tags: kotlin, tiny
Published: 2024-01-29 09:08:08

As you may know, Kotlin has a lot of useful functions to work with collections and maps. One such function is `Iterable.partition()` which splits a given iterable into a pair of lists by predicate. For instance:

```kotlin
val list = listOf(100, -5, 42, 25)
val (lessThan42, greaterThanOrEqualTo42) = list.partition { it < 42 }
println("lessThan42=$lessThan42")
println("greaterThanOrEqualTo42=$greaterThanOrEqualTo42")
```

And the output is

```
lessThan42=[-5, 25]
greaterThanOrEqualTo42=[100, 42]
```

However, for some reason, there is no `partition()` function for maps. So, let's right the wrong and create an extension function for it:

```kotlin
fun <K, V> Map<K, V>.partition(predicate: (Map.Entry<K, V>) -> Boolean): Pair<Map<K, V>, Map<K, V>> {
    val map1 = mutableMapOf<K, V>()
    val map2 = mutableMapOf<K, V>()
    entries.forEach {
        if (predicate(it)) {
            map1[it.key] = it.value
        } else {
            map2[it.key] = it.value
        }
    }
    return Pair(map1, map2)
}
```

Here is the usage example:

```kotlin
val list = listOf(100, -5, 42, 25)
val map = list.associateWith { it.toString() }
val (keyLessThan42, keyGreaterThanOrEqualTo42) = map.partition { it.key < 42 }
println("keyLessThan42=$keyLessThan42")
println("keyGreaterThanOrEqualTo42=$keyGreaterThanOrEqualTo42")
```

And the output is

```
keyLessThan42={-5=-5, 25=25}
keyGreaterThanOrEqualTo42={100=100, 42=42}
```

---

*Dream your code, code your dream.*
Нажмун Нахар: Хэрэв бид зоригтой байвал дөрвөн хананы дунд насыг барах ёсгүй
Published: 2024-01-29 09:08:04

Ажил таны халаасыг дүүргэдэг бол аялал таны сэтгэлийг дүүргэдэг гэдэг үг бий. Хүн өдөр тутмынхаа нэгэн хэвийн амьдралын хэмнэлээс гарах сайхан боломж бол аялал. Монгол орныхоо очиж үзээгүй гайхалтай газраар аялсан ч, алс хол улсын сонин содон соёлтой танилцаж, нутгийн хүмүүстэй уулзаж, байгалийн сайхныг харах нь сэтгэл сэргээхээс гадна хувь хүнийхээ хувьд ч аливааг эргэцүүлэх, хөгжих туршлага болж үлддэг.

"Би аялах л гэж төрсөн" хэмээн өөрийн амьдралын зорилгоо аялал болгосон энэ бүсгүйг Нажмун Нахар гэдэг. Түүний аялсан 168 дахь орон нь Монгол бөгөөд манайд аялахаар ирэхэд нь хэсэг хором уулзаж түүний хөл тавьсан улс орнуудын гайхалтай түүхээс бидэнтэй хуваалцсаныг хүргэж байна.

"БИ АЯЛАХ ГЭЖ Л ТӨРСӨН"
Test Scripts vs Test Cases
Tags: testing, testcase, testscript, softwaretesting
Published: 2024-01-29 09:06:47

Let’s discuss some of the basic differences between [test scripts and test cases](https://hubs.ly/Q02hYZjF0).


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


Software testing is a vast process of validating an application by following commands. Some use test cases, while others rely on test scripts when they move to automation. Both of these options work for testing software. But they only yield the best results and the correct reports when used at the right time.

Test cases mostly work well for manual testing and no-code automation. For instance, the above example of writing test cases with Testsigma shows how automation tools easily support plain English to perform complex test scenarios. On the other hand, test scripts are better suited for automation testing using code-based tools. When put in motion with the right set of prerequisites, test scripts, and test cases, verify the applications under test for all their features.
Jest: Exceeded Timeout of 5000 ms for a Test
Tags: testing, jest, javascript, beginners
Published: 2024-01-29 09:04:42

Encountering this error during test runs led me to the decision to address it by adding a timeout value to the test case. After experimenting with a few values, 7000 ms emerged as the optimal choice, and hoorah! 🎉 The test passed.

On another day, rerunning the tests revealed that the same test now failed with a timeout error:
```
Thrown: "Exceeded timeout of 7000 ms for a test.
    Add a timeout value to this test to increase the timeout if it's a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."
```

Additionally, a couple more errors appeared for other tests:
```
Thrown: "Exceeded timeout of 5000 ms for a test.
    Add a timeout value to this test to increase the timeout if it's a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."
```

Now, one test failed for a 7000 ms timeout and two others for a 5000 ms timeout. After trial-testing with different values, settling on 10000, 7000, 8000 seemed to solve the issue! 🎉🎉

But wait! Was the battle ⚔️ against Jest test timeouts truly won? Not quite. Similar situations recurred, necessitating manual trial-tests and updates to values in specific test cases.

So, how did I overcome this never-ending battle against Jest?The answer lies in configuring Jest timeouts! 😉
A new way to build websites? Feedback is needed for my application themex.
Tags: css, html, javascript, website
Published: 2024-01-29 09:02:46

Hello everyone! 👋

I'm excited to invite you all to explore my newest project: Themex. As a frontend developer, I have often worked with various CSS frameworks such as Bootstrap and Tailwind. However, I noticed a challenge: revisiting a project after a long time and deciphering the work done can be quite daunting.

This observation led me to develop Themex. My main goal with Themex is to provide a solution that not only prioritizes reproducibility but also ensures clarity and intuitiveness across various website projects. Built with vanilla JavaScript, CSS, and HTML, Themex includes the core web technologies we all care about. The aim is to provide a foundation that can be built in minutes and relevant CSS properties have been included. This is compiled in the browser and then continued later in the IDE.

I believe Themex could be a practical solution. To get an idea of what Themex offers and how it can transform your workflow, visit http://themexproject.com/ 🚀. I'm excited to hear your feedback and look forward to seeing how I can develop further with your insights!
📘 The Ultimate Cheat Sheet for Mastering AI Chatbots
Tags: chatgpt, news, career, ai
Published: 2024-01-29 09:00:00

Hello folks, today I found another great study that I would like to share with you. As a professional in the IT world, I'm always on the lookout for groundbreaking research that can transform the way we interact with technology. Recently, I stumbled upon a gem - a study that unveils the "26 Rules" for mastering AI chatbots.

This is more than just another guide; it's research that we can rely on with a considerable degree of certainty. This is especially true in 2024, as AI chatbots become increasingly sophisticated and integral to our digital lives.

The study, conducted by the VILA Lab at Mohamed bin Zayed University of Artificial Intelligence in Abu Dhabi, is a deep dive into the nuances of prompt-engineering – the art of effectively communicating with large language models (LLMs). Their findings results in a compelling piece of research titled “Principled Instructions Are All You Need for Questioning LLaMA-1/2 GPT-3.5/4”, further emphasising the importance of these principles.

### Key Takeaways from the Research

- Simplicity and Clarity: The study emphasizes the importance of clear and straightforward prompts, a principle echoed in the “26 Rules”. Clarity leads to more focused responses from AI.

- Specificity is Key: Being specific in our queries significantly improves the relevance and accuracy of AI responses.

- The Art of Prompt Structure: The way we frame our questions can make a world of difference. This is particularly evident in complex tasks, where breaking down the query into manageable parts leads to better results.

- Engagement and Interaction: How we engage with AI determines the quality of the output. The research and the ‘26 Rules’ both highlight the importance of this dynamic interaction.

👉 **Curious to see all 26 Rules?** [Check out the full article](https://iwooky.substack.com/p/the-ultimate-cheat-sheet-for-prompt-engineering) for a deeper dive into mastering your prompts.

![The Ultimate Cheat Sheet for Mastering AI Chatbots](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1y6qos5offj168hd2k6.jpg)
My personal favourites
Published: 2024-01-29 08:52:43

With the amount of upcoming JavaScript frameworks and the new benefits they each have, they all define a new set of rules which can limit your projects scalability with other technologies. I remember trying to use Svelte with PHP and that did not go well. That said, here is how I’d do it going into 2024.

- Typescript (for perfect JavaScript)
+ Reactjs / Vuejs
* Postgres (Database)
- Redis (if needed)
What is a healthy lifestyle, exactly?
Published: 2024-01-29 08:52:38

These five areas were chosen because prior studies have shown them to have a large impact on risk of premature death. Here is how these healthy habits were defined and measured:

1.   Healthy diet, which was calculated and rated based on the reported intake of healthy foods like vegetables, fruits, nuts, whole grains, healthy fats, and omega-3 fatty acids, and unhealthy foods like red and processed meats, sugar-sweetened beverages, trans fat, and sodium.

2.  Healthy physical activity level, which was measured as at least 30 minutes per day of moderate to vigorous activity daily.

3.   Healthy body weight, defined as a normal body mass index (BMI), which is between 18.5 and 24.9.

4.   Smoking, well, there is no healthy amount of smoking. "Healthy" here meant never having smoked.

5.   Moderate alcohol intake, which was measured as between 5 and 15 grams per day for women, and 5 to 30 grams per day for men. Generally, one drink contains about 14 grams of pure alcohol. That's 12 ounces of regular beer, 5 ounces of wine, or 1.5 ounces of distilled spirits.

Researchers also looked at data on age, ethnicity, and medication use, as well as comparison data from the National Health and Nutrition Examination Surveys and the Centers for Disease Control and Prevention's Wide-Ranging Online Data for Epidemiologic Research.
NestJs typeORM으로 MySQL 연결, 2024-01-29
Tags: nestjs, mysql
Published: 2024-01-29 08:51:43

src아래에 configs 폴더 생성
configs아래에 typeorm.config.ts 생성

```
import { TypeOrmModuleOptions } from "@nestjs/typeorm";

export const typeORMConfig : TypeOrmModuleOptions = {
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    username: '',
    password: '',
    database: '',
    entities: [__dirname + '/../**/*.entity.{js,ts}'],
    synchronize: true
}
```

_참조 : https://www.youtube.com/watch?v=3JminDpCJNE&t=13257s_
Creativity with Python: How to Create a Word Cloud
Tags: python, programming, wordcloud
Published: 2024-01-29 08:51:41

Visual representation of data has always been a fascinating aspect of analytics. Among these, word clouds stand out as a captivating way to represent textual data. Today, we're diving into the world of Python to see how a simple script can transform any piece of text into a visually stunning word cloud.

---

## What is a Word Cloud?
A word cloud is a collection of words depicted in different sizes, which represent the frequency or importance of each word. They are not only visually appealing but also provide a quick, insightful view of the key themes in a body of text.

---

## Python and Data Visualization
Python, with its vast libraries, is a powerhouse for data visualization. In this post, we focus on using the `wordcloud` library, a tool that simplifies the process of creating word clouds.

---

## The Script: Crafting Your Word Cloud
Let's break down the script:

```
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def create_word_cloud(text):
    # Generate a word cloud image
    wordcloud = WordCloud(background_color="white", max_words=200, contour_width=3, contour_color='steelblue')
    wordcloud.generate(text)

    # Display the generated image
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis("off")
    plt.show()

if __name__ == "__main__":
    user_input = input("Enter your favorite quote or text for the word cloud: ")
    create_word_cloud(user_input)
```

- Generating the Word Cloud: The WordCloud function from the wordcloud library is used to create the cloud.
- Customization: You can customize the background color, number of words, and more.
- Displaying the Image: Using matplotlib, the script displays the generated word cloud.

### Setting Up
To experiment with this script, you need to have Python installed. Additionally, install the wordcloud and matplotlib libraries using pip:

```
pip install wordcloud matplotlib
```

---

## Creating Your Word Cloud
Run the script, and enter your favorite quote, poem, or any text. Watch as the script transforms your words into a beautiful cloud of words.
For example:

```
Enter your favorite quote or text for the word cloud:  
Take time to deliberate but when the time for action has arrived stop thinking and go in.
```

Will generate this word cloud:

![Generated Word Cloud](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1px8z70vo1amy2od8du7.png)

---

## Applications
Word clouds can be used for:
- Analyzing key themes in documents or speeches
- Creating visually appealing representations of your favorite texts
- Educational purposes to help students identify key terms in lessons

---

## Conclusion
This simple Python script opens the door to a world where data and art collide. It shows how Python's simplicity and power can be leveraged to create not just functional, but also beautiful, results.
Fortify Your Code: A Junior Developer's Guide to Crafting Bulletproof Software
Tags: webdev, beginners, programming, productivity
Published: 2024-01-29 08:49:43

Hey fam! Today, let's dive into the fascinating world of writing code that stands strong against bugs and errors. Imagine it like building a fortress, where every line of code is a resilient brick. As you embark on this coding adventure, let's explore the essential tools that will transform your software into a bastion of reliability.

**1. Version Control: Your Code's Time Machine 🕰️**
Think of version control like a magical time machine for your code. Git is your trusty sidekick, allowing you to revisit different stages of your project's history. Branch out like a botanist experimenting with new code features while keeping the main garden (master branch) secure.

**2. Code Linters: The Grammar Police for Developers 🚔**
Ever had a grammar-savvy friend proofread your writing? Code linters do the same for your code! ESLint and Prettier ensure your code follows a consistent style guide, making it clean, readable, and easily understandable.

**3. Testing Suites: The Guardians of Functionality 🛡️**
Imagine testing suites as superheroes that protect your code's functionality. Jest and Mocha are your dynamic duos, ensuring each function in your codebase performs its role flawlessly. Unit tests act like loyal sidekicks, catching bugs before they even think about causing trouble.

**4. Continuous Integration (CI): Your Code's Personal Trainer 💪**
CI is like having a personal trainer for your codebase. Travis CI and Jenkins ensure that every piece of code you write is strong and fit for deployment. Automated builds pump up your code's muscles, making sure it can handle anything thrown its way.

**5. Code Reviews: The Collaborative Brainstorming Sessions 🧠**
Picture code reviews as collaborative brainstorming sessions. Submitting pull requests is like putting your idea on the table. Peer reviews bring fresh perspectives, constructive feedback, and the collective wisdom of the team, making your code even more resilient.

**6. Static Code Analysis: The Detective Uncovering Hidden Clues 🔍**
Static code analysis tools are like detectives searching for hidden clues in your codebase. SonarQube and CodeClimate play the detective role, revealing potential vulnerabilities and ensuring your code is secure.

**7. Documentation: Your Code's User Manual 📚**
Consider documentation as your code's user manual. READMEs, API documentation, and well-placed code comments guide future developers, making it easy for them to understand and extend your work.

In conclusion, crafting bulletproof code is not just a skill; it's an art. These tools are your brushes and shields, helping you create a masterpiece that stands resilient against the test of time. Embrace them, learn from their wisdom, and let your code fortresses inspire the developers who come after you.

Cover image by Photo by Mati Mango
How to use Markdown?
Published: 2024-01-29 08:41:22

I began my journey as a web developer in 2015, and since then, I've continued to grow and evolve as a developer, taking on new challenges and learning the latest technologies along the way. Now, in my early thirties, 7 years after starting my web development journey, I'm building cutting-edge web applications using modern technologies such as Next.js, TypeScript, Nestjs, Tailwindcss, Supabase and much more.

I am very much a progressive thinker and enjoy working on products end to end, from ideation all the way to development.

When I'm not in full-on developer mode, you can find me hovering around on twitter or on indie hacker, witnessing the journey of early startups or enjoying some free time. You can follow me on Twitter where I share tech-related bites and build in public, or you can follow me on GitHub.



```js



import { useEffect, useState } from "react";
import { LuMoonStar } from "react-icons/lu";
import { GoSun } from "react-icons/go";
import { FaGrinStars } from "react-icons/fa";

export function ThemeChanger() {
  const [theme, setTheme] = useState("light"); //dark

  function changeTheme() {
    if (theme === "light") {
      setTheme("dark");
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");
    } else {
      setTheme("light");
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");
    }
  }

  useEffect(() => {
    const localTheme = localStorage.getItem("theme");
    setTheme(localTheme);
    document.documentElement.classList.add(localTheme);
  }, []);
  2;
  return (
    <button onClick={changeTheme}>
      {theme === "light" && <GoSun className="w-[25px] h-[25px]" />}
      {theme === "dark" && <LuMoonStar className="w-[25px] h-[25px]" />}
    </button>
  );
}








```
Monday Warm-up: Kickstart Your Week with Productivity and Positivity! ✨🚀
Tags: beginners, devops, discuss
Published: 2024-01-29 08:40:00

Hey Devs! 👋

It's Monday, and a brand new week lies ahead, filled with possibilities and opportunities. Let's make the most of it by starting off with a productive and positive mindset. Here are a few ideas to warm up your Monday and set the tone for a great week ahead:
**
Plan Your Week**: 📅 Take a few moments to reflect on your goals and priorities for the week. Jot them down and create a roadmap to keep yourself on track. Break down big tasks into smaller, manageable ones, and schedule them throughout the week.

**Tackle the Tough Tasks**: 💪 Start your week by tackling the most challenging tasks on your to-do list. By addressing them head-on, you'll feel a sense of accomplishment and set a productive tone for the rest of the week.

**Review and Reflect**: 📝 Spend some time reviewing your previous week's accomplishments and challenges. Celebrate your wins and learn from any setbacks you experienced. Use these insights to make improvements and set clearer goals for the current week.

**Stay Organized**: 🗃️ Keep your workspace and digital environment tidy and organized. A clutter-free space promotes focus and reduces distractions. Take a few minutes to declutter your physical and digital spaces, ensuring everything is in order for a productive week.

**Practice Self-Care**: 💆‍♀️ Remember to prioritize self-care throughout the week. Take breaks, get some fresh air, exercise, and nourish your body with healthy meals. A healthy mind and body contribute to improved productivity and overall well-being.

**Engage with the Community**: 🤝 Reach out to your fellow developers, engage in discussions, and share your knowledge. Participating in the Dev Community or other online platforms fosters connections, learning, and inspiration. You never know what valuable insights or collaborations might come your way!

**Set Realistic Expectations**: ⚖️ While it's great to be ambitious, it's equally important to set realistic expectations for yourself. Be mindful of your workload and avoid overcommitting. Setting achievable goals allows you to maintain a healthy work-life balance and avoid unnecessary stress.

Remember, each Monday is an opportunity for a fresh start. Embrace it with enthusiasm, positivity, and determination. Let's make this week one of growth, learning, and accomplishment! 🌟

What are your favorite Monday warm-up rituals? Share your thoughts and ideas in the comments below. Let's inspire each other to start the week on a high note! 💬✨

Wishing you all a fantastic and productive week ahead! 🌈💪
5 star review
Published: 2024-01-29 08:35:54

🌟 Thank you for the glowing 5-star review! 🙌 Your feedback means the world to us and motivates us to keep delivering top-notch service. We're thrilled to hear you had a fantastic experience. Looking forward to serving you again soon! #Grateful #CustomerAppreciation #FeedbackIsFuel #TopNotchService #FiveStarExperience
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftvoi0jj4cxe9d3dt3rm.jpg)