teleren/devto huggingface dataset:
TDD x Coding Challenges
Tags: programming, productivity, discuss, watercooler
Published: 2022-02-14 14:36:29

I hate coding challenges. And with that out the way...

I mean, I understand what they bring to the table, depending on where you work it’s definitely a way to train. But most of the time, it’s either a chore you need to learn and train to do or a fun brain teaser you do in your free time.

But someway, somehow for reasons unknown to me... it’s something many hate and yet is the industry standard... want a job in tech? 
Use this terrible online (and not your) IDE everyone will hate to answer the cumulative weight of a watermelon person problem that has 10 million watermelons where its size changes in a Fibonacci pattern.

---

## My challenge (pun intended)

What I wanted: Can you use, explicitly, TDD to solve coding challenges?

What I found: depends. (the default programmer response)

While you can (and should) use TDD even without using TDD. 
(basically, you go through the red-green-refactor cycle, just without writing tests.)

### Why TDD might not the right tool for the job:

- You can end up “wasting” time (especially when it’s a timed challenge) on things that are not important to the test at hand.
    - many challenges say that the input doesn’t need to be validated
    - you already know the minimum/maximum values possible
- You already have test cases.
    - you might not know what they are (and some platforms even hide if you’re passing everything or not... not sure why...) so, do you even need to actually write the tests?
- Many challenges are self-contained.
    - most of what you have to make could be made in a line and not in multiple functions/classes.
    - if you start with a wrong abstraction or data structure, all the buildup you’ve made goes to the “trash”.

### Is it useless then?

I’m not saying you’re not gonna get a solution using TDD, you will. 

Most likely, when you’re totally lost, TDD will help you reach a solution...

It just might not be the “BEST” solution, the solution that will pass all tests (especially the time/space complexity ones).

---

## Now with you!

What is your experience with coding challenges?

Do you have an alternative for solving them?

So far, the best advice I got and that I can give you is the one you’ll probably see in many games out there (with pun intended): “***git gud***”.

---

