teleren/devto huggingface dataset:
Javascript: iterating object
Tags: javascript, codenewbie, womenintech
Published: 2020-09-05 16:46:30

Objects in Javascript is similar to dictionary with key value pair value. Within the project development process we need to deal with the iteration of object. Let's look at different ways for iterating.

## for...in 

The traditional *for...in* loop works bit different for objects than arrays. For...in loop enumerates through the object's it's own property.

<code>let person={name:"Ravina", age:25, country:"India"}</code>

<code> for(let data in person){   console.log(`${data}: ${person[data]}`);}</code>

Object class provides other methods that we can use for iterating over an object.

## Object.entries(obj)

Object.entries(obj) return an array of it's own object enumerated string-keyed property [key, value] pair returned in the same way as provided by for...in loop. The order of an array returned by entries() method is same as the object defined.

<code>for(const[key, value] of Object.entries(person)){   console.log(`${key}: ${value}`);}</code>

## Object.keys(obj)

Object.keys(obj) returns an array of an object's own enumerated property and iterated in the same way as that in loop. The array returned by keys is iterated in the same way as given by looping over the properties of an object manually.

<code>for(let key in Object.keys(person)){   console.log(`${key}: ${person[key]}`);}</code>

## Object.values(obj)

Object.values(obj) return an array of object's own enumerated property values and iterated in the same order as that of for...in loop.The array returned by keys is iterated in the same way as given by looping over the property values of an object manually.

<code>for(let value in Object.values(person)){   console.log(`${value}`);}</code>

## When to use what

1. For checking existence of property and requires iterating through property only we can make use of Object.keys(obj) method.

2. For validating property values and requires iterating through property values only we can make use of Object.values(obj) method.

3. For mapping through property and property values we can make use of Object.entries(obj) method.



Happy coding!
Why my tests fail only during pre-commit ?
Tags: python, pytest, precommit, git
Published: 2020-09-05 16:44:18

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z4otbi7ysl1hnbq1sh8c.png)

## Symptom ##

Recently I ran across (what I thought was) strange behaviour.

I use `pre-commit` for all my git commits, and one of the step is to ensure that
all the unit tests pass.

I also have a `make` target to run just the unit tests.

Each time when I tried commit, the unit test step in the `pre-commit`
would fail - which indicates that the unit tests did not pass. But when I run
`make unit` it would pass. 🤷

During the `pre-commit`, pytest would return with `exit code 5` - which
indicates `no tests ran`. So it wasn't that one or more tests failed during
`pre-commit` - but nothing was *tested* - and due to non-zero exit code,
`pre-commit` prevented the commit (as it should)

## Root Cause ##

It turns out `pre-commit` runs all the steps only on the modified files.
It passes the list of modified files to each command - implicitly.
That is, unless you configure it not to. 😀

So when I modify a source file (not a test file) - pytest would "ignore"
the file - since it would not contain any tests.

## Solution ##

Now that we understand the "why" - solution is obvious.

> Patient : Doctor, it hurts when I do *this*
>
> Doctor : Then don't do *that*
> 😂

For the unit test step, ask pre-commit not to pass the file names as an argument
via `pass_filenames: false`

## Reference ##

