teleren/devto huggingface dataset:
Convert object of objects to array of objects
Tags: javascript, fundamentals
Published: 2021-07-01 21:15:00

---
title: Convert object of objects to array of objects
published: true
description: Simple explanation how to convert an object of objects into more friendly data structure
tags: 
- javascript
- fundamentals
canonical_url: "https://geodev.me/blog/convert-object-of-objects-to-array-of-objects/"
---

In some scenarios, we need data in a different format than we are given, for example from the API response. This is the situation when data transformation comes to play. In this short post, I'd like to show how to transform an object containing other objects, to a more developer-friendly format, like an array of objects.

## Input data

Let's consider the following data collection.
```javascript
const objectOfObjects = {
  1:
    {
      countryName: "Slovakia",
      hasSeaAccess: false,
      isInEU: true
    },
  2:
    {
        countryName: "Belarus",
        hasSeaAccess: false,
        isInEU: false
    },
  3:
    {
      countryName: "Albania",
      hasSeaAccess: true,
      isInEU: false
    },
  4:
    {
      countryName: "Finland",
      hasSeaAccess: true,
      isInEU: true
    },
}
```
This data structure is something I've seen a few times in my (not too long) career. If we want to loop through such a collection and create some components from it, it's much easier to have an array and iterate over it.
The simplest solution is to use `Object.entries()` method over it to convert this structure to an array.
If we use only this method, that's the result:

```javascript
const objectEntries = Object.entries(objectOfObjects)
// The result
[
  ['1', { countryName: 'Slovakia', hasSeaAccess: false, isInEU: true }],
  ['2', { countryName: 'Belarus', hasSeaAccess: false, isInEU: false }],
  ['3', { countryName: 'Albania', hasSeaAccess: true, isInEU: false }],
  ['4', { countryName: 'Finland', hasSeaAccess: true, isInEU: true }]
]

```
Close enough. To convert it only to an array of objects and keep the id we are given we have to use `Array.map()` over it.

```javascript
const arrayOfObjects = Object.entries(objectOfObjects).map(key => ({ ...key[1]}));
// The result
[
  {
    id: '1',
    countryName: 'Slovakia',
    hasSeaAccess: false,
    isInEU: true
  },
  {
    id: '2',
    countryName: 'Belarus',
    hasSeaAccess: false,
    isInEU: false
  },
  {
    id: '3',
    countryName: 'Albania',
    hasSeaAccess: true,
    isInEU: false
  },
  { 
    id: '4',
    countryName: 'Finland',
    hasSeaAccess: true,
    isInEU: true
  }
]
```

That's the desirable result. If you need this to be working on an older browser, like Internet Explorer 11 you have to use this sophisticated <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#polyfill">polyfill</a> provided by the MDN. Or you can use my solution below.

```javascript
function convertCollection(obj) {
    var keys = Object.keys(obj);
    return keys.map(function(key) {
      return ({ id: key, ...obj[key] })
    })
}
```

This will return the same result as the solution with the `Object.entries()`.
Returning a Sorted Array Without Changing the Original Array
Tags: javascript, devops, beginners, programming
Published: 2021-07-01 21:01:35

 * A side effect of the `sort` method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that `slice` and `concat` return a new array), then run the `sort` method.

* Use the `sort` method in the `nonMutatingSort` function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the `globalArray` variable.
```
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Only change code below this line


  // Only change code above this line
}
nonMutatingSort(globalArray);
```
* Answer:
```
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
let copy = [...arr];
  copy.sort((a, b) => {
     return a - b;
})
     return copy;
}
console.log(nonMutatingSort(globalArray)); will return [2, 3, 5, 6, 9]
```
* OR
```
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  return [].concat(arr).sort(function(a, b) {
    return a - b;
  });
}
nonMutatingSort(globalArray);
```
* Code Explanation:
* First we concatenate the array taken in as a parameter to a new empty array.
* Then Use the `sort()` method create a function to sort the new array in ascending order.

Larson, Quincy, editor. “Return a Sorted Array Without Changing the Original Array.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.
Timestamping in Active Record models
Tags: ruby, rails
Published: 2021-07-01 20:02:34