Cover Photo by [Jukan Tateisi](https://unsplash.com/@tateisimikito?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/challenge?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)

[![buy me a coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7tn3ysg95bjuxaiyzb4.png)](https://buymeacoffee.com/noriller)
Remove Stones to minimize the Total(code and Explanation)
Tags: python, programming, algorithms, leetcode
Published: 2022-02-14 14:32:09

**PROBLEM STATEMENT**
You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:

Choose any piles[i] and remove floor(piles[i] / 2) stones from it.
Notice that you can apply the operation on the same pile more than once.

Return the minimum possible total number of stones remaining after applying the k operations.

floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).
'''
'''
Example 1:

Input: piles = [5,4,9], k = 2
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [5,4,5].
- Apply the operation on pile 0. The resulting piles are [3,4,5].
The total number of stones in [3,4,5] is 12.
Example 2:

Input: piles = [4,3,6,7], k = 3
Output: 12
Explanation: Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [4,3,3,7].
- Apply the operation on pile 3. The resulting piles are [4,3,3,4].
- Apply the operation on pile 0. The resulting piles are [2,3,3,4].
The total number of stones in [2,3,3,4] is 12.

**EXPLANATION**
Everytime you want the maximum value from the pile to be divided.So we will use a maxheap to store the elements in 
greatest to least order and after dividing we push the resultant value again inside the heap
**CODE**

```
from heapq import *
class Solution:
    def minStoneSum(self, piles: List[int], k: int) -> int:
        maxHeap = []
        for i in range(len(piles)):
            heappush(maxHeap, -piles[i])
            
        i = k
        while i > 0:
            temp = heappop(maxHeap)
            x = floor(temp/2)
            heappush(maxHeap,x)
            i -= 1
        return -sum(maxHeap)
```
_Time Complexity_
O(KlogN)
_Space Complexity_
O(N) for storing N elements in heap
Paracetamol.js💊| #54: Explica este código JavaScript
Tags: javascript, beginners, spanish, webdev
Published: 2022-02-14 14:27:46

## **Explica este código JavaScript**

```js
const name = "Lydia"

console.log(name())
```

-     A: `SyntaxError`
-     B: `ReferenceError`
-     C: `TypeError`
-     D: `undefined`

Respuesta en el primer comentario.

---
TIL: GitHub Actions | Fix "Error: Dependencies lock file is not found"
Tags: githubactions, ci, todayilearned
Published: 2022-02-14 14:26:49

## Question

How to fix this error:

```console
Error: Dependencies lock file is not found in /path/to/project. Supported file patterns: package-lock.json,yarn.lock
```

in [`actions/setup-node@v2`](https://github.com/actions/setup-node) GitHub Action?

## Answer

This error occurs because by default, this job searches for `package-lock.json` in the root of the repository for caching. We need to explicitly specify the location of our `package-lock.json`

```diff
             - name: Setup Node.js
               uses: actions/setup-node@v2
               with:
                   node-version: 16.14.0
                   cache: "npm"
+                  # The action defaults to search for the dependency file
+                  # (package-lock.json or yarn.lock) in the repository root, and uses
+                  # its hash as a part of the cache key.
+                  # https://github.com/actions/setup-node#caching-packages-dependencies
+                  cache-dependency-path: "./blog/package-lock.json"
```

## Links

-   https://github.com/actions/setup-node#caching-packages-dependencies
#OpenCV – Detect and blur faces 😁 using DNN in Python 🐍
Tags: englishpost, dnn, facedetection
Published: 2022-02-15 16:18:47

---
title: #OpenCV – Detect and blur faces 😁 using DNN in Python 🐍
published: true
date: 2022-02-14 14:26:26 UTC
tags: EnglishPost,DNN,EnglishPost,FaceDetection
canonical_url: 
---

Hi !

Quick post today: detect a face using a pretrained DNN model and blur the face area. Easy to implement, and also easy to read:

![demo of face blur](https://brunocapuano.files.wordpress.com/2022/02/face-blur-1.gif?w=350)

Code below

{% gist https://gist.github.com/elbruno/2be864075b6c2dbef18e6a68530aa736 %}

That’s it, sample using DNN. Next challenge will be to do this in F#.

#### Face Recognition and Face Detection series in Python

1. [Detecting Faces with 20 lines in Python](https://elbruno.com/2019/05/22/vscode-lets-do-some-facerecognition-with-20-lines-in-python/)
2. [Face Recognition with 20 lines in Python](https://elbruno.com/2019/05/23/vscode-lets-do-some-facerecognition-with-20-lines-in-python-2-n/)
3. [Detecting Facial Features with 20 lines in Python](https://elbruno.com/2019/05/29/vscode-lets-do-some-facerecognition-with-20-lines-in-python-3-n/)
4. [Facial Features and Face Recognition with 20 lines in Python](https://elbruno.com/2019/05/30/vscode-lets-do-some-facerecognition-with-20-lines-in-python-4-n/)
5. [Performance improvements with code](https://elbruno.com/2019/05/31/vscode-lets-do-some-facerecognition-with-20-lines-in-python-5-n/)
6. [Resize the camera input with OpenCV](https://elbruno.com/2019/06/28/vscode-lets-do-some-facerecognition-with-20-lines-in-python-6-n/)
7. [Working with Haar Cascades and OpenCV](https://elbruno.com/?p=31124)
8. [Detect and blur faces 😁 using haar cascades](https://dev.to/azure/opencv-detect-and-blur-faces-using-haar-cascades-56d7)
9. [Detect and blur faces 😁 using DNN](https://elbruno.com/2022/02/14/opencv-detect-and-blur-faces-%f0%9f%98%81-using-dnn/)

[Original Post](https://elbruno.com/2022/02/14/opencv-detect-and-blur-faces-%f0%9f%98%81-using-dnn/)

Happy coding!

Greetings

El Bruno

* * *
NextJS Portfolio Site
Tags: showdev, nextjs, tailwindcss, portfolio
Published: 2022-02-14 14:24:05

Hi All,

After two years I decided it was time to give my personal website an overhaul.

### Stack:
- NextJs
- Sanity CMS
- Tailwind
- Netlify

I've been enjoying working with this stack lately. I was a little apprehensive about Tailwind at first but after working with it recently on a few projects I can safely say that I am a fan. On the previous version of my site I used NetlifyCMS and while I didn't have issues with that SanityCMS has just been a blast to work with. With their robust plugin system, community Slack, and impressive documentation it is currently my go-to CMS.

I plan on writing more about the inner workings of this site in the future but for now take a look and let me know what you think. Any feedback is appreciated :)

[https://johnrock.me/](https://johnrock.me/)
Must Do Interview Questions for Higher Order Functions 
Tags: javascript, higherorderfunct, webdev, programming
Published: 2022-02-14 14:08:39


// 📌Q-1 Get the number of products whose price is atleast 100

const products = [
    { name: "T-Shirt", price: 25 },
    { name: "Headphones", price: 125 },
    { name: "Keyboard", price: 75 },
    { name: "Monitor", price: 200 },
  ];

//   let prouductabove100 =products.map(function(products){
//         return products.price
//   }).filter(function(price){
//       return price>=100
//   }).length

// 👉ans->2  (correct one )

//📌Approach -2

  let productabove100 =products.filter(function(item){
      return item.price>=100
    }).map(function(item){
        return item.name
    }).length
    
    console.log(productabove100);

    //👉 ans -> 2(also correct one 😊)



//📌 Q-2 //Get the movie Names from this Array of Objects
//method and only get the movie name which has rating higher than or equal to 8
// use Filter and map  chaining to achaive the objective


var newReleases = [
    {
           "id": 1,
           "title": "Die Hard",
            "rating":9
           
    },
    {
           "id": 2,
           "title": "Bad Boys",
            "rating":7
           
    },
    {
           "id": 3,
           "title": "The Chamber",
           "rating": 10
           
    },
    
];

// soltion---->
let moviename =newReleases.filter(function(movie){
    return movie.rating>=8
}).map(function(movie){
    return movie.title
})


console.log(moviename);

// 👉ans ->[ 'Die Hard', 'The Chamber' ]


//📌 Q-3

//👉(a)You have to use map function and have to get all the students name in upperCase
//Map Question


//👉(b)Retrieve the details of students who scored more than 50 marks and have id greater than 120 from studentRecord 
//use filter method to approach the problem
let studentRecords = [ {name: 'Abhishek', id: 123, marks : 98 },
          {name: 'Udai', id: 101, marks : 90 },
          {name: 'Himanshu', id: 200, marks : 96 },
          {name: 'Mrinal', id: 115, marks : 75 } ]


//   solution -(a)


let ans1 =studentRecords.map(function(student){
    return student.name.toUpperCase();
})

console.log(ans1);

// 👉ans ->[ 'ABHISHEK', 'UDAI', 'HIMANSHU', 'MRINAL' ]


let ans2=studentRecords.filter(function(stu){
    if(stu.marks>50 && stu.id>120)
    return stu
})

console.log(ans2);

// 👉ans->[
//     { name: 'Abhishek', id: 123, marks: 98 },
//     { name: 'Himanshu', id: 200, marks: 96 }
//   ]


// 📌📌Reduce questions 


// From the transaction array filter out positive Elements and calculate the total amount 
// Use filter and reduce method

const transactions =[1000,3000,4000,2000,-898,3800,-4500];

let ans =transactions.filter(function(transactions){
        return transactions>0
}).reduce(function(answer,value){
    let sum =answer+value
    return sum
},0)

console.log(ans);

// 👉ans ->13800
Reduce Higher Order Functions
Tags: javascript, webdev, programming, beginners
Published: 2022-02-14 14:07:40

**Reduce Higher Order Functions **

Learning with the help of exapmle :-

const arr =[2,3,4,5,6];

// c is a procedural language 
// c++ and java is a object oriented language
// javascript is a functional programming language

//reduce returns only single time after executing the whole program 


let addition =arr.reduce(function(sum,value){
    let updatedsum =sum+value;
    return updatedsum
},0)

console.log(addition);

// 👉ans ->20

let multiplication =arr.reduce(function(product,value){
    let updatedproduct =product*value;
    return updatedproduct
},1)

console.log(multiplication);

// 👉ans->720


//📌📌ReduceRight
// (It is same as reduce , only diffrence is that it runs from right)
let addition1=arr.reduceRight(function(sum,value){
    let updatedsum1=sum+value;
    return updatedsum1
},0)

console.log(addition1);

// ans->20

For hand written notes :
https://github.com/pushanverma/notes/blob/main/webd/Reduce%20.pdf
Contains Duplicate
Published: 2022-02-14 13:55:49

## Instructions
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

### Example 
Input: nums = [1,2,3,1]
Output: true

## Approach
We can [solve this](https://leetcode.com/problems/contains-duplicate) problem using several approaches.

A brute force approach would be to compare each element in the array with other elements to determine if they are the same. 

This approach yields a time complexity of O(n)<sup>2</sup> because we have to go through each element. The space complexity is O(1) because we do not use extra memory.

```python
def contains_duplicate(nums):
    for i in range(0, len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] == nums[j]: return True
    return False
```


However, we can improve this solution by making a trade-off on space complexity.

We can use a set and compare the lengths of the array to determine if there a duplicates. A set contains only unique elements, therefore, if there are duplicates the length of the new array is smaller than the original array.

```python
def containsDuplicate(self, nums):
    new_nums = set(nums)
    if len(new_nums)<len(nums):
       return True
     else:
         return False
```

####One Liner

```python
def containsDuplicate(self, nums):
    return True if len(set(nums))<len(nums) else False
```

This solution has a time complexity of O(n) and space complexity of O(n).

##Approach 2
We can also use a hashmap or hashset and lookup if we have already encountered an element. If we have, we immediately return True because there is a duplicate.

 

```python
def containsDuplicate(self, nums):
        hashset = set()
        for i in nums:
            if i in hashset:
                return True
            else:
                hashset.add(i)
        return False
```
We could also use a hashmap as follows:

```python
def containsDuplicate(self, nums):
        hashmap = {}
        for i in nums:
            if i in hashmap:
                hashmap[i] = hashmap.get(i)+1
            else:
                hashmap[i] = 1
        for k,v in hashmap.items():
            if v > 1: return True
        return False
```
The dictionary has a key-value pair where the element is the key and the value is the number of occurrence of a given element. If an element appears more than once then there is a duplicate and we return True.
This solution also has a time complexity of O(n) and space complexity of O(n).

Happy learning !!!
Introduction To JavaScript
Tags: javascript, beginners, programming, tutorial
Published: 2022-02-14 13:49:36


**Who is this course for? **
This course is for developers of every level, from beginner to advanced, who want to improve their JavaScript skills and get up to date with all the upgrades done to the language specification since 2015

What is Javascript?
Javascript is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. JavaScript was developed by Brendan Eich in 1995.

**What can Javascript do?**

- JavaScript Can Change HTML Content
- Can Change HTML Attribute Values
- Change HTML Styles (CSS)
- JavaScript Can Hide HTML Elements
- Show HTML Elements

**How does JavaScript work?**
JavaScript can be added to a page’s code using <script> tags with the type attribute text/javascript or as a header file with the extension .js. A web browser then downloads and runs the script, changing it into the dynamic objects and effects seen on a screen.
JS framework
ReactJS, Angular, Vue.js and Bootstrap.

**How it is used**

- Build web and mobile applications
- Add interactive elements to a website
- Many developers use JavaScript to make web pages more interactive
- Develop games
- The programming language
- Build efficient IoT systems

**How to Run JavaScript?**
JavaScript cannot run on its own. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it is up to the browser to execute it. 
To start with, you need a text editor to write your code and a browser to display the web pages you develop. You can use a text editor of your choice including Notepad++, Visual Studio Code, Sublime Text, Atom or any other text editor you are comfortable with. You can use any web browser including Google Chrome, Firefox, Microsoft Edge, Internet Explorer

**Main uses are:**

- Client-side validation,
- Dynamic drop-down menus,
- Displaying date and time,
- Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box),
- Displaying clocks etc.

**JavaScript Example**
<script>  
document.write("Hello JavaScript by JavaScript");  
</script> 
 
**Javascript frameworks and libraries available:
**
 Angular
-React
- jQuery
- Vue.js
- Ext.js
- Ember.js
- Meteor
- Mithril
- Node.js
- Polymer
- Aurelia
- Backbone.js
`
Day 15 of 100DaysOfCode
Tags: 100daysofcode, github, python, discord
Published: 2022-02-14 13:35:40

---
title: Day 15 of 100DaysOfCode
published: true
description: Day 15 of 100DaysOfCode
tags: '100daysofcode, github, python, discord'
cover_image: 'https://raw.githubusercontent.com/InvalidLenni/dev.to-posts/main/posts/assets/100-days-of-code.jpg'
canonical_url: null
---


## Day 15 of 100 Days Of Code
_I was too busy for writing a post yesterday._

Here can you find what I learned (& published) yesterday.

## What I published / coded (/ updated) yesterday?
* the day 15 started with improving the linksite issue templates
* edit https://pypi.com/project/simple-amari.py error codes & making the https://pypi.com/project/simple-amari.py v1.0.2-dev draft release
* updating the disweb issue templates from md to yml 
* and ended with the blog post.
Image Processing #3 Statistics
Tags: python, imageprocessing, formyownuse
Published: 2022-02-14 13:31:17

## About this memorandum
Recently, I had a chance to experience deep learning and image/video processing at work, but there were many things I didn't understand about how to touch parameters and amplify data, so I decided to study video processing from scratch.

## Statistics
- Image (pixel value) statistics: used for various image analysis
 - Mean value
 - Median
 - Frequent value
 - Variance
 - Contrast
- Some can be calculated from histograms

The right image shows a white whiteboard with a black metamon on it.
max:1 (white), min:0.0 (black), and we can see that the contrast is 1.0.
There are many ways to calculate contrast.(see code below)

![Summary](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/innv8vktwr4781f8u1ue.png)

Statistics calculation code

```
im_files =[file_path_A, file_path_B, file_path_C]

for file in im_files:
    im = imread(file)[:,:,:3]  # For RGBA, extract only RGB
    im = rgb2gray(im)
    imshow(im)
    plt.show()
    
    print('mean: ', im.mean())
    print('std: ', im.std())
    print('median: ', np.median(im))
    print('max: ', im.max())
    print('min: ', im.min())
    print('contrast1: ', (im.max() - im.min()) / (im.max() + im.min()) ) # Michelson contrast
    print('contrast2: ', im.max() / im.min() if im.min() > 0 else np.nan ) # contrast ratio
    print('contrast3: ', im.max() - im.min() ) # contrast difference
    print()

```

## Calculate the mean and variance

### Unsuggested code 

- Keep the definition formula
- Large computational complexity: 2 double loops
![fomula](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nt43gizghytem6qaixhs.png)
 
```
im = rgb2gray(imread('file_path'))
h, w = im.shape

mean = 0
for y in range(h):
    for x in range(w):
        mean += im[y, x]
mean /= h * w
print('mean: ', mean)

var = 0
for y in range(h):
    for x in range(w):
        var += (im[y, x] - mean)**2
var /= h * w
print('variance: ', var)
print('std: ', np.sqrt(var))
```

### Suggested code
- Transformed formula
- Half the computation: one loop.
![Transformed formula](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rp4k2xq9r7l31ccb7jf6.png)

```
im = rgb2gray(imread('file_path'))
h, w = im.shape

mean = 0
var = 0
for y in range(h):
    for x in range(w):
        mean += im[y, x]
        var  += im[y, x]**2

mean /= h * w
print('mean: ', mean)

var /= h * w
var -= mean**2
print('variance: ', var)
print('std: ', np.sqrt(var))
```
Ionic Mobile App Development Company
Published: 2022-02-14 13:24:50

Ionic is an open-source mobile SDK for developing native and progressive web applications. Progressive web apps are a new way to offer incredible mobile app experiences that are highly optimized, reliable, and accessible completely on the web.

Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores.

So, developing a mobile app with Ionic technologies needs expert developers that are highly skilled and experienced. Now, where can you get such expert developers?

**WebClues Infotech** is an expert web and mobile app development company offering its services to organizations and entrepreneurs around the world. They have a pool of talented 120+ developers who can help you in developing an Ionic mobile app at affordable rates. 

Whether you want to hire a fully remote team or want to add developers to your existing team, they serve Ionic developers for hire in both terms. Their developers deliver high-quality code, 24/7 technical support, and on-time delivery.
 
So, we can conclude that WebClues Infotech is the best Ionic app development company to hire dedicated Ionic developers.
DevHack 3.0
Tags: devfolio, techfest, iitdharwad, devhack
Published: 2022-02-14 13:13:58

DevHack is an acronym that signifies perfection, something that everyone strives for. DevHack 3.0, Parsec 2022's 36-hour long hackathon is your chance to get closer to perfection by designing and building effective prototypes or solutions to the multitude of real-life predicaments. 
You can register as a team of 3-4 for DevHack 3.0 with your Devfolio account on our website. The event will kick off at 8:00 pm on the 4th of March 2022 so register as soon as possible. 
For registration and more information regarding the event, visit our website: 
https://parsec.iitdh.ac.in/hackathon