* [Stackoverflow](https://github.com/pre-commit/pre-commit/issues/1130)

---
Testing Acceptance
Published: 2020-09-05 16:44:08

User acceptance testing, or, as it is also known, end-user testing is one of the key phases of the development and testing life cycle. This functionality testing technique is applied during the final stages of the development before the system is released. The main purpose of the UAT is to get the client’s approval of the created application. As any system is created for customers, their estimation is highly important. In the process of executing acceptance tests, real-world scenarios are simulated in order to confirm that the system meets the testing criteria and therefore can be released to the market. Checking such features as functionality, usability, performance, and UI may be involved as well. Take into consideration, that even though the user acceptance test is carried out right before the production, it is important to have enough time for fixing the detected bugs. This ensures delivering a high-quality and satisfactory application. See the details.
UAT is categorized into several types, including alpha and beta testing, contract, regulation, and operational acceptance testing. The choice of the method depends on your circumstances and goals.
Working with more capable people does not mean that you get stuck
Tags: work, career, motivation
Published: 2020-09-05 16:31:31

---
title: Working with more capable people does not mean that you get stuck
published: true
description: In my career I have been fortunate to work with people much more capable and intelligent than me and the only thing I have received from all of them is knowledge and help.
tags: work, career, motivation
cover_image: https://user-images.githubusercontent.com/751424/92309434-bc1be680-ef62-11ea-8e1e-d67b830acebf.jpg
canonical_url: https://fmontes.com/blog/working-with-more-capable-people-does-not-mean-that-you-get-stuck/
---

This week a friend called me concerned because his company was going to hire a new developer to work on a new project.

They need to make deep changes in the architecture that he has never been able to do because of his daily work and because he has not dedicated himself to researching how to do it.

His concern was because he thinks that this new developer was going to get to work full time on new technology, improve the application and he would be stuck as a developer and would **not allow him to grow and learn new things**.

## Slapping reality into him

1. **You have been in the company for 5 years** and you have never made the required architecture change, you have your reasons but you are already stuck.
2. Your professional stagnation depends only on you and no one else.
3. The new developer is going to need as much from you as you from him and that's what it's all about, giving and receiving knowledge.

## It worked?

The next day my friend sends me a Slack and tells me he wants to show me something. He had set up for the architecture change they need, among other things he told me that it was much easier than he thought and that he saw a lot of benefit.

On the call you could hear in his voice that he was enthusiastic and eager to work on the project, it was like talking to a completely different person.

## The smartest in the room

The worst thing that can happen to you is being the smartest in the room **(or believe you are)** because that does stagnate you, you have no one to learn from and human beings learn from others and create incredible things together.

In my career I have been fortunate to work with people much more capable and intelligent than me and the only thing I have received from all of them is knowledge and help.

> "We are the average of the five people we spend the most time with." - [Jim Rohn](https://www.wikiwand.com/en/Jim_Rohn)
#1 DBMS ( FOR INTERVIEW  PURPOSES)
Tags: database, computerscience, career
Published: 2020-09-05 16:08:44


In this series of blog, we will study all the database management ( DBMS ) topics for interview purposes. this blog gives you only the insights and working explanation of each topic, we will not go in-depth of the topic 

so let's start with #1 Topic 

#1) What is DBMS? How it is Different from Data Structures.

##DBMS

DBMS means Database Management System. DBMS is a software designed to store, retrieve, define, and manage data in a database.

DBMS software mainly works as an interface between the end-user and the database.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8wxktlkan4jlfgsbb1z0.png)

Let see an example of how a company maintains a database. it contains files for employees, clients, products.

The database is organized as these files:- 

1) EMPLOYEE file contains the employee details such as name, designation, salary, etc.

2) CLIENT  file contains the client details such as user details, membership details, etc.

3) PRODUCT file contains the product details such as product price, stock quantity, etc.

- **Types of DBMS**
    1. Hierarchical database systems
    2. Network database systems
    3. Object-oriented database systems
    4. No-SQL or non-relational database systems

---

##DATA STRUCTURES :

Data structures are a way of organizing data in the computer memory in an efficient way by using optimal time and space complexity. using proper data structure will speed up the performance of the software

- **Types of Data structures :**
    - **Linear**

        Array

        Linked list

        Stack

        Queue

    - **Non-linear**

        Tree

        Binary-tree

        Graph

---

##DBMS VS DATA STRUCTURES

- By definition, you can understand DBMS used for storing and accessing data while data structure is used for managing and organizing data in an optimal way

- DBMS stores data in permanent memory. Data structure stores data in temporary memory ( It is alive till the program is alive )

- let's understand by example :
we are running a company and have a list of employees. for storing a list of employees we use DBMS and for searching data of the specific employee, we use a data-structures so that it performs in an optimal way.

thank you for reading : )
My #100DOC - Day 10
Tags: 100daysofcode, challenge, log
Published: 2020-09-05 15:58:14

### Day 10: September 5, 2020

