teleren/devto huggingface dataset:
Profiling a PHP script with XDebug
Tags: php, xdebug, profiling
Published: 2022-06-07 20:01:07

Software profiling is a powerful technique when you want to optimize your code. Among other things, a profile snapshot will show you which parts of your software are the slower.

In this article I will explain how to create a profile snapshot for a PHP script.

## Requirements

I assume you are using _Ubuntu_ and you already have PHP installed. Please also install _XDebug 3_ and _KCachegrind_:

```console
$ apt install php-xdebug
$ apt install kcachegrind
```

## Create profile file

As an example, I will profile tests from [jawira/plantuml-encoding](https://github.com/jawira/plantuml-encoding).

```console
$ git clone https://github.com/jawira/plantuml-encoding.git
$ cd plantuml-encoding
$ php tests/vanilla.php
```

Execute the following command to profile `tests/vanilla.php`:

```console
$  php -dxdebug.mode=profile -dxdebug.output_dir=. tests/vanilla.php
```

After the execution is finished, a new profile snapshot will be created. This profile file has the following name pattern `cachegrind.out.xxxxx` (where `xxxxx` is a number).

![terminal screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vv7jue687nrg0iliv4ks.png)

_XDebug_ can be configured in `php.ini`. Here we have configured _XDebug_ _on-the-fly_ passing `php.ini` configuration through the terminal.

* **-dxdebug.mode=profile**: This option makes `profile mode` enabled for this command.
* **-dxdebug.output_dir=.**: Save profile snapshots in current dir "`.`", otherwise snapshots are saved in `/tmp`.

In our case `profiling mode` is ephemeral, but it can be a problem if you are activating profiling by other means (for example directly editing `php.ini` file). Profile snapshots can take a LOT of disk space, never leave profile mode permanently enabled. 

## Opening profile file

To visualize your profile snapshot, simply open the snapshot (in our case `cachegrind.out.14476`) with _KCachegrind_.

![KCachegrind screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sj19zq92e7yuidjcmr8s.png)

The reading and interpretation of profiling files are beyond the scope of this article, yet I recommend you to see this video <https://www.youtube.com/watch?v=h-0HpCblt3A> presenting KCachegrind.

## Conclusion

Creating a profile snapshot is easy if you understand how to configure _XDebug_ properly. Using `-d` options is very convenient technique to enable profiling from the terminal.

## Resources

- https://xdebug.org/docs/profiler
- http://kcachegrind.github.io/html/Documentation.html
Single Number III
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 20:00:43

Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

**Example 1:**

**Input:** nums = \[1,2,1,3,2,5\]
**Output:** \[3,5\]
**Explanation: ** \[5, 3\] is also a valid answer.

**Example 2:**

**Input:** nums = \[-1,0\]
**Output:** \[-1,0\]

**Example 3:**

**Input:** nums = \[0,1\]
**Output:** \[1,0\]

**Constraints:**

*   `2 <= nums.length <= 3 * 104`
*   `-231 <= nums[i] <= 231 - 1`
*   Each integer in `nums` will appear twice, only two integers will appear once.

**SOLUTION:**

    import bisect
    
    class Solution:
        def singleNumber(self, nums: List[int]) -> List[int]:
            nums.sort()
            op = []
            numset = set(nums)
            for num in numset:
                if bisect.bisect_right(nums, num) == bisect.bisect_left(nums, num) + 1:
                    op.append(num)
            return op
Robo-Promoting Perl
Tags: perl, ai, marketing
Published: 2022-06-07 19:56:50

---
title: Robo-Promoting Perl
published: true
description: Using an AI to write about Perl
tags: perl, ai, marketing
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7pjw6vrho2h9trpy4hug.jpg
# Use a ratio of 100:42 for best results.
---

Last I was fascinated by Simon Willison's article [A Datasette tutorial written by GPT-3](https://simonwillison.net/2022/May/31/a-datasette-tutorial-written-by-gpt-3/). [Datasette](https://datasette.io/) is a project I've been following for a while now. It's tool for exploring data stored in SQLite databases. [GPT-3](https://beta.openai.com/docs/engines/gpt-3) was new to me, but it seems it's an AI for writing articles from simple text prompts. I had a quick look at the web page for it, but couldn't find any obvious way to actually try it out, so I filed it away to investigate further at some point in the future.

But today, I saw another article by Simon called [How to play with the GPT-3 language model](http://simonwillison.net/2022/Jun/5/play-with-gpt3/) which gave basic instructions on getting going on the system. And within a couple of minutes I was ready to go.

I seeded the text input with the phrase "Write an article about why Perl is popular" and pressed the submit button. Here's the text I got back:

> Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular among programmers. Perl is often used for system administration, web development, network programming, and GUI development.

> Perl's popularity can be attributed to its many features, which make it both powerful and easy to use. Perl's syntax is very concise and easy to read, making it a great choice for beginners. Perl also has excellent support for text processing, which is one of its most commonly used applications. Additionally, Perl's extensive library of modules makes it easy to add new functionality to Perl programs.

> Perl is also very portable, meaning it can run on a wide variety of platforms. Perl is available for many operating systems, including Windows, Linux, and Mac OS. This portability makes it a great choice for developing cross-platform applications.

> Overall, Perl's popularity is due to its many features that make it a powerful and easy-to-use programming language. Perl's text processing capabilities, portability, and large module library make it a great choice

And that looks pretty good to me. It simply and effectively ticks all the boxes on my "why I use Perl" list.

Of course, I'm not seriously suggesting that we use AI to write a marketing campaign for Perl. But I do think it's an easy way to get a start on promotional material that you can then clean up yourself.

What do you think? Can you think of a way to use this software?
Pillars of Great Engineering Leadership
Tags: webdev, engineeringleadership, productivity, career
Published: 2022-06-07 19:53:15

The topic of organizational leadership is clearly one that engineering leaders are thinking about. As a former engineering leader myself, I certainly feel the same way! I know it's an area that I felt a lot of pressure in. Every engineering leader feels like they need to do everything and be everywhere. With that pressure, how can we really focus on the areas that will take our engineering organizations from good to great? 

Organization, Velocity, Quality, Outcome, and Impact are five topics that continually come up in my conversations with hundreds of engineering professionals. These, in my opinion, are the foundations of great technical leadership. Learn more about them on [Lohika ReThink Community ](https://community.lohika.com/home/learn)
Set Matrix Zeroes
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 19:00:46

Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.

You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg)

**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg)

**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[0].length`
*   `1 <= m, n <= 200`
*   `-231 <= matrix[i][j] <= 231 - 1`

**Follow up:**

*   A straightforward solution using `O(mn)` space is probably a bad idea.
*   A simple improvement uses `O(m + n)` space, but still not the best solution.
*   Could you devise a constant space solution?

**SOLUTION:**

    class Solution:
        def setZeroes(self, matrix: List[List[int]]) -> None:
            m = len(matrix)
            n = len(matrix[0])
            rows = set()
            cols = set()
            for i in range(m):
                for j in range(n):
                    if matrix[i][j] == 0:
                        rows.add(i)
                        cols.add(j)
            for i in range(m):
                for j in range(n):
                    if i in rows or j in cols:
                        matrix[i][j] = 0
Get the Largest Number
Tags: javascript, challenge
Published: 2022-06-07 19:38:39

For any given array of arrays of numbers, create `largerNumber` function that sums up the content of each sub-array(where possible) and return the larger number.

Here examples of arrays and their results:
```js

largesetNumber([[1, 2], [2, 10], [3, 4]]); //12
largesetNumber([[1, 2, 100,1], [2, 10], [3, 4]]); //104
largesetNumber([[1], [2, 10], [3, 4]]);//12
largesetNumber([[], [2, 10], [3, 4]]);//12
largesetNumber([]);//'empty array'
```
##Assumptions
* items are all numbers or empty arrays

##Knowledge
* how to access a nested array
* how to sum-up its nested items

##Pseudo-code
1. mapping through each nested array
2. sum up each value inside their nested array
3. choose the largest number

##Solution

```js
const largesetNumber = (array) => {
    if(array.length<1){
        return "empty array";
    }
    return Math.max(...array.map(item => item.length? item.reduce((acc, curr) => acc + curr) : 0))
}
```
##Comment(s) (random)
* originally I did not think about a statement to "filter out empty arrays" not empty nested arrays: an if statement and a ternary operator made the job
* initially while the map was looping through the nested loop I would push the result of reduce inside another array, but a more efficient way was found

```js
// const largerNumber = (array) => {
//     if(array.length<1){
//         return "this is an empty array";
//     }

//     const result = [];
//     array.forEach((item, index) => item.length>0 ? result.push(item.reduce((acc, curr)=> acc + curr)): console.log(`Array at position ${index} is empty`))
//     return Math.max(...result)

// }
```
* Math.max does not take an array. It takes a set of parameters. The spread operator provides all of the values of the array as individual parameters.
[](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max)
[](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max)
Delete Node in a Linked List
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 19:30:43

Write a function to **delete a node** in a singly-linked list. You will **not** be given access to the `head` of the list, instead you will be given access to **the node to be deleted** directly.

It is **guaranteed** that the node to be deleted is **not a tail node** in the list.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/01/node1.jpg)

**Input:** head = \[4,5,1,9\], node = 5
**Output:** \[4,1,9\]
**Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/09/01/node2.jpg)

**Input:** head = \[4,5,1,9\], node = 1
**Output:** \[4,5,9\]
**Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

**Constraints:**

*   The number of the nodes in the given list is in the range `[2, 1000]`.
*   `-1000 <= Node.val <= 1000`
*   The value of each node in the list is **unique**.
*   The `node` to be deleted is **in the list** and is **not a tail** node

**SOLUTION:**

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def deleteNode(self, node):
            prev = node
            curr = node
            while curr and curr.next:
                curr.val = curr.next.val
                prev = curr
                curr = curr.next
            prev.next = None
How to Manage Multiple Github Accounts
Tags: github, programming, devops, codenewbie
Published: 2022-06-07 19:04:45

If you work for a company and code on the side you may need to manage multiple Github accounts from the same device. 

Here's how to push from two different Github accounts locally

## Step 1) Create SSH keys

For each SSH key pairs:
`run ssh-keygen -t rsa -b 4096 -C "your_email@example.com"`

You'll be prompted: "Enter a file in which to save the key" so make sure to use a unique name like "company" or "personal".


## Step 2) Add public key to Github

Follow [these steps](https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/).


`Step 3) Create an ssh config file
`
`cd ~/.ssh`
`touch config`

Enter something like this making sure to save after:

```
#personal account
Host github.com-personal
   HostName github.com
   User git
   IdentityFile ~/.ssh/personal
   IdentitiesOnly yes

