teleren/devto huggingface dataset:
How to undo a git pull
Tags: webdev, github, git, tutorial
Published: 2022-09-05 20:09:27

Have you ever been working on a project, ran a `git pull` only to realise you've majorly messed up? Now all your code has been overwritten with whatever was in your remote repository - and sometimes this **isn't** what you want. In times like this, it's easy to panic, but fortunately there are a few ways to revert your code back to its old state and undo the `git pull`.

First things first, make a copy of your project in case you cause things to get worse. Also note that these commands will cause you to lose all uncomitted changes - so a backup can help you save that stuff before you continue. At least then, you'll have the version you currently have. After you've done this backup, you'll want to get a list of all your commit history. You can do this by running `git reflog`:
```shell
git reflog
```

This will generate a list that looks like this:
```shell                                       
648e314 (HEAD -> master, origin/master) HEAD@{0}: commit: Design refresh
b0168ee HEAD@{1}: commit: Minor CSS tweaks
514a02f HEAD@{2}: commit: Fixed extra curly brace
b432ba7 HEAD@{3}: commit: fixed border-radius
a707d13 HEAD@{4}: commit: fixed image border-radius
abf89a3 HEAD@{5}: commit: updated look and feel
```

Select the version you want to revert to. For example, if I wanted to revert to 'Minor CSS tweaks', I'd select the ID `b0168ee`. Next, run the following command to revert your repository to that verson:
```shell
git reset --hard b0168ee
```

This is quite easy, and gives you a lot of control over which version you recover. However, another easier way to do this is to give a time. If you don't want to run `git reflog`, you can run the following command to revert to the version of your repository as it was 30 mins ago, assuming your branch is `master`. **Note**, if you have been working on a specific branch for a long time, this may revert you back quite far. In that case, you might be better using the previous method - but you should be fine if you have a backup. 😄
```shell
git reset --hard master@{"30 minutes ago"}
```
Cansado de conferir o schema.rb
Tags: rails, ruby, braziliandevs
Published: 2022-09-05 20:00:36

---
title: Cansado de conferir o schema.rb
published: true
description: Abro o model. Não lembro os campos que estão por lá. Vamos olhar o schema... Repete (30x). Não mais depois desse post aqui.
tags: rubyonrails, rails, ruby, braziliandevs
canonical_url: https://giovanisleite.dev/cansado-de-conferir-o-schema-rb
---

O Rails nos dá algumas facilidades que parecem mágica. A não-necessidade de importar os módulos que queremos usar, a metaprogramação da linguagem Ruby, os generators presentes no framework... Entre outras. Para mim, o maior contraste com outras linguagens é como fazer muito escrevendo tão pouco quando comparado. E isso tem o seu lado ruim também.

Quando criamos um novo modelo, não precisamos declarar no arquivo ruby (`model.rb`) todos os campos presentes naquele modelo. Geralmente, só mencionamos os campos que precisam de alguma validação ou que estão presentes em algum método para aquele modelo. E toda vez que queremos saber algum campo que não é mencionado: `ctrl + f` no `schema.rb`. O que não é exatamente a forma mais rápida e agradável que gostaríamos, ainda mais quando o campo é mencionado em diferentes tabelas, a tabela é mencionada em outras tabelas, indexes e etc.