#### **Today's Progress**: 
1. **[Worked on my Addicted Developer Twitter Bot project](https://github.com/pablohs1986/addictedDEV_TwitterBot)** (3h):<br>Reviewing the Heroku log, I realized that my bot had an issue. The methods were not returning a random hashtag/status, something had been misspelled. I went through all the methods and found a way to make everything work. I also added new phrases and hashtags and separated them into separate files to make the code cleaner.
    
#### **What I learned**: 
* How to separate data from code in Node.js.
* That simple things work better.

#### **Total time**:
3h.
Ghost Issues Notifier
Tags: actionshackathon
Published: 2020-09-05 15:42:06

[Instructions]: # (To submit to the GitHub Actions x DEV Hackathon, please fill out all sections.)


### My Workflow
[Note]: # (Make sure to include the name of your GitHub Action and share where it's being used!)

#### Pre-requisites

Create a label in your repo to assign to ghost(pushed back in stack because of unnecessary duplication of issues) issues.

The default label this action uses is **stuck**, but you can use any label.

**NOTE: The label must be setup before using this action**

#### Inputs

✳️ = Required

<table>
  <thead>
    <tr>
      <th width="1%">&nbsp;</th>
      <th width="20%">Input</th>
      <th width="10%">Default</th>
      <th width="69%">Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>✳️</td>
      <td>repo-token</td>
      <td>&nbsp;</td>
      <td>Input for `secrets.GITHUB_TOKEN`.</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>cutoff</td>
      <td>24h</td>
      <td>The cutoff time period before a pull request is considered stuck. The value will be passed to the <a href="https://www.npmjs.com/package/ms">ms</a> package.</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>label</td>
      <td>stuck</td>
      <td>
        Name of the label to assign to ghost issues.<br /><br />
        <strong>The supplied label must already exist. This action will not create a new label.</strong>
      </td>
    </tr>
    <tr>
      <td>✳️</td>
      <td>message</td>
      <td>&nbsp;</td>
      <td>The comment message to post on the issues to notify a user.</td>
    </tr>
    <tr>
      <td>✳️</td>
      <td>search-query</td>
      <td>&nbsp;</td>
      <td>
        Search query to pass to the issue search.<br/><br />
        The value provided will be appended to the base search query, which looks something like this:<br />
        <pre lang="javascript">
        repo:${GITHUB_REPOSITORY} is:issue is:open created:<=${createdSinceCutOff} -label:${stuckLabel}
        </pre>
      </td>
    </tr>
  </tbody>
</table>

### Example workflow

```yaml
name: Ghost Issues
on:
  schedule:
    - cron: '0 * * * *' # Run once per hour
jobs:
  stuck-prs:
    runs-on: ubuntu-latest
    steps:
      - uses: harsh-2711/ghost-issues-notifier-actions@main
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          message: 'Hey @yourUsername, this issue appears to be stuck.'
          search-query: 'author:app/dependabot-preview author:app/dependabot'
```


### Submission Category: 

[Note]: # (Maintainer Must-Haves, DIY Deployments, Interesting IoT, Phone Friendly, or Wacky Wildcards)
Maintainer Must-Haves


### Yaml File or Link to Code

[Note]: # (Our markdown editor supports pretty embeds. Try this syntax: `{% github link_to_your_repo %}` to share a GitHub repository)
[Ghost Issues Notifier](https://github.com/harsh-2711/ghost-issues-notifier-actions)
kotlin learning notes Ⅴ—— kotlin and java
Published: 2020-09-05 15:16:49

#Mutual call between kotlin and Java
If you declare a function in kotlin, how do you call it in Java?
Suppose that in the KotlinDemo.kt file Write a kotlin function in the file:
```
fun getName(name:String):String{

    return name;
}
```
Then, we create a new Java file called javademo. How do we call the function getName in the file KotlinDemo.kt?
```
    public static void main(String[] args){
        KotlinDemoKt.getName("I am xxx");
    }
```
As we can see, we can call this function only by using the file name in kotlin and the function name to be called in the java file. The format is:
<Kotlin file name>. <Function name> to be called
This way you can call the Kotlin function in Java.
#Anonymous Inner Class in kotlin
```
object Test{
    fun sayHello(){
        print("hello!!");
    }
}

```
Using anonymous inner class in kotlin is very simple. You can use type directly. Function name can be used
```
fun getTest(){
    Test.sayHello();
}
```
How to use it in Java? It's also very simple
```
  public static void main(String[] args){
        Test.INSTANCE.sayHello();
    }
```
#static in kotlin
There is no concept of static variables and static methods in kotlin, that is, there is no static keyword in kotlin. So what if we want to have a method similar to public static in Java in kotlin? In fact, this is also very simple. We only need a modifier @ jvmstatic to modify the sayhello function
```
object Test{
    @JvmStatic
    fun sayHello(){
        print("hello!!");
    }
}

```
In this way, sayhello becomes a static method, which can be used directly in Java Test.sayHello () instead of using instance.
Desempenho for – forin – forof JavaScript
Tags: javascript
Published: 2020-09-05 15:05:34

Nesse post vou mostrar através de um exemplo qual laço tem o melhor tempo de execução, só lembrando que o uso de cada um depende da ocasião e a escolha de quando usar nem sempre é baseado no tempo de execução.

1. Para o exemplo:

* Node v12.x
* Visual Studio Code

Vamos a codificação, no terminal execute **mkdir exemplolacos** e depois **cd exemplolacos** e por ultimo **npm init -y** .

No Visual Studio Code crie um arquivo chamado servico.js, para o exemplo vamos consumir uma API o https://swapi.co/ que retorna informações de Star Wars. Para o consumo da API vou usar **axios** https://www.npmjs.com/package/axios

Execute o comando **npm i axios** para adiciona ao **package.json** nas dependências.

O código do **servico.js** é mostrado abaixo:

```javascript
const axios = require('axios');
 
const urlBase = 'https://swapi.co/';
 
async function obterPessoas(nome) {
    const url = `${urlBase}/api/people/?search=${nome}&amp;format=json`;
    const resposta = await axios.get(url);
    return resposta.data;
}
 
module.exports = {
    obterPessoas
}
```

No código importamos o **axios** através do require que usamos para realizar um **get** na **API**, é uma operação bem simples. 
Tive que criar a função assíncrona, pois o retorno do **get** é de forma assíncrona, feito isso exportamos a função **module.exports** para ser usado em outros arquivos.
Agora vamos criar um novo arquivo chamado **lacos.js** no mesmo nível do **servico.js**. 

O código do arquivo **lacos.js** encontra-se abaixo:

```javascript
const servico = require('./servico');
 
async function main() {
    try {
        const resultados = await servico.obterPessoas('a');
 
        const names = [];
        /** 1 - For*/
        console.time('for');
        for (let i = 0; i &lt;= resultados.results.length - 1; i++) {
            const pessoa = resultados.results[i];
            names.push(pessoa.name);
        }
        console.timeEnd('for');
        /** 2 - Forin*/
        console.time('forin');
        for (let i in resultados.results) {
            const pessoa = resultados.results[i];
            names.push(pessoa.name);
        }
        console.timeEnd('forin');
        /** 3 - Forof*/
        console.time('forof');
        for (pessoa of resultados.results) {
            names.push(pessoa.name);
        }
        console.timeEnd('forof');
 
        //imprimir resutados
        console.log('nomes', names);
    } catch (error) {
        console.error('houve erro', error);
    }
}
 
main();
```
No código fiz a divisão para cada for, o resultado dos tempos de execução segue abaixo:

```console
$ node lacos.js 
for: 0.580ms
forin: 0.068ms
forof: 0.423ms
```

Como podemos observar pelo tempos o que teve melhor desempenho foi o **forin**, claro que só essa informação não define qual devemos usar, o uso vai depender de cada caso, a tomada de decisão será definida pela necessidade na hora de desenvolver e da complexidade da lista que estamos manipulando.

O código completo no link: https://github.com/wandealves/exemplolacos
Better debugging with Console Utilities API
Tags: javascript, debugging, console
Published: 2020-09-05 14:52:07

There are some built-in console utilities to improve JavaScript debugging. These utilities make debugging faster. Let's learn about these utilities.

NOTE: All these utility things only work on dev tools console. They will not work in scripts.

The page used is https://example.com

### `$_`
You can use `$_` to get the last evaluated value.

![Usage of `$_`](https://i.imgur.com/VUfrFsy.png)

### `$0`, `$1`, `$2`, `$3` and `$4`
You can use these to reference recently accessed elements in the console. You can access elements using the "Elements" tab. `$0` returns the most recently accessed element, `$1` returns the second most recently accessed variable, the rest of these works in the same way.

#### Example
1. Accessing an element
![Accessing element in Dev tools](https://i.imgur.com/onK5v3Z.png)
2. Referencing the element in the console
![Referencing element in the console](https://i.imgur.com/cSiDReP.png)

### `$()` and `$$()`
You can use these utility functions to find an element in the document. `$()` is basically an alias for `document.querySelector()`, and `$$()` is for `document.querySelectorAll()`.

For both of these function, the first parameter is the selector you want to find, i.e. - `$('.sel')` basically means `document.querySelector('.sel')` and `$$('.sels')` means `document.querySelectorAll('.sels')`.

There is also an optional second parameter, this should be a `Node` or `Element` in which the selector should be searched. Like before, `$('.sel', element)` basically means `element.querySelector('.sel')` and `$$('.sels', element)` means `element.querySelectorAll('.sels')`.

#### Example
##### `$()`
![Usage of `$()`](https://i.imgur.com/gxxVAaH.png)
##### `$$()`
![Usage of `$$()`](https://i.imgur.com/3VXBf48.png)

### `copy()`
You can use this utility function to copy the string representation of any object to the clipboard.

#### Example
![Usage of `copy()` function](https://i.imgur.com/ADKAw71.png)

### `keys()` and `values()`
`keys()` is just an alias for the `Object.keys` method and `values()` is alias for the `Object.values` method.

#### Example
![Usage of `keys()` and `values()`](https://i.imgur.com/zkJHQS8.png)


### Bonus tricks
#### Saving a logged object in the console
![Saving a logged object](https://i.imgur.com/OBRZIYt.gif)

#### Multiline text with `Shift` + `Enter` key combination
![Multiline text example](https://i.imgur.com/tLkWYzn.gif)

<br>
That's all for now. See you next time!
Why wordpress?
Tags: webdev
Published: 2020-09-05 14:51:08

## Why not Wordpress?

Without a doubt the most popular content management system in use today is Wordpress. It is said that 30% of the whole internet is run by WordPress. One of the reasons why WordPress became so popular is that it can be installed by anybody without any technical knowledge in under 5 minutes. Another reason is speed of development. As there is such a vast collection of WordPress Themes available, novice users can define the look & feel of their WordPress website by just choosing any of the free themes offered at wordpress.org. Installing a theme couldn't be easier - just login to your WordPress install, choose a theme, click "activate" - that's it. This is the perfect scenario for web developers looking to make money. It is simple, fast and profitable.

## So why don't you use it?
Wordpress started as a blogging platform and added to and patched so it can power whole websites and even ecommerce sites. This wasn't the initial reason for Wordpress, so if it is used as anything more than a blogging site, the website site will most likely be bloated with unused code, making your site slower.

## Are they all bad ?
No, I'm not saying that all Wordpress sites are slow or bad. If the website creator doesn't use a pre built template or template creator, then it is possible to get a fast site. The fact of the matter is that almost all Wordpress sites are using templates. This is definitely something to be concerned about.

## Why would I worry about this?
Many studies have shown that a website's bounce rate ( the percentage of visitors to a particular website who navigate away from the site after viewing only one page. ) are higher when the site takes longer to load. For users with an average page load time of 2 seconds, the bounce rate is quite low - only 9.61%. This goes up slightly for those with an average page load of 3 seconds, to 13.0%. 4 second page load time having a bounce rate of 17.1%. This raises to 22.1% for a 5 second page load. And if users experience an average page load time of 7 seconds, the bounce rate is 32.3%. This is such an important factor for your website to be successful, and one that should not be ignored. Google also factors your page speed in its search engine rankings, so for great SEO you should be aiming for a blazing fast site.

## So if not Wordpress, then what?
There are loads of other options available. I am an advocate for JAMstack sites. This means that when a change is made using the content management system of choice, this triggers a build and the site is compiled into static files and automatically uploaded. This means faster load times, more security and better search engine optimisation. For basic sites, I really like using a GIT based content management system. For a lot of uses this is sufficient. Any unwanted changes can be restored from the complete history. For more complicated sites, I have used Strapi and really enjoy the flexibility and simple user interface.

Have you used wordpress? Would you recommend it to clients?

[mctweb.co.uk](www.mctweb.co.uk)