teleren/devto huggingface dataset:
Looping over a reactive array in NixixJS
Tags: javascript, nixix, beginners, tutorial
Published: 2023-09-24 06:45:00

Looping over elements in an array is a very useful technique for programmers to know.
It is essential when manipulating the DOM, as I mentioned in my last post, how all JavaScript developers should know how to manipulate the DOM. 

Fortunately, JavaScript provides developers with many different ways of performing this operation seamlessly, but that is beyond the scope of this post.

In this post, I will explain how to loop over a reactive array(an array which it's elements change when state changes) in NixixJS using the built-in 'For' component.
Be sure to keep reading because you will learn something new by the end of this post.

✔️ First, create a component that returns some JSX to create the UI.

✔️ Next, create a reactive array(also known as a store) with the 'callStore' function exported by the 'nixix/primitives' module; The function returns a tuple which the first element is the argument passed to it and the second is the setter function for the store.

 ✔️ Third, import the For component from the 'nixix/hoc' module; You can use the component in your code as it is used in the example below.

The For component requires three props - 
  - The each prop: is the reactive array. 
  Behind the scenes, the For component 
  appends an effect which is called when 
  the length of the reactive array changes.     
  The effect does not replace old nodes     
  with new ones when the array changes, 
  rather it creates reusable DOM nodes 
  and uses the DocumentFragment Web 
  API to append new nodes to reduce the 
  DOM reflow time.

  - The children prop: is only one callback 
   that returns the nodes to be shown when 
   the reactive array is looped over.

  - The fallback prop: is the node to be shown when the length of the array is 0. This prop is optional.

In the example below, when the nodes are first created, three divs will be shown in the DOM. The next time - when the button is clicked and the reactive arrays length changes is '2', the first two of the formerly created divs are still shown in the DOM, with their props updated, and then the third div will be cached(removed from the DOM and kept in memory) for later use without destroying it wasteful recreating and replacing existing DOM nodes.


![Snappify code example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zgcyugip2zjs2demqmik.png)

This is just the tip of the iceberg of how the For component works, there is a plethora of exciting features to learn about. You can ask me about them in the comments below 😉. 

Do like 👍 and follow  🏃 for more content.
Toggle dark theme in Angular Material
Tags: angular, angularmaterial, webdev, typescript
Published: 2023-09-24 06:35:31

---
title: Toggle dark theme in Angular Material
published: true
description: Need to toggle between dark and light theme in Angular Material? We have got your back... Read this article to know how!
tags: angular,angularmaterial,webdevelopment,typescript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w4lorjrdjn2nnrkxxhrs.png
---

In one of our previous articles, we saw how to lazy load a dark theme. If you haven't already, please check it first:

{% embed https://dev.to/ngmaterialdev/save-some-bytes-when-using-multiple-themes-in-angular-material-components-agh %}

Now, to load the "dark-theme.css" based on user's choice, we will create a simple service called "StyleManager":

```typescript
// style-manager.service.ts

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class StyleManager {
  isDark = false;

  toggleDarkTheme() {
    if (this.isDark) {
      this.removeStyle('dark-theme');
      document.body.classList.remove('dark-theme');
      this.isDark = false;
    } else {
      const href = 'dark-theme.css';
      getLinkElementForKey('dark-theme').setAttribute('href', href);
      document.body.classList.add('dark-theme');
      this.isDark = true;
    }
  }

  removeStyle(key: string) {
    const existingLinkElement = getExistingLinkElementByKey(key);
    if (existingLinkElement) {
      document.head.removeChild(existingLinkElement);
    }
  }
}

function getLinkElementForKey(key: string) {
  return getExistingLinkElementByKey(key) || createLinkElementWithKey(key);
}

function getExistingLinkElementByKey(key: string) {
  return document.head.querySelector(
    `link[rel="stylesheet"].${getClassNameForKey(key)}`
  );
}

function createLinkElementWithKey(key: string) {
  const linkEl = document.createElement('link');
  linkEl.setAttribute('rel', 'stylesheet');
  linkEl.classList.add(getClassNameForKey(key));
  document.head.appendChild(linkEl);
  return linkEl;
}

function getClassNameForKey(key: string) {
  return `style-manager-${key}`;
}
```

Then you can inject the "StyleManager" service, and call "toggleDarkTheme" whenever you want!

```typescript
// src/app/app.component.ts

import { Component } from '@angular/core';
import { StyleManager } from './services/style-manager.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  title = 'my-app';
  isDark = this.styleManager.isDark;

  private styleManager = inject(StyleManager);

  toggleDarkTheme() {
    this.styleManager.toggleDarkTheme();
    this.isDark = !this.isDark;
  }
}
```

That's it!!! For more information, read full article at:

{% embed https://angular-material.dev/articles/angular-material-theming-system-complete-guide %}
Grey Box vs Double Grey Box Testing
Tags: softwaretesting, greyboxtesting, testing, doublegreyboxtesting
Published: 2023-09-24 06:17:57

**Grey box testing** and **double grey box testing** are two types of software testing methods that differ in the amount of information that is shared between the testers and the target system. 

In **grey box testing**, the testers have partial knowledge of the internal structure of the system, such as the architecture, the data structures, or the algorithms. They use this information to design test cases that can cover both the functionality and the code of the system. **Grey box testing** is a combination of black box testing and white box testing, where black box testing does not require any knowledge of the internal structure, and white box testing requires full access to the source code. **Grey box testing** can provide better test coverage and efficiency than black box testing, as well as identify context-specific errors that are related to web systems.

In **double grey box testing**, not only the testers have partial knowledge of the internal structure of the system, but also the system has partial knowledge of the test cases that are being executed. This means that the system can adapt its behavior or responses based on the test cases and try to evade or deceive the testers. **Double grey box testing** is often used in penetration testing or security testing, where the testers try to find vulnerabilities or weaknesses in the system, and the system tries to defend itself or hide its flaws. **Double grey box testing** can provide a realistic assessment of the security posture and resilience of the system, as well as challenge the skills and creativity of the testers.
Automate Your Facebook Presence with this Python Bot
Tags: api, python, facebook, bot
Published: 2023-09-24 06:01:17

[Github Repo](https://github.com/Gerry-Aballa/Facebook-GraphAPI-Bot)
Meet me on this [Facebook Page](https://www.facebook.com/profile.php?id=61551872334297)

Are you tired of manually posting updates to your Facebook Page every day? Do you want to streamline your social media management? If so, you're in luck! In this blog post, I'll introduce you to a Python script that allows you to automate your Facebook Page posts using the Facebook Graph API.


### Prerequisites

Before using the script, you need the following:

1. **Facebook Page and Developer Account:** You should have a Facebook Page where you want to make posts, and a Facebook Developer Account to obtain the necessary credentials.

2. **Access Tokens:** You need a Facebook Page Access Token, which you can get by creating a Facebook App and configuring permissions.

3. **Python Libraries:** Make sure you have the required Python libraries installed. You can install them using pip:
   ```
   pip install -r requirements.txt
   ```

### Configuration

In the `keys.py` file, replace the placeholders with your Facebook Page ID and Page Access Token.

```python
# keys.py

PAGE_ID = 'your_page_id'
PAGE_ACCESS_TOKEN = 'your_access_token'
```

### Usage

1. Set the message and link you want to post in the script:

   ```python
   post_message = 'Hello Python 🐍. I bet you are awesome today!🚀🚀.\nI am a bot 🤖. Meet me on Github'
   post_data = {
       'message': post_message,
       'link': 'https://github.com/Gerry-Aballa/Facebook-GraphAPI-Bot',
       'access_token': keys.PAGE_ACCESS_TOKEN
   }
   ```

2. Schedule the post time using the `schedule.every().day.at()` method. By default, it's set to post at 8:00 AM every day. You can adjust the time to your preference.

3. Run the script:

   ```
   python3 facebook.py
   ```

   The script will run indefinitely, posting your message and link at the scheduled time each day.

## Keep Your Access Tokens Secure

Remember to keep your Facebook Page Access Token and other sensitive information secure. Avoid sharing them in public repositories or exposing them to unauthorised users. Consider using secure methods like environment variables in production environments.

With this Python script, you can take the hassle out of Facebook Page management and focus on creating engaging content for your audience.

Automate your posts, stay connected, and watch your online presence thrive!
Task 2
Published: 2023-09-24 05:25:30

**Q1: Create a sample decision table for fields First Name, Last Name, Email, Phone, Appointment Date/time.**

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

T - True (Correct value)
F - False (Wrong input)
B - Blanks

**QN2: Write sample test cases for a new mobile app with 3 roles: Basic user, Premium user, and Admin user.**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g425hz5uftr3h2lxaaz2.png)
My experience with OpenAI API
Tags: openapi, node, gpt3, javascript
Published: 2023-09-24 05:28:25

**Today I’ll share my experience working with openAI API (ChatGPT)**

✨ I have been working with AI based travel planner application✈️. I’m going to share my problem, what difficulties I’ve faced and how I came up with the solutions.

✨ **Problem** 

Planning a trip based on users interests and other preferences where trip could be of multiple days. 


✨**How OPEN AI helped me:** 

I’ve connected OPEN AI with user preferences to get related places with their personality.


⭐️ **Challenges** ⭐️

1. Taking all user preferences to GPT to understand user’s personality.

2. Making prompt so that every time i get same response format.

3. Had to recover data returned from GPT in my preferred JSON format.

4. Connect google places API to get users required trip places based on GPT driven result.

5. Handling GPT error while generating a trip for smooth user experience.

⭐️ **Solutions** ⭐️

1. GPT has limited token supply for each prompt. We can’t pass all our data through prompt. It’s better to make another prompt to get desired data before making the final prompt. In our case we had to generate personality for each profiles by providing user preferences and interests to maintain token length small enough in final prompt.

2. POMPT Engineering is must for making application smooth. Application needs same response all the time. So making a prompt that gives same response all the time, is must. We had to repeat same keyword sometimes to make GPT understand what we need the most. 

3. GPT generally replies like human being. But for developer like us who has a little more complex issues need the JSON format mostly. We need key-value pair in order to get out best. Cause parsing text and making JSON is not a good idea. We had specified our JSON format and current version of JSON to get the static output.

4. Now we have JSON, we need places. For getting places we made queries based on preferences of user and for each query we got some places from PLACES API.

5. Finally, the worst part of GPT is when traffic is high it breaks down. That’s a big issue until you start a project related to OPEN AI 😄 So all you need to check every time whether there is anything right or not. Making smooth user experience we had to handle them multiple times.

✨**That’s all from my perspective.** I believe learning knows no bounds. Feel free to share your thoughts 💭
What's new in Playwright 1.38
Tags: testing, playwright, webdev, news
Published: 2023-09-24 05:22:10

- Evergreen browsers
- Bug fixes
- New features

[Updating Playwright](https://playwright.dev/docs/intro#updating-playwright)
`npm install -D @playwright/test@latest` 
`npx playwright --version` 

## UI Mode Updates
`npx playwright test --ui`

![releases v1.38.0 image UI Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2tmcqxo8ru5p7ki1d18p.png)
1. Zoom into time range.
2. Network panel redesign.

{% embed https://www.youtube.com/watch?v=YGJTeXaZDTM %}

[releases v1.38.0](https://github.com/microsoft/playwright/releases/tag/v1.38.0)

[Slides](https://docs.google.com/presentation/d/1f25YSouChc2-UsU_1-GYJY_KWmL2w3FG6qGAXBxltMw/edit#slide=id.g11f345ce5b9_0_1):
{% embed https://docs.google.com/presentation/d/1f25YSouChc2-UsU_1-GYJY_KWmL2w3FG6qGAXBxltMw/edit#slide=id.g11f345ce5b9_0_1 %}
Exoplanet Data
Published: 2023-09-24 04:00:00

The NASA Exoplanet Archive is a database of exoplanets and their host stars. It contains information on over 5,000 confirmed exoplanets and thousands of candidates. The data is collected from a variety of sources and is updated regularly. The archive is a valuable resource for scientists and anyone interested in learning more about exoplanets.
[NASA Explonet Data](https://exoplanetarchive.ipac.caltech.edu/docs/data.html)


Sure, I can help you with that. Here is the copyedited text:

**Exoplanet data**

* Name: Name of the exoplanet.
* Mass (MJ): Mass of the exoplanet in terms of Jupiter masses (MJ).
* Radius (RJ): Radius of the exoplanet in terms of Jupiter radii (RJ).
* Period (days): Orbital period of the exoplanet in days.
* Semi-major axis (AU): Semi-major axis of the exoplanet's orbit in astronomical units (AU).
* Temp: Temperature of the exoplanet in kelvins (K).
* Discovery method: Method used to discover the exoplanet.
* Disc. Year: Year of discovery.
* Distance (ly): Distance from Earth in light years (ly).
* Host star mass (M☉): Mass of the host star in terms of solar masses (M☉).

## Analysis

```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt


def clean_value(value):
    if not isinstance(value, str):
        return value
    value = value.replace(',', '')
    if '±' in value:
        return float(value.split('±')[0])


df = pd.read_csv('exoplanets.csv')

# when were they discovered?
year = 'Disc. Year'
max_year = int(df[year].max())
min_year = int(df[year].min())
df[[year]].plot.hist(bins=1 + max_year - min_year, legend=True)

# how were they discovered?
method = 'Discovery method'
df[method].value_counts().plot(kind='pie')

# do we expect to see a correlation between mass and distance?
distance = 'Distance (ly)'
mass = 'Mass (MJ)'
df[distance] = df[distance].apply(clean_value)
df[mass] = df[mass].apply(clean_value)

sns.scatterplot(
    data=df, x=distance, y=mass, hue=method, palette='tab10', legend=False
)
plt.title('Mass vs. Distance')
plt.show()

# how about mass vs radius?
radius = 'Radius (RJ)'
df[radius] = df[radius].apply(clean_value)

sns.scatterplot(
    data=df, y=mass, x=radius, hue=method, palette='tab10', legend=False
)
plt.title('Mass vs. Radius')
plt.show()

# maybe a pairplot will help
sns.pairplot(
    data=df[[mass, radius, distance, method]], diag_kind='kde', palette='tab10'
)
plt.title('Pairplot of exoplanet properties')
plt.show()

# let's look directly at the correlations
correlations = df[[mass, radius, distance, method]].corr()
sns.heatmap(correlations, cmap='coolwarm')
plt.title('Correlations between exoplanet properties')
plt.show()

print(correlations)


```
Celebrate Educators with Mazezy's Unique Teacher Gifts
Published: 2023-09-24 04:33:15

https://mazezy.com/shop/teacher Mazezy's Teacher Gifts express deep gratitude to educators✔️ The main entity, Teacher Gifts✔️ embodies appreciation✔️ Supporting entities like Teacher Mugs✔️ Tote Bags✔️ and Keychains offer practical tokens of thanks✔️ Unique entities cater to diverse subjects and teaching styles✔️✔️✔️
+1 (601) 602-7601
sales@mazezy.com
200 Foxgate Avenue, Unit 11C, Hattiesburg, MS 39402, United States
https://teachergiftsmazezy.weebly.com/
https://teachergiftsmazezy.medium.com/
https://ameblo.jp/teachergiftsmazezy
https://band.us/band/92475613
https://boosty.to/teachergiftsmazezy
Task 2
Published: 2023-09-24 04:25:13

Boundary value analysis:
-> It is a black box testing methodology in which the test engineer, tests the application/software by giving the valid and invalid inputs.
-> It checks for the input values near the boundary that have a higher chance of error. Every partition has its maximum and minimum values and these maximum and minimum values are the boundary values of a partition.
Example: Consider a text field that holds the maximum 4 digit character. The max value of the field is 9999 and the min value is 1000. These are the boundary values and the values below min and above max, all fall under invalid cases and testing is done according to that.

Decision Table testing: 
-> Decision table testing is a software testing methodology used to test the system behavior for different input combinations. This is a systematic approach where the different input combinations and their corresponding system behavior i.e., Output for the input are recorded in the form of table. 
-> That is why it is also called as a Cause-Effect table where Cause and effects are captured for better test coverage. The output may be dependent on many input conditions and decision tables give a tabular view of various combinations of input conditions and these conditions are in the form of True(T) and False(F)
Example: Consider a login screen with a decision table. A login screen with E-mail and Password input boxes. The condition is  − The user will be routed to the homepage if they give the right username and password. An error warning will appear if any of the inputs are incorrect

Use case testing:
-> Use case testing is a type of black box testing technique that helps in identify test cases that form part of the entire system on a transaction basis from start to finish. 
-> It is a goal-oriented list of steps taken by the user to reach their target within a system. It focuses on understanding user and system behaviors. 
-> Use case testing is used for functional testing to find defects in a developed system.
Example : The user is buying an item from an online shopping site. The user will first login to the system and start performing a search of the item he needed. The user will select one or more items shown in the search results and he will add them to the cart. After all this, he will check out by selecting the payment option.

LCSAJ testing:
-> In LCSAJ testing, LCSAJ stands for Linear Code Sequence and Jump. LCSAJ is a type of white box testing whichis used to determine the maximum code coverage of the developed application. -> What percentage of the code is executed with the existing test cases. It helps in designing new test cases, which results in increase the coverage of the code under testing phase and test plan created.
What can you do with JavaScript(And where does it run)
Tags: webdev, javascript, beginners, programming
Published: 2023-09-24 03:42:51

## What can you do with JavaScript

For a long time, JavaScript was only used in browsers to build interactive web pages. Some developers refer to JavaScript as a toy language. But those days are gone because of huge community support and investments by large companies like Facebook and Google.

This days, you can build full-blown web or mobile apps, as well as real time networking applications like chat and video streaming services, command-line tools, or even games. Here is an example:

![A JavaScript game](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9taj7hvhhis0vrpkt4q.png 'A JavaScript game')

The next question.

## Where does JavaScript code run?

JavaScript was designed to run only in browsers so every browsers has what we call a JavaScript engine that can execute JavaScript code.

![JavaScript engine that execute JavaScript code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mf7m8liufcvcua8dzx5a.png 'JavaScript engine that execute JavaScript code')

For example, the JavaScript engines in Firefox and Chrome are SpiderMonkey and V8. 

In 2009, a very clever engineer called Ryan Dahl took the open-source JavaScript engine in Chrome and embedded it inside a C++ program. He called that program, node.

Node is a C++ program that includes Google's V8 JavaScript engine. Now with this, we can run JavaScript code out of a browser. So, we can pass our JavaScript code to node for execution. This means, with JavaScript, we can build the back-end for our web and mobile applications.

So, in a nutshell, JavaScript code can be run inside of a browser, or in node. Browsers and node provide a runtime environment for our JavaScript code.

That's it.

You can get my members-only eBook! It's been called "the most practical and informative" Complete HTML, CSS and JavaScript eBook. But it's a well-kept secret. Because it's not sold in every bookstore. [**The Complete HTML, CSS, and JavaScript eBook(Zero to Mastery)**](https://karlgusta.gumroad.com/l/edtbb) is packed with hands-on advice for understanding HTML, CSS, and JavaScript. From tips, to tricks, and hints, **The Complete HTML, CSS, and JavaScript eBook(Zero to Mastery)** guides you from beginner to advanced. It's a how-to eBook for people who want to roll up their sleeves and get to work! [You can get it here](https://karlgusta.gumroad.com/l/edtbb).

I hope you received excellent value in today's article. If you would like to go deeper, head over to [My Newsletter](karlgusta.substack.com), where you can find more great contents that will help you in your productivity, your impact and the quality of your life. I wish you an amazing day.