Com a `gem` (Annotate)[https://github.com/ctran/annotate_models], podemos facilmente adicionar um comentário ao fim do código no `model.rb` com a estrutura da tabela referente aquele model, no mesmo formato que encontramos no `schema.rb`, algo tipo:

```rb
# == Schema Info
#
# Table name: line_items
#
#  id                  :integer(11)    not null, primary key
#  quantity            :integer(11)    not null
#  product_id          :integer(11)    not null
#  unit_price          :float
#  order_id            :integer(11)
#
```

Maravilha, né?

![Obama dizendo "Special... Beautiful"](https://media.giphy.com/media/XKyP6RJH29cCaD0QpF/giphy.gif)
How to get last element of an array or string using JS ES13 Feature
Tags: javascript, programming, softwaredeveloper, es13
Published: 2022-09-05 19:52:58

---
title: How to get last element of an array or string using JS ES13 Feature
published: true
description:
tags: #js #programming #softwaredeveloper #es13 
# cover_image: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4gj9dmzlqjrmf8fbvep3.png)
# Use a ratio of 100:42 for best results.
---

Javascript ES13 has released in June 2022 and it has pretty cool new features one of them is at() method that can be used with strings and arrays.

So, before ES13 if you want to find the last element of an array or string.

You need to subtract 1 from the length of the array and string and the calculated value will be passed within [] to get the last element like this 👇

![Before ES13](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9oxhgqk2rs4olufa1kw9.png)

But now, after ES13 you can use at() method with negative indexes to get the elements in reverse order of a string or array like this 👇

![After ES13](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36xfqtg68iego2k04ib0.png)

Simple right? 

Thanks for reading this article.

If you find this post helpful

Follow me on [Twitter](https://twitter.com/nandhakumar_dev) and [Instagram](https://www.instagram.com/nandhakumar.dev) to show your support

Cheers ✌️
[Algorithms] 12 - Let's Master Heap
Tags: algorithms
Published: 2022-09-05 19:44:49

## 1. Introduction of Heap

- Definition

  - Heap is a **complete binary tree** that satisfies the heap properties (min or max heap).

  - Max Heap: Every node has greater or equal key(value) to their children.

  - Min Heap: Every node has smaller or equal key(value) to their children.

- Properties

  - Basically heap is an array.

  - Height of any heap will be `log(n)` only.

  - Left child is at `2*i`

  - Right child is at `2*i+1`

  - Parent is at `i/2`


## 2. Insertion (max heap)

- 1) Insert the element to the end of the array.

- 2) Then swap the element with its parent until the parent is greater or equal to the element 

```cpp
void Insert(int arr[], int i){
  while(i > 0 && arr[i/2] < arr[i]){
    
    // Swapping parent and current  
    swap(arr[i/2], arr[i]);
    
    // Move on to the next element
    i = i/2;
  }
}
```

## 3. Deletion (max heap)

- In heap, deletion means deleting the root node.

- 1) Swap the element with the given index with the last element in the heap.

- 2) Delete the current last element.

- 3) Compare swapped element's children. Swap the element with the greater child (only when any of the children are greater or equal to the element).

- 4) Repeat the process until we find the place where both children are smaller than the element.

```cpp
void deleteRoot(int arr[], int& n)
{
    // Get the last element
    int lastElement = arr[n - 1];
 
    // Replace root with last element
    arr[0] = lastElement;
 
    // Decrease size of heap by 1 (element deleted)
    n = n - 1;

    // Start from the bottom
    int i = n;

    // Construct the heap again after the deletion
    while(true){

      // After we proceed the root node, break out of the loop.
      if(i < 0)break;

      // Compare two children and swap
      if(i*2 <= n && arr[i] < arr[i*2]){
        swap(arr[i], arr[i*2]);
      } else if(arr[i] < arr[i*2+1]){
        swap(arr[i], arr[i*2+1]);
      }

      i--;
   }
}
```

## 4. Heap Sort

- Use one of properties of deletion. 

- Every time we delete an element from the heap, we  get an additional empty space at the end of the array.

- We also get the maximum element among the heap. 

- Therefore, if we keep inserting those deleted elements to the end of the array, the array will be eventually sorted.

## 5. Heapify

- Heapify allows you to create a heap within O(N) time complexity. Using insertion method would take O(N*log(N)).

- Heapify starts from the bottom. It repeatedly compares every children of nodes and swap with the parent until it reaches to the root node. 

  - Max heap example: `swap(arr[i], max(arr[2*i], arr[2*i+1]))`

  - Min heap example: `swap(arr[i], min(arr[2*i], arr[2*i+1]))`


## 6. How to use Heap in C++

- `priority_queue<T>` can be used as Max Heap in C++. Max Heap is the default behavior of the library.

  - ex) `priority_queue<T> pq;`

- `priority_queue<T>` can be used as Min Heap in C++. You just need to pass some additional arguments to the constructor.

  - ex) `priority_queue <T, vector<T>, greater<T> > pq;`
Set up Document Intelligence Component in Contextual Sidebar
Tags: servicenow, tokyo
Published: 2022-09-05 19:06:57

!This post was made for the ServiceNow Tokyo Release!

With the Tokyo Release of ServiceNow we got some nice improvements to the Record page. I assume here, that you installed the Document Intelligence component already.

