teleren/devto huggingface dataset:
Export an Array of JSON Objects to Excel with SheetJS
Tags: sheetjs, beginners, javascript
Published: 2023-03-07 06:29:45

In this article, we will demonstrate how to convert JSON response data to an Excel file with defined headers and columns that can be downloaded directly by the client.

To accomplish this, we will utilize the [SheetJS ](https://sheetjs.com/) plugin.

Let's begin, add a button that users will click to generate an export

```HTML
<button type="button" id="exportExcel" > Export Excel </button>
```

then create array of "employees" objects

```javascript
const employees = [
  {
    id: '1',
    name: 'Saitama',
    age: '32'
  },
  {
    id: '2',
    name: 'Genos',
    age: "24"
  }
]
```

Next create a workbook
`XLSX.utils.json_to_sheet` generates a worksheet:

```javascript
const worksheet = XLSX.utils.json_to_sheet(employees);
```

`XLSX.utils.book_new` creates a new workbook and `XLSX.utils.book_append_sheet` appends a worksheet to the workbook. The new worksheet will be called "Empoloyess":

```javascript
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Employees");
```

Last export the file
`XLSX.writeFile` creates a spreadsheet file and tries to write it to the system.  
`compression: true` enables ZIP compression for XLSX and other formats.

```javascript
XLSX.writeFile(workbook, "Employee Lists.xlsx", { compression: true });
```

That’s it! this is the simplest code to convert JSON data in XLSX EXCEL file which will download on the client side.

**Access functioning demo [here](https://codepen.io/raieldev/pen/LYJjgNO)**
 

### **PS.**

By default, `json_to_sheet` creates a worksheet with a header row. In this case, the headers come from the JS object keys: "id", "names" and "age".

Let's create array of custom header

```javascript
const excelHeader = [
  "Employee Id",
  "Full Name",
  "Age"
]
```

If we want to fix the header and customize the name we can simply use `XLSX.utils.sheet_add_aoa` that can write text values to the existing worksheet starting at cell A1:

```javascript
XLSX.utils.sheet_add_aoa(worksheet, [excelHeader], { origin: "A1" });
```

And since some names may exceed the default column width, we can adjust the column width by defining the "!cols" worksheet property. For example, the following line sets the width of column A to approximately length of the header + 5

```javascript

// Map the array and get the length and add 5 to add extra spaces.
// Push the value to the defined variable `wscols` 
// Assign the varialbe `wscols` to `worksheet["!cols"]`
let wscols = []
excelHeader.map(arr => {
  wscols.push({ wch: arr.length + 5 })
})
worksheet["!cols"] = wscols;
```

**Access functioning demo [here](https://codepen.io/raieldev/pen/oNPeQxV)**
python: Mock variations
Tags: python, mock
Published: 2023-03-07 06:24:21

This is my note on how to create various mocks. Please let me know if you have trouble creating a mock in your test.

```python
import pytest
from unittest.mock import Mock

# Create a mock with one attribute.
def test_mock_with_one_attribute():
    mock = Mock(one_attribute='one')
    assert "one" == mock.one_attribute

# Create a mock with multiple attributes.
def test_mock_with_multiple_attributes():
    mock = Mock(**{"one_attribute":"one","two_attribute":"two"})
    assert "one" == mock.one_attribute
    assert "two" == mock.two_attribute

# Create a mock with name attribute. As name is an argument of Mock, 
# we need to speficy it after create mock object.
def test_mock_name_attribute():
    mock = Mock()
    mock.name = "ken"
    assert "ken" == mock.name

# Set return value when the mock itself is called as function.
def test_mock_as_function():
    mock = Mock(return_value='result')
    assert "result" == mock()

# Create a mock with one method.
def test_mock_with_one_method():
    mock = Mock(**{"my_method.return_value":"result"})
    assert "result" == mock.my_method()

# Create a mock with several methods and attributes at once.
def test_mock_with_methods_and_attributes():
    mock = Mock(**{"my_method.return_value":"result_my",
                   "another_method.return_value":"result_another",
                   "one_attribute":"one",
                   "two_attribute":"two"})
    assert "result_my" == mock.my_method()
    assert "result_another" == mock.another_method()
    assert "one" == mock.one_attribute
    assert "two" == mock.two_attribute

# Create a method that returns Exception.
def test_mock_with_side_effect_exception():
    mock = Mock(side_effect=Exception("dummy"))
    with pytest.raises(Exception) as e:
        mock()
    assert "dummy" == str(e.value)

# Create a mock and inner mock as it's attribute
def test_mock_with_innter_mock_multiple_attributes():
    mock = Mock(data = Mock(**{"one_attribute":"one","two_attribute":"two"}))
    assert "one" == mock.data.one_attribute
    assert "two" == mock.data.two_attribute
```
What is Global variables in javascript?
Tags: javascript, webdev, beginners, programming
Published: 2023-03-07 06:21:21

In JavaScript, _a global variable is a variable that is accessible from anywhere in the code, including inside functions and blocks_.

Global variables are declared outside of any function or block, usually at the top of a script. Once declared, they can be accessed and modified from any part of the code, which makes them convenient but also potentially risky, as they can be accidentally overwritten or modified by different parts of the code.

Here's an example of how to declare a global variable in JavaScript:

```
var globalVariable = "I am a global variable";

console.log(globalVariable)

function myFunction() {
  globalVariable = "I am modified";
  console.log(globalVariable);
}

myFunction(); // outputs "I am modified"
console.log(globalVariable); // also outputs "I am modified"

```
In this example, globalVariable is a global variable that can be accessed and modified from any part of the code.

It's important to be careful when using global variables in JavaScript, as they can make code harder to maintain and test. It's usually better to use local variables when possible, and pass values between functions using parameters and return values.
AcademyOcean LMS
Tags: lms, emplyee, news
Published: 2023-03-07 06:07:16

[AcademyOcean](https://academyocean.com/) is a company that offers a comprehensive learning management system (LMS) for employee training, education, and development. The company specializes in providing solutions that are tailored to meet the unique needs of businesses of all sizes and industries.

The AcademyOcean platform is designed to help organizations manage all aspects of their training programs, from creating and delivering engaging content to tracking progress and analyzing results. The platform features a user-friendly interface that makes it easy for employees to access and complete training courses at their own pace.

In addition to the core LMS functionality, AcademyOcean offers a range of tools and features to help businesses create effective training programs. These include customizable course templates, quizzes and assessments, gamification elements, and social learning features.

AcademyOcean's solutions are suitable for businesses of all sizes, from small startups to large corporations. The platform can be customized to meet the specific needs of each organization, ensuring that businesses can create training programs that are effective and engaging for their employees.

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

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



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

Overall, AcademyOcean is a trusted partner for businesses looking to improve their employee training and development programs. With a range of tools and features designed to support learning and growth, the platform helps businesses improve their bottom line by increasing employee engagement, productivity, and performance.[](url)
O que é e para o que serve Lop For
Published: 2023-03-07 05:17:28

O loop for é uma estrutura de controle de fluxo utilizada na programação para percorrer uma array de elementos, executando um bloco de código para cada elemento dessa coleção. Essa estrutura é muito útil em situações em que precisamos realizar uma mesma operação em uma série de elementos, como percorrer uma lista de números, imprimir uma sequência de valores, ou buscar informações em um banco de dados.

O loop for é composto por três partes principais: 

- A **inicialização** da variável de controle.

- A **condição** de execução.

- O **incremento** da variável de controle.

A variável de controle é utilizada para percorrer a coleção de elementos, e inicializada com o primeiro elemento da coleção. 

Em seguida, o bloco de código é executado para cada elemento da coleção, e a variável de controle é incrementada até que atinja o último elemento.

Em JavaScript, existem duas formas principais de criar loops "for":
"for" clássico e "for...in". Cada um desses loops é usado para iterar sobre uma sequência de elementos, mas cada um tem sua própria sintaxe e comportamento. Neste artigo, vamos explorar as diferenças entre esses dois tipos de loops "for".

**"For" clássico**
O loop "for" clássico é usado para iterar sobre uma sequência de números em ordem crescente ou decrescente. A sintaxe geral do loop é a seguinte:

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

O argumento "início" define o número inicial da sequência, o argumento "condição" define a condição que o loop deve atender para continuar a execução e o argumento "incremento" define o que acontece com o contador em cada iteração. O corpo do loop é executado a cada iteração do loop.

Por exemplo, o seguinte loop "for" imprime os números de 0 a 4:

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

**"For...in"**
O loop "for...in" é usado para iterar sobre as propriedades de um objeto. A sintaxe geral do loop é a seguinte:


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

A cada iteração do loop, a variável "variável" assume o nome de uma propriedade do objeto, e o corpo do loop é executado. O loop "for...in" é útil para iterar sobre todas as propriedades de um objeto, incluindo as propriedades herdadas.

Por exemplo, o seguinte loop "for...in" imprime as propriedades de um objeto:

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

Em resumo, os loops "for" clássico e "for...in" são úteis para iterar sobre diferentes tipos de sequências em JavaScript. Cada um desses loops tem sua própria sintaxe e comportamento, e é importante escolher o tipo correto de loop para a tarefa em questão. O loop "for" clássico é usado para iterar sobre uma sequência de números, enquanto o loop "for...in" é usado para iterar sobre as propriedades de um objeto.
Loa Marshall Woburn III Chính Hãng Tại NgocKhoaMedia
Published: 2023-03-07 05:14:15

**Nếu bạn đang tìm kiếm một cửa hàng đáng tin cậy để mua loa Marshall Woburn III chính hãng, **[NgocKhoaMedia.com](https://ngockhoamedia.com/)** là lựa chọn tuyệt vời cho bạn.
**
Với hơn 10 năm kinh nghiệm trong lĩnh vực âm thanh và truyền hình, NgocKhoaMedia.com cam kết mang đến cho khách hàng sản phẩm chính hãng, chất lượng và dịch vụ tốt nhất.

Tại NgocKhoaMedia bạn có thể tìm thấy **[loa Marshall Woburn III](https://ngockhoamedia.com/loa-bluetooth-marshall-woburn-3/)** chính hãng với giá cả cạnh tranh và chế độ bảo hành đầy đủ. Chúng tôi luôn sẵn sàng hỗ trợ và tư vấn cho khách hàng để giúp họ lựa chọn sản phẩm phù hợp nhất với nhu cầu của mình.

Ngoài ra, NgocKhoaMedia.com còn cung cấp một loạt các sản phẩm âm thanh khác của các thương hiệu nổi tiếng như Bose, JBL, Sony, Samsung và nhiều hãng khác. Với đội ngũ nhân viên giàu kinh nghiệm và tận tâm, chúng tôi sẽ mang đến cho bạn trải nghiệm mua sắm tuyệt vời và sản phẩm chất lượng.

Hãy ghé thăm NgocKhoaMedia.com để tìm kiếm sản phẩm phù hợp với bạn và trải nghiệm dịch vụ tuyệt vời của chúng tôi!
Announcing the CrUX Site Validator
Tags: webdev, react, webperf, tooling
Published: 2023-03-07 05:11:54

Over the past few years, I have worked closely with various performance tools. One issue I often encounter is whether a website is in the CrUX. To clarify, one can run a PageSpeed Insights report to determine this. However, this can be problematic for workflow reasons when creating strategies for clients.

If a client's website does not meet the eligibility requirements for the CrUX, it becomes challenging to aggregate and visualise data without the help of the CrUX.

## What is the CrUX?
The CrUX or Chrome User Experience Report is the official dataset for Google's Web Vitals program. All data is collected from Google Chrome users worldwide as long as users have opted in.

There are also eligibility requirements for sites that make it into the CrUX, such as traffic volume and other factors.

Tools like Page Speed Insights and Search Console use the CrUX to show your site's performance against real user metrics.

## CrUX Validator
I have developed a straightforward tool that uses the CrUX API to verify if a site is in the CrUX. You will receive an immediate response if the site is not present in the CrUX. However, if it is, the tool includes direct links to the PageSpeed Insights Report and the CrUX Dashboard for that URL.

You can check out the tool here: https://dainemawer.com/tools/crux-checker.
Synchronization, Race Condition, Critical Section
Published: 2023-03-07 05:06:14

##**What happens when two threads access one object?**

**&rarr; Why is synchronization important?**

```
java
Copy code
for(apple for appleBox) {
	if(apple status is bad) {
		badCounter.increment(); 
	}
}

public class Counter {
	private int state = 0;
	public void increment() {state++;}
//1. LOAD state to R1 // Load state into R1
//2. R1 = R1 + 1 // Add 1 to R1 and store the result in R1
//3. STORE R1 to state // Store R1 back into state
	public int get() {return state;}
}
```

Assuming that two threads check for bad apples in one appleBox respectively using this code, if T1 finds 2 bad apples and T2 finds 5 bad apples, the value of memory's state, which is initially 0, is expected to be 7, but that's not always the case.

###**The result can be different depending on when the context switching occurs.**

For example, when T1 loads the state from memory to R1, R1 becomes 0. Then, when T1 stores the result of adding 1 to R1 in R1, R1 becomes 1. If a context switching occurs at this point, T2 executes steps 1 and 2, and stores the value of R1 in memory's state. Then, when context switching occurs again and T1 stores R1 in state, the value remains 1 because T2 already stored it as 1. (It should have been 2 originally.)
&rarr;Race condition


**Race condition**: A situation where the result may vary depending on the timing or access order when multiple processes/threads manipulate the same data.

**Synchronization**: Maintaining the consistency of shared data even when multiple processes/threads are executed simultaneously.

##**How to synchronize?**

**Critical section**: An area that only one process/thread can enter and execute to ensure the consistency of shared data.

```
java
Copy code
do{
	entry section
		critical section
	exit section
		reminder section
} while(TRUE)
```

Conditions for solving the critical section problem

**1. Mutual exclusion**
&rarr; Only one process/thread can execute the critical section at a time.

**2. Progress**
→ If the critical section is empty and multiple processes/threads want to enter the critical section, one of them must be executed.

**3. Bounded waiting**
→ Waiting indefinitely to enter the critical section should not be allowed.

**This posting is just a study note which was written after watching youtube videos in Korean.**

[Youtube Link](https://youtu.be/vp0Gckz3z64)
A walkthrough of a software development process or project
Published: 2023-03-07 05:00:00

A Walkthrough of a Software Development Process: From Idea to Launch

Developing software is a complex and multifaceted process that involves a wide range of activities. In this post, we'll take a high-level look at the software development process, from idea to launch.

Idea generation: The first step in the software development process is generating an idea for a product or feature. This can involve identifying a problem or opportunity and brainstorming potential solutions.

Requirements gathering: Once an idea has been generated, the next step is to gather requirements for the product or feature. This involves working with stakeholders to define the scope and objectives of the project, as well as any constraints or limitations.

Design: After the requirements have been gathered, the next step is to design the product or feature. This may involve creating wireframes, prototypes, or other design artifacts to visualize and test the user experience.

Development: With the design complete, the next step is to start building the product or feature. This involves writing code, integrating with other systems, and testing to ensure that the product is functioning correctly.

Testing: Testing is an important part of the software development process. It helps to ensure that the product or feature is of high quality and meets the specified requirements. There are various types of testing that may be performed, including unit testing, integration testing, and acceptance testing.

Deployment: Once the product or feature is complete and has been tested, the next step is to deploy it to production. This involves releasing the code to a live environment and making it available to users.

Maintenance: After a product or feature has been launched, it's important to continue maintaining it to ensure that it remains stable and reliable. This may involve fixing bugs, adding new features, and making performance improvements.
Conclusion

The software development process is a complex and multifaceted endeavor that involves a wide range of activities. By following a structured process, you can ensure that your product or feature is developed efficiently and effectively, and that it meets the needs of your users.
GO88 – Cổng game bài uy tín GO88 Club – Link tải GO88 cho điện thoại Android Apk/ IOS mới nhất 2022
Published: 2023-03-07 04:05:53

https://go88.band/ Tải bài Go88 nhận ngay 50k chơi game✔️ Go88 là một cái tên nổi tiếng trong lĩnh vực trò chơi cá cược trực tuyến✔️✔️✔️
https://velog.io/@go88band
https://pbase.com/go88band/go88band
https://plaza.rakuten.co.jp/go88band
https://penzu.com/p/6e2eb899
https://matters.news/@go88band
TRUNCATE TABLE Statement
Tags: opengauss
Published: 2023-03-07 03:51:06

The TRUNCATE TABLE statement deletes table data but does not delete the table structure. You can also execute the DROP TABLE statement to delete a table. However, this statement deletes the table structure together with the table. To insert data into the table, you need to recreate the table.

It has the same effect as an unqualified DELETE statement on each table, but it is faster since it does not actually scan the tables. This is most useful on large tables. In addition, the TRUNCATE TABLE statement immediately releases tablespaces without requiring subsequent VACUUM operations.

**Syntax**

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

**Parameter Description**

**· table_name**

Specifies the name (optionally schema-qualified) of the target table.

Value range: an existing table name

**Examples**

Execute the TRUNCATE TABLE statement to delete data from the customer_t1 table.

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

Query the customer_t1 table. The query result is as follows:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3b4x2c7fy3ae7g40df3.png)
Строки и строки байтов в Python
Published: 2023-03-07 03:48:59

Строка - это набор символов, а строка байтов - это именно это и есть - строка байтов. Обычная строка перед тем, как станет возможным сохранить её на компьютере должна быть преобразована (**encoding**) в строку байтов.

Обычные строки - это наборы символов на каком-то человеческом языке, они читаются и понимаются, строки байтов - могут быть представлены в *двоичном* или *шестнадцатеричном* (или каком-то другом) формате и людьми обычно не понимаются.

Тем не менее в *Python* если какой-то переменной присвоить строку байтов **b'string'** и вывести в консоль, то *Python* представит строку байтов как строку доступную для чтения.

```
s=b'string'
print(s)
# Вывод: b'string'
```
Здесь дело в том, что перед выводом на консоль команда **print** преобразовывает строку байтов в формат, удобный для чтения, то есть в обычную строку. На самом деле это будет по-прежнему строка байтов, а не набор символов как каком-то из международных языков. К примеру можно представить набор символов строки **s** в шестнадцатеричном формате
```
c=s.hex()
print(s)
# Вывод: 737472696e67
```
Использован ответ пользователя stackoverflow.com

<https://stackoverflow.com/a/31322359/12613870>
Flutter Infinite Scrolling
Tags: flutter, programming, android, ios
Published: 2023-03-07 03:38:37

## Requisite 
Have you ever use Instagram and/or Facebook application? Especially on your leisure time keep scrolling your timeline or home page seeing what's new and viral while you're laying on your bed.

If you get some "big" data from server and put it into the app, your app will become slow, lagging and near to ANR. You need to separate data response from server into few parts (we can call it "page") and user can get each separated data when click on other page or reach on the bottom of the page. This method is called pagination and infinity scroll. Wonder how to do it in flutter? Let's create this.

## How to do infinite scrolling in flutter

Currently we use `Scroll Controller` in `ListView` to make the list control and get new API request if user reaches the bottom of the list. We also using BLoC for event-state management

**First thing you need to create a project using BLoC. This tutorial refers to [this page](https://dev.to/mikkelofficial7/bloc-flutter-at-its-best-1ice)**

As we said before, we use Scroll Controller to control user behavior in order to scrolling list to the top or bottom.

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

At the `ListView`, we can find a parameter named 'controller' to determine what action when user scrolling to the ListView.

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

We also using flag `_canLoadMore` to define the state when the list can load more data.

```
_scrollController.offset >= _scrollController.position.maxScrollExtent
```

This code block means if user _reaches the bottom_ of the `ListView`, you can hit more data.

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

This code block means a part you want to manipulate when the response successfully loaded. you can add `CircularProgressIndicator` to the bottom of item list every time the data from API is loaded.


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

fully code on [my github](https://github.com/mikkelofficial7/flutter-airline)

Happy Coding :)