Recording a timestamp in order to mark that an event occurred to an object is a common practice when dealing with Active Record models. Active Record itself gives us a good example of such an approach. It automatically stores the time when a record was created or updated in the `created_at` and `updated_at` fields.

Similarly, we can create custom timestamp fields by adding `datetime` columns in the database. Yet in order to conveniently manage such fields, we would need to accompany each of them with a bunch of methods in the model class. The more timestamp fields we want to manage, the more methods we need. As a result, the model gets bigger and bigger.

That's where the [`active_record-events`](https://github.com/pienkowb/active_record-events) gem comes into play.

## Using the gem

The gem provides us with the `has_event` macro which adds convenience methods on top of a `datetime` field.

Let's look at the following example. Assume we have a `Task` model with a `completed_at` field. Now, let's add the `has_event` macro inside the model class:

```ruby
class Task < ActiveRecord::Base
  has_event :complete
end
```

As a result, we get plenty of methods for managing the field without the need to define them explicitly.

```ruby
task = Task.create!

task.completed? # => false

task.complete

task.completed? # => true
task.completed_at # => Sun, 20 Dec 2020 16:54:11 UTC +00:00
```

The generated methods allow us to check if a timestamp was recorded (`task.completed?`, `task.not_completed?`), record or overwrite a timestamp (`task.complete`, `task.complete!`), as well as record multiple timestamps at once (`Task.complete_all`).

Additionally, the macro defines two scope methods for retrieving objects with and without a recorded timestamp (`Task.completed`, `Task.not_completed`).

All of this can be achieved at the cost of a simple one-liner.

## Generating a migration

Before we can record a timestamp, we need to add the `completed_at` column to the `tasks` table in our database. In order to do that, we could manually create a migration file, but it's much easier to use a generator provided by the gem:

```
$ rails generate active_record:event task complete
```

This will create a necessary migration and insert a `has_event` statement into the corresponding model class.

```ruby
# db/migrate/XXX_add_completed_at_to_tasks.rb

class AddCompletedAtToTasks < ActiveRecord::Migration[6.0]
  def change
    add_column :tasks, :completed_at, :datetime
  end
end
```

```ruby
# app/models/task.rb

class Task < ActiveRecord::Base
  has_event :complete
end
```

## Alternatives

In more complex scenarios, you might consider using a state machine gem (e.g. `aasm`, `workflow` or `statesman`). Another alternative is `ActiveRecord::Enum`, which offers similar functionality with a different underlying mechanism.

*This article was originally published on Planet Ruby as a part of the Ruby Advent Calendar series.*
🎬How To Make Login & Registration Form | HTML CSS & Vanilla JavaScript✨
Tags: html, css, webdev, javascript
Published: 2021-07-01 20:33:09

Hey Devs, in this episode, you will learn how to make a **Login Form and Registration Form** design using HTML and CSS step by step with a toggle button we will use vanilla JavaScript to switch between login and registration form. 

---

{% youtube FtnCieJKAMQ %}


---
**🏆 Recommended Projects 🏆**
🎬 Neumorphism Login Form | HTML & CSS 
➤https://youtu.be/QWh0S-3D7uY
🎬 Animated Sidebar Menu with HTML & CSS 
➤ Watch: https://youtu.be/QPZrQ_xPVs4 
🎬 Amazing Social Media Buttons Hover Effects | HTML & CSS 
➤ https://youtu.be/P9pi4hq7BBA 
🎬 Animated Login Form | HTML, CSS & JavaScript 
➤ Watch: https://youtu.be/ogNwc45qHKo 
🎬 Slider Sign In / Sign Up Form | HTML CSS Vanilla JS 
➤ Watch: https://youtu.be/Wz5THk0-Y1s 

---

🛴 Follow me on: 
👉https://www.facebook.com/WebdevMadeEasy

---
How to append to the beginning of a list python
Tags: python
Published: 2021-07-01 20:30:30

Append ( )  in python
Anyone who is learning programming will have seen the append function in most of the programs. Most of the students will not know about it and will know more about this function. Append means that we have an element in our list.  The function of the append list is the value that we want to add at the end of the list, so we will use the append function. You must keep in mind that the append function should only be added at the end.  Will never do in the beginning. This means that we can make the list bigger and longer than the end.