First we need to open UI Builder (UIB) and navigate to the Record page. Then lets go to our tab sidebar component:

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

 and add a new tab.

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

I'm selecting the "start from an empty container".

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

Then creating a tab and selecting an icon.

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

In that newly created tab I can now select a component.

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

Now we need to do some wiring. I created a GraphQL Data Broker to fetch me the the right DI task (di_task). As we have a source_table and source_record field on the di_task table, we can use that to get our di_task.

The Properties of my GraphQL data broker is a filter, so I can set the right filter in the UIB.
```javascript
[{ 
  "name": "filter", 
  "label": "Filter for getting the right docIntel Task", 
  "description": "Query conditions in the 'encoded query' format, for filtering the di_task table", 
  "readOnly": false, 
  "fieldType": "condition_string", 
  "mandatory": false, 
  "defaultValue": "", 
  "typeMetadata": {"table": "di_task"} 
}] 
```
And then a simple query:
```javascript
query ($filter: String){
  GlideRecord_Query {
    di_task(queryConditions: $filter) {
      _results {
        display_name {
          value
        },
         sys_id{
          value
        }
      }
    }
  }
}
```
Lets now wire up the Filter on the UIB and do the data binding. We can also use the props data of the record page in the filter conditions.

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

And the last point is to do the data binding on the component.

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

Thats it, have fun!
Quick WSN: Serve Angular App on Local Network for Responsive Device Previews
Tags: angular, testing, webdev, javascript
Published: 2022-09-05 18:39:21

#### What
Enable a live preview of your Angular application on any device on your local network, including laptops and mobile devices. This works by enabling the typical `:4200` port with your devices' local **_network_ IP address** (not internet).

#### So, what?
Useful for previewing applications on **smaller device screens** for responsive design; and for **debugging inconsistencies** rendered by different browsers on different devices and/or operating systems.

#### Now, what?
1. Get your IP Address
2. Run your app's port on it