#user2 account
Host github.com-company
   HostName github.com
   User git
   IdentityFile ~/.ssh/company
   IdentitiesOnly yes
```


## Step 4) Clone Repo

`git clone git@github.com-company:REPOSITORY_NAME.git`


## Step 5) Edit config

You'll need to do this for each repo

Open up local git config using git config --local -e and add:

```
[user]
    name = company
    email = name@company.com
```

type `:wq` and **_enter_** to save and quit

## Step 6) Confirm your remote url
`git remote set-url origin git@github-comcompany:REPOSITORY_NAME.git `


## Step 7) Git add commit and push

Now you can git actions (pull/push/fetch...etc) all you like!

Resources:
https://www.youtube.com/watch?v=R5yS23LKr04
https://gist.github.com/Jonalogy/54091c98946cfe4f8cdab2bea79430f9
Delete and Earn
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 18:30:40

You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:

*   Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.

Return _the **maximum number of points** you can earn by applying the above operation some number of times_.

**Example 1:**

**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.

**Example 2:**

**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.

**Constraints:**

*   `1 <= nums.length <= 2 * 104`
*   `1 <= nums[i] <= 104`

**SOLUTION:**

    from collections import Counter
    
    class Solution:
        def deleteAndEarn(self, nums: List[int]) -> int:
            ctr = Counter(nums)
            prev = curr = 0
            for num in range(10001):
                prev, curr = curr, max(prev + num * ctr[num], curr)
            return curr
Add more languages to your ServiceNow RPA OCR action
Tags: servicenow, rpa, automation
Published: 2022-06-07 18:29:10

ServiceNow's OCR RPA action uses tesseract OCR. As it is open source, we can add more languages. That means you can do following steps to add more languages to your 'OCR Text' Action:

1. Go to the GitHub repo and get the trained data of your desired language --> [https://github.com/tesseract-ocr/tessdata](https://github.com/tesseract-ocr/tessdata)

2. C:\Users\{local.user}\AppData\Local\ServiceNowRPA

3. Open the folder that is named like your instance

4. Find the ID of your bot and open the latest version (mostly 1)

5. Open the folder 'tessdata' and copy your downloaded trained data into it. 

6. Restart the RPA Desktop Design Studio and then you will see the added language in your 'OCR Text' action.
Midnight Fun- Meme on JavaScript splice( ) 😆
Tags: discuss, jokes, javascript
Published: 2022-06-07 18:28:06

splice() method is used on javascript array to remove element. 
The syntax is:
`splice(start_index, delete_count(optional),item(optional))`

One use case I found on twitter 😂

![the image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jd2n35131zdm33p8g2j5.jpg)
The reply I got🤣:

![The Reply](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o194nls9ns83jhugjckx.jpg)

Comment what does it mean and comment your reaction on it!!

Also the splice () method can be used to add, remove, update array elements. To understand it read my tweet 👇
[JavaScript splice() method](https://twitter.com/dev_ash_twiter/status/1526261975088615429?t=FxQsRkYq2xbEwM7c6GeyGQ&s=19)

Thanks...
A Personal .gitignore - Even for a Single Repository
Tags: todayilearned, git
Published: 2022-06-07 18:27:17

I think I might be a bit messy, but maybe so are you? Either way, I quite often find myself with stuff in a repository that I don't want to delete or commit. Then the question becomes, should I add this to the _.gitignore_ file? Quite often I feel like i shouldn't, as no one else working on the project will benefit from it. If everyone is adding their personal stuff to the file, it will get messy quite fast. What I want is a personal .gitignore. Does this exist? You bet it does!

# Solution 1 - Configuring a Global .gitignore
One solution I have seen suggested is to use a global .gitignore. You configure this by setting the path in your global git config like this:
```bash
$ git config --global core.excludesFile ~/.gitignore
```
Here I use a file named _.gitignore_ in my home folder, but this could be any path. 

My main issue with this solution is that this applies to all repositories. This can be useful if you for example always use the same name for your python virtual environments. However, quite often I find myself with some files that are relevant for a single project, making a global solution the wrong choice.

# Solution 2 - Configuring a Local .gitignore
The observant reader might have noticed we used the `--global` flag with the command. May we not just change this to `--local` in the previous command? Yes, yes we can! This allows us to set the configuration for another .gitignore file for the single repository. To not have a naming collision we will need to name it something else, e.g. _.mygitignore_. The command looks like this:
```bash
$ git config --local core.excludesFile .mygitignore
```
This will look for a file named _.mygitignore_ in the current repository. Now you just need to create the file and add what you want to ignore to it. Here I would also suggest adding the .mygitignore file to itself. It will still be used but won't show up when you do e.g. `git status`

**Sidenote:** The local configuration file is stored in the  _.git/config_ in your repository if you ever need to change something.

# Solution 3 - .git/info/exclude
You can also cut the middle man from the previous solution. Git already has a local .gitignore type file inside it that you can use.
This is the file `.git/info/exclude`. It uses the same syntax as your bog-standard .gitignore and is automatically used by .git, no need for any configuration. It doesn't get committed and is specific to the repository.

# Closing Remarks
Of course, you should be careful that this doesn't result in duplicate work for your teammates. If everyone has a _notebooks_ folder or names their virtual environments _.venv_, it is probably better to just add it to the .gitignore. 

I'm torn between the second and third solutions. With the third solution, I like that it's standardized in git and doesn't require configuration. However, it hiding out in the .git folder makes it harder to remember when returning to an old project. In general, I never look in the .git folder unless I have to. So, I will go with the second solution. But, pick your poison as they say.
How to Delete the node modules Folder on Windows
Tags: javascript, programming, webdev, tutorial
Published: 2022-06-07 18:22:16


![NPM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a86lfktnvpb3f3asomb3.png)If you attempt to delete the node_modules folder on Windows, you may have trouble for a variety of reasons. In some cases, for example, the folder nesting within the directory creates folder names that are too long. You might also get the annoying Folder Access Denied message stating, "**You'll need to provide administrator permission to delete this folder**".

 The solution I use is to install **RimRaf** globally with **npm** and then use it to delete the folder. RimRaf is an implementation of the UNIX/LINUX command **rm -rf** for Node, which removes directories and their contents recursively. First, enter this command to install RimRaf from npm:

![npm i rimraf](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odq1pk4uc554podkxeiv.png)

Once it is installed, you can use the following command from within the project directory that contains the **node_modules folder.**

![rimraf node_modules](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nwnqzeme938pal8muwxs.png)That's it! It works and it's easy to remember and execute.
Maximum Length of Pair Chain
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 16:30:41

You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`.