There are other similar functions like insert, and extends and add functions, their function is also similar to append function.  Yes, there is only a slight difference. Extend lets the element of one list be added to the element of another list. Sometimes there are multiple elements. And if they have to be added to the list, then I will use the extend method.  Does this by adding one to the end element and having it reprinted. Most use the append function.  When we start programming a list, it is used everywhere.

 The syntax for using it is something like:

 list.append (item).
Adding Prettier to a Project
Tags: javascript, tooling, prettier, productivity
Published: 2021-07-01 20:28:02

While working at a smaller dev shop, our team hit the point at which the inconsistent code formats between and within projects was becoming a pain. Our needs included:

1. A consistent linter/formatter for all projects in a particular language
2. An autoformatter so developers didn't spend time "fixing" linter errors
3. A tool readily available in tools like VS Code which could apply changes on save

We decided to go with [Prettier](https://prettier.io/). We also added a pre-commit hook to ensure that all code changes complied with the new authoritarianism.

I initially published this as a [gist](https://gist.github.com/siakaramalegos/4a5cdab1f44ffb217a48d5260043f8ae) to help when setting up new projects at that company. Today, it was useful for a client I was working with, so I'm sharing it now in an article in case the same use case fits for you, and you'd like a handy reference.

## The Steps

Most of these steps can be found in the [docs](https://prettier.io/docs/en/install.html) and through other links in the docs.

**A key step here is to run Prettier on all the files in a separate commit. You don't want to pollute all your future pull request diffs with formatting changes.**

(1) Install prettier:

```bash
$ npm install --save-dev --save-exact prettier
```

(2) Create an empty config file to let tools know you're using Prettier:

```bash
$ echo {}> .prettierrc.json
```

(3) Create a `.prettierignore` file to let tools know which files NOT to format. `node_modules` are ignored by default. Some suggestions:

```bash
build
coverage
.package-lock.json
*.min.*
```

(4) Manually run Prettier to re-format all the files in the project:

```bash
$ npx prettier --write .
```

(5) Set up your code editor to auto-format on save for ease of use. See [instructions](https://prettier.io/docs/en/editors.html) for various editors.

(6) Set up commit hooks with [pretty-quick](https://github.com/azz/pretty-quick) and [husky](https://github.com/typicode/husky). First, install them as dev dependencies:

```bash
$ npm i --save-dev pretty-quick husky
```

(7) Finally, add the pre-commit instructions to your `package.json` file:

```json
"husky": {
  "hooks": {
    "pre-commit": "pretty-quick --staged"
  }
},
```

Now when you commit your changes, files in the commit will automatically be formatted!

This article was originally published on [sia.codes](https://sia.codes/posts/how-to-add-prettier-to-a-project/). Head over there if you like this post and want to read others like it, or sign up for my [newsletter](https://buttondown.email/sia.codes) to be notified of new posts!
Display your codewars stats on your github profile 👾
Tags: github, opensource, markdown
Published: 2021-07-01 19:59:54

I'm sure you already have an awesome github profile on which you display your stats, languages usage and all that other hot stuff 😎  

If not, defenitly checkout https://github.com/anuraghazra/github-readme-stats

there are many other possibilities 😉 And now there is one more:

If you are a passionet codewars player like me and want to let all your github visitors know that you play a lot, well then I have something for you. I have started a new small project which lets you display a nice codewars card with your stats on your github readme 🚀 

I have just started a few days ago and I am happy to share that it is already possible to use. For sure it is still an early bird but I'll keep enhance it and I am happy to take any feedback or costribution in any way 😊  

You can find it here:
https://github.com/andreasvogt89/codewars_readme_stats

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axtz4r7739v9lcoqwyfz.PNG)

A few weeks ago I added the possibility to add icons of your top trained languages. 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5oz9b1nyp4zswk8wsxvr.png)
TIL how to alter gitlab-ci include-directives
Tags: todayilearned, ansible, gitlab
Published: 2023-05-19 20:38:58

---
title: TIL how to alter gitlab-ci include-directives
published: true
date: 2021-07-01 19:47:00 UTC
tags: TIL,ansible,gitlab
canonical_url: https://www.zufallsheld.de/2021/07/01/til-how-to-alter-gitlab-ci-include-directives/
---

We have a set of common pipeline jobs that are shared among different projects in Gitlab. We include them like this:

```
include:
  - project: 'shared/gitlab/linting'
    ref: master
    file:
      - markdown.yml
      - ansible.yml

```

When you do this, these included jobs get executed with the runner that is defined in the included job. We do want to use a specific project runner though. We normally achieve this by adding a tag to the jobs. But how do you add a tag to a job that you include? The Gitlab community [forums provided the answer](https://forum.gitlab.com/t/using-include-keyword-with-tags/26767/1). You simply add a tag to the job. :)

```
ansible:
  tags:
    - docker

```

This way the job “ansible” that is defined in the included gitlab-ci configuration gets the “docker” tag added.

You can of course not only add tags but other things there, too!
Async lifeCycle hooks may cause props to be undefined 
Tags: vue, javascript
Published: 2021-07-01 19:44:02

## Introduction

Have you ever passed down props from parent to a child component in vue only to realize that the prop isn't yet available but showing `undefined` instead?

Well, one possibility is the presence of async code in lifecycle hooks

## Example

```js
// parent.js
<script>
  import Child from './child'
  export default{
    data() {
      return {
        prop: undefined,
      }
    }
    async created() {
      this.prop = await this.$store.dispatch('getProp')
    }
  }
</script>
<template>
  <Child
    :prop=prop
  />
</template>
```

```js
// child.js
<script>
  export default{
    props: ['prop'],
    created() {
      console.log(this.prop)
    }
  }
</script>
<template>
   ...
</template>
```
When we pass props from parent components to children, props are available by the time the `created` hook runs since the parent `created` hook runs before the child `created` hook. (The opposite for `mounted` hook).

However, in cases like the example above `console.log(this.prop)` will output `undefined` and that is because the lifecycle hooks themselves are synchronous even if they include async code inside of them.

In the example above, the `created` hook in the child component will be called immediately after the `created` hook in the parent component is called. It will not wait for the code inside of it to finish.

In fact, `console.log(this.prop)` might still result in `undefined` even if it is called in `mounted` hook instead. Although, the hooks run in order, the code inside them could finish at a later time.

## Solution 
I have no idea of when the `prop` is available in the child component, so my proposed solution is to `watch` it, and run that watcher only once

```js
 watch: {
  prop(new, old) {
      if (old === undefined && new !== undefined) {
        console.log(this.prop)
      }
    },
  },
```
now, the output would give you the prop.
7 Practice Problems for APEX Triggers
Published: 2021-07-01 19:44:00

<!-- wp:separator -->
<hr class="wp-block-separator"/>
<!-- /wp:separator -->

<!-- wp:paragraph -->
<p>Here is my list of 7 practice problems for Apex Triggers programs that can help any fresher to get started with the salesforce apex triggers. These are classics, popular, and very effective. You can use the developer console to write the triggers. See all solutions and ask if you have any queries.</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">For experienced who are more advanced and reading this, please keep in mind that this is merely for the purpose of learning.</pre>
<!-- /wp:preformatted -->

<!-- wp:separator -->
<hr class="wp-block-separator"/>
<!-- /wp:separator -->

<!-- wp:heading {"textAlign":"center"} -->
<h2 class="has-text-align-center">Problem 1</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Assignment:</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Create Account record whenever new contact is created without an account.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4> Solution : </h4>
<!-- /wp:heading -->

Continue reading :- “ 7 Practice Problems for APEX Triggers ”
https://salesforceforfresher.wordpress.com/2021/06/30/7-practice-problems-for-apex-triggers/
Asynchronous
Tags: beginners, javascript, todayilearned
Published: 2021-07-01 19:40:20

In the middle of learning `setTimeout(), I'm seeing the word *asynchronous* a lot. And Google says that just means

> not existing or happening at the same time

(There's a second definition that's probably even more of a relevant application to coding, but it's a bit *wordy*.)

But, okay, async, not at the same time. So synchronous *is* at the same time.

OMG THAT'S WHY THEY CALL IT BEING IN SYNC.

---

If *NSYNC ever makes a comeback, they can call their album **SYNCHRONOUS**. Here's the concept album art they can have *for free*.

![SYNCHRONOUS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n35ay0un2apx18d6zpli.jpg)
Looking for contributors for my curated list of tech resources 
Tags: webdev, devops, git, bash
Published: 2021-07-01 19:38:09

Hi awesome community, Andou here.

At https://github.com/andou/tech-resources you can find my curated list of useful tech resources for web developers and tech enthusiasts.

I've a strong backend background, so my list is somewhat lack of frontend references and links, as you can see :)

So, please, check out the list, give it a star if you like it and do not hesitate to contribute with a PR. Any help, frontend-wise expecially, would be appreciated!

Enjoy!
Mathematical Programs Salesforce Apex Trigger
Published: 2021-07-01 19:36:57

<!-- wp:paragraph -->
<p>Today we will introduce some common mathematical problems that can be solved using Salesforce Apex Trigger's.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly we have to create an object of name “<strong>&nbsp;MPC__c</strong>“.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":357,"width":781,"height":273,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://salesforceforfresher.files.wordpress.com/2021/06/image-28.png?w=1024" alt="" class="wp-image-357" width="781" height="273"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"textAlign":"center","fontSize":"huge"} -->
<h2 class="has-text-align-center has-huge-font-size">Numbers &amp; Series</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Lets start with some designated number and series to program. Here we shall see how to code to get Armstrong, Prime, Factorial numbers and Fibonacci series.</p>
<!-- /wp:paragraph -->

Continue reading :- “ 7 Practice Problems for APEX Triggers ”
https://salesforceforfresher.wordpress.com/2021/06/13/mathematical-programs-salesforce-apex-trigger/
Salesforce Apex Trigger to Create a Simple Calculator
Published: 2021-07-01 19:33:16

<!-- wp:paragraph -->
<p>In this example, you will learn to create a simple calculator from a apex trigger in salesforce development.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Firstly we have to create an object of name "<strong> Calculater__c</strong>". </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":312,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://salesforceforfresher.files.wordpress.com/2021/06/image-23.png?w=1024" alt="" class="wp-image-312"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>This apex trigger takes an picklist arithmetic operator  " <strong>operator__c </strong>"&nbsp;<code>+, -, *, /</code>&nbsp;and two fields operands " <strong>Value_1__c</strong> " and " <strong>Value_2__c</strong> " from the user. Then, it performs the calculation on the two operands depending upon the operator entered by the user.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":314,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://salesforceforfresher.files.wordpress.com/2021/06/image-24.png?w=1024" alt="" class="wp-image-314"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph {"fontSize":"large"} -->
<p class="has-large-font-size">Code :</p>
<!-- /wp:paragraph -->

Continue reading :- “ Salesforce Apex Trigger Program to Calculate Age from Birth Date in (Day, Month, Year) ”
https://salesforceforfresher.wordpress.com/2021/06/06/salesforce-apex-trigger-to-create-a-simple-calculator/
How to Print Pattern in Apex
Tags: salesforce, apex, programing, codeing
Published: 2021-07-01 19:28:39

<!-- wp:paragraph -->
<p><strong>Apex pattern program</strong>&nbsp;enhances the coding skill, logic, and looping concepts. It is mostly asked in&nbsp;<strong>Salesforce interview</strong>&nbsp;to check the logic and thinking of the programmer. We can print a&nbsp;<strong>Apex pattern program</strong>&nbsp;in different designs. To learn the pattern program, we must have a deep knowledge of the Apex loop, such as&nbsp;<strong>for</strong>&nbsp;loop&nbsp;<strong>do-while</strong>&nbsp;loop. In this section, we will learn&nbsp;<strong>how to print a pattern in Apex</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="f6f4">Pattern Programs in Apex</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Star Patterns </li><li>Numeric Patterns</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p id="ac95">Let’s get started. :-)</p>
<!-- /wp:paragraph -->

Continue reading “ How to Print Pattern in Apex ”
https://salesforceforfresher.wordpress.com/2021/06/03/how-to-print-pattern-in-apex/