---
### Skip to Step
* [Find and Copy **Local IP Address**](#find-and-copy-local-ip-address)
* [**Host Application** on IP Address](#host-application-on-ip-address)
* [**Result**](#result)

---

## Find and Copy Local IP Address
Get your local IP address from the command line
```bash
# for Mac machines connected via ethernet
ipconfig getifaddr en0

# for Mac machines connected via router
ipconfig getifaddr en1

# for Windows machines
ipconfig
```

---

## Host Application on IP Address
```bash
# Command Line
ng serve -o --host 192.16x.x.xx
```
* `-o` opens in browser
* `--host` enables address following flag to act as host [replace `192.16x.x.xx` with address returned from first step's command]

---

# Result
Any device, on the same network (ensure `wifi` is on) can preview application via `http://192.16x.x.xx:4200`
Smallest sum contiguous subarray
Tags: geeksforgeeks, solution, algorithms, kadane
Published: 2022-09-05 18:36:04

### Problem statement
Given an array arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the minimum sum and return its sum.

link to the problem could be found here, https://practice.geeksforgeeks.org/problems/smallest-sum-contiguous-subarray/1

Sample Input and Outputs
> Example 1
```
Input: 
    arr[] = {3,-4, 2,-3,-1, 7,-5}
Output: -6

Explanation: 
sub-array which has smallest 
sum among all the sub-array is {-4,2,-3,-1} = -6
```

> Example 2
```
Input:
    arr[] = {2, 6, 8, 1, 4}
Output: 1
Explanation: 
sub-array which has smallest
sum among all the sub-array is {1} = 1
```

### Expected Time Complexity: O(N)
### Expected Auxiliary Space: O(1)


## Solution 

Here the most simplest and efficient solution is based upon the Kadane’s Algorithm. Which sweeps the iterator (here mentioned as current sum) from element to element, meanwhile after every updated value of the iterator, or current sum, this value is being checked with minimum result sum, if minimum sum get a further minimum value, then the contents are updated, else not. 

Meanwhile if the current sum any where exceeds the 0, then we need to reset the current sum to zero. This means for any value here on it would make sense to ignore the subarray till this point, as if considered would result into few positive numbers, that inturn would oppose the interest of the problem to find minimum number (to which only negative numbers contribute). So avoid taking positive numbers into current sum.

```
class Solution
{
    static int smallestSumSubarray(int a[], int size) {
        int minSum = Integer.MAX_VALUE;
        int curSum = 0;
        for(int i : a) {
            curSum += i;
            minSum = Math.min(minSum, curSum);
            curSum = Math.min(curSum, 0);
        }
        return minSum;
    }
}
```
Angular 2.3 to Angular 14
Published: 2022-09-05 18:33:49

---
title: Angular 2.3 to Angular 14
published: true
description: Need some direction/guidance on how to approach this migration.
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
--- 
## Need some direction/guidance on how to approach this migration.
Planning in Excel with Writeback
Published: 2022-09-05 18:26:30

Check our newest video on how [eMondrian](https://sergeisemenkov.github.io/eMondrian/) can support you to decentralize your planning and forecasting activities for your organization.

{% youtube kmpBqEFKZWA %}

Our example from today is a beverages company which operates in many different regions and has plenty of stores. We are going to quickly show you how you could outsource the initial planning for the sales per product to the store managers.

This video was created by [Leandro Aeschlimann] (https://www.linkedin.com/in/leandro-aeschlimann/). His company [Consenso](https://www.linkedin.com/company/consenso-solutions/) specialises in implementing data analytics tools and data infrastructure.

eMondrian  is a free and open source alternative to Analysis Services from Microsoft which you can install on Linux and Windows.
It allows you to build cubes and consolidate the tables of you underlying data sources to a data model and connect to it from various client tools to visualize & analyse your data in a more user friendly way.
Change Default Port 22 of SSH Server
Published: 2022-09-05 18:20:11

 **Port 22** is used by default to establish an SSH connections. This port is automatically configured during the installation of your operating system.

To reduce the number of brute force attacks, you can change it to a different port for SSH access.

### Changing the Default Port

To change the SSH port:

- Log on to the server as an **root** or an **administrator user**.
- Open the SSH configuration file **sshd\_config** with the text editor **nano** :

```
$ nano /etc/ssh/sshd_config
```

- Search for the entry **Port 22** (could be commented)
- Replace it with the desired value - port between **1024** and **65536**
- Save and Restart the **OpenSSH** service

```
$ service ssh restart

# or 

$ systemctl restart sshd
```
Demystifying Conditional Rendering in ReactJS
Tags: react, javascript, webdev, programming
Published: 2022-09-05 18:11:57

In React, you can create distinct components that can elaborate the desired behavior. You can render only some of them, depending on the state of your application.
**Conditional Rendering** works exactly as it does in JavaScript. Use _Conditional Operators_ to create elements representing the current state, and let React update the UI.
```javascript
function UserGreeting(props) {
     return <h1>Welcome Back!</h1>
}

function GuestGreeting(props) {
     return <h1>Please sign up.</h1>
}
```
Consider these two components

We'll create a Greeting component that will display either of these depending upon the condition.
```javascript
function Greeting(props) {
     const isLoggedIn props.isLoggedIn
     if (isLoggedIn) {
          return <UserGreeting />
     } else {
          return <GuestGreeting />
     }
}

const root = ReactDOM.createRoot(document.getElementById('root'))
// Try changing to isLoggedIn={true}
root.render(<Greeting isLoggedIn={false} />)
```
When _isLoggedIn={false}_, the output will be **_Please sign up._**. 
When _isLoggedIn={true}_, the output will be **_Welcome Back!_**.

You can use variables to store elements. This can help you conditionally render a part of the component without changing the rest of the output. Consider these two components representing Logout & Login buttons.
```javascript
// Login Button
function LoginButton(props) {
     return (
          <button onClick={props.onClick}>
               Login
          </button>
     )
}

// Logout Button
function LogoutButton(props) {
     return (
          <button onClick={props.onClick}>
               Logout
          </button>
     )
}
```

Let's create a component that holds some state, i.e. _stateful component_ and name it **LoginControl**. This will render <LoginButton /> OR <LogoutButton /> depending on it's current state and <Greeting /> from the previous example.

```javascript
class LoginControl extends React.Component {
     constructor(props) {
          super(props)
          this.handleLoginClick = this.handleLoginClick.bind(this)
          this.handleLogoutClick = this.handleLogoutClick.bind(this)
          this.state = {isLoggedIn: false}
     }
     
     handleLoginClick() {
          this.setState({isLoggedIn: true})
     }

     handleLogoutClick() {
          this.setState({isLoggedIn: true})
     }

     root.render(<LoginControl />)

     render() {
          const isLoggedIn = this.state.isLoggedIn
          let button
          if (isLoggedIn) {
               button = <LogoutButton onClick = {this.handleLogoutClick} />
          } else {
               button = <LoginButton onClick = {this.handleLoginClick} />
          }

          return (
               <div> 
                    <Greeting isLoggedIn = {isLoggedIn} />
                    {button}
               </div>
          )
     }
}
```

## Excercise
Run the above code and see what the result is. 
Believe me, you will love it 💖
Placeholder Selectors in SASS
Tags: programming, productivity, webdev, tutorial
Published: 2022-09-05 18:08:58

In SASS a **placeholder** looks and acts a lot like a class selector, only it starts with a `%` and it is not included in the CSS output.

Our `%placeholder` selector contains some width and height declarations:
```js
%placeholder {
    width: 100%;
    height: 100%;
}
body {
    @extend %placeholder;
}
p {
    @extend %placeholder;
}
```
Note that we’ve used the `@extend` directive, which allows one selector to inherit styles of another selector.

This outputs to CSS as follows:
```css
body, p {
    width: 100%;
    height: 100%;
}
```
Simple and as expected!

However, the preprocessor will skip `%placeholder` and it won’t be included in the final CSS file.

## Why Use Placeholders?
Placeholder selectors are mainly useful when writing a SASS library where each style rule is optional.

Typically, when working on your own project, it’s often better to just extend a class selector instead. But it’s good to know, as it could come in quite handy if you start working on larger-scale projects.

In the next article, we’ll learn how to structure our SASS projects.

## Conclusion
If you liked this blog post, follow me on [Twitter](https://twitter.com/RembertDesigns) where I post daily about Tech related things!
![Buy Me A Coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijinng8k7bf23v0o6gkj.png) If you enjoyed this article & would like to leave a tip — click [here](https://www.buymeacoffee.com/rembertdesigns)

### 🌎 Let's Connect

- [Portfolio](https://www.rembertdesigns.co/)

- [Twitter](https://twitter.com/RembertDesigns)

- [LinkedIn](https://www.linkedin.com/in/rrembert/)

- [Hashnode](https://rembertdesigns.hashnode.dev/)

- [Devto](https://dev.to/rembertdesigns)

- [Medium](https://medium.com/@rembertdesigns)

- [Github](https://github.com/rembertdesigns)

- [Codepen](https://codepen.io/rembertdesigns)
massCode v3 - An open source snippets manager is out 🚀
Tags: vue, typescript, opensource, webdev
Published: 2022-09-05 18:03:05

---
title: massCode v3 - An open source snippets manager is out 🚀
published: true
description: massCode - An open source snippets manager for developers
tags: vue, typescript, opensource, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/528xyn15v88li06w6mqb.png
---

## What it is and why

massCode is a snippet manager for developers that helps you conveniently organize pieces of code and have quick access to them. Multilevel folders and tags are used for organization, and each snippet has fragments for even more granular structuring. The app supports Markdown so it can be used as a notebook if needed.

## What's New

### Direct support for TextMate grammars

Now massCode uses Codemirror as the basis for the editor and `.tmLanguage` as the grammar for syntax highlighting. This tandem opens the door to over 600 existing grammars. The application currently supports more than 160 grammars. In addition to `.tmLanguage`, the application supports `.tmTheme` for themes.

### Real-time Render for HTML & CSS

Now you can see the result of HTML & CSS directly in the application. This is such a CodePen on minimal 😀

![Real-time Render for HTML & CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/br9wh6oqt1b8ej2kh4dv.gif)

### Mermaid Diagram

Added support for Mermaid - diagramming and charting tool that renders Markdown-inspired text definitions to create and modify diagrams dynamically.

### Presentation Mode

massCode allows you to make a presentation out of a sequence of snippets. It's great for classroom use, team meetings, conferences or simply reviewing notes on your own.

![Presentation Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zsiok39q9lu2v6kzc9k.gif)

### Screnshots

Create beautiful snippet images on different backgrounds and in different modes.

### Localization

massCode is available in English, Español, Português (Brasil), Русский, 中文 (简体), 中文 (繁體), 中文 (繁體 香港特別行政區) & 日本語 languages.

{% github massCodeIO/massCode %}

Best regards,
Anton