A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion.

Return _the length longest chain which can be formed_.

You do not need to use up all the given intervals. You can select pairs in any order.

**Example 1:**

**Input:** pairs = \[\[1,2\],\[2,3\],\[3,4\]\]
**Output:** 2
**Explanation:** The longest chain is \[1,2\] -> \[3,4\].

**Example 2:**

**Input:** pairs = \[\[1,2\],\[7,8\],\[4,5\]\]
**Output:** 3
**Explanation:** The longest chain is \[1,2\] -> \[4,5\] -> \[7,8\].

**Constraints:**

*   `n == pairs.length`
*   `1 <= n <= 1000`
*   `-1000 <= lefti < righti <= 1000`

**SOLUTION:**

    class Solution:
        def biggestChain(self, pairs, i, n):
            if i == n - 1:
                return 1
            if i in self.cache:
                return self.cache[i]
            mlen = 1
            for j in range(i+1, n):
                if pairs[j][0] > pairs[i][1]:
                    curr = self.biggestChain(pairs, j, n)
                    mlen = max(mlen, 1 + curr)
            self.cache[i] = mlen
            return mlen
        
        def findLongestChain(self, pairs: List[List[int]]) -> int:
            pairs.sort(key = lambda x: x[0])
            self.cache = {}
            n = len(pairs)
            mlen = 1
            for i in range(n):
                curr = self.biggestChain(pairs, i, n)
                mlen = max(mlen, curr)
            return mlen