teleren/devto huggingface dataset:
Searching Algorithms in Go
Tags: go, sort, tutorial
Published: 2020-11-11 22:55:51

Hey, Dev.to community!

In this post, I am sharing with you the Go code I've written for some famous searching algorithms.

# Table of Contents

- [Linear Search](#linear-search)
- [Binary Search](#binary-search)
- [Jump Search](#jump-search)

# Linear Search <a name="linear-search"></a>

Linear search is the most basic search algorithm. What you'd do in this algorithm is basically iterate through an array until you find the desired result and return its index.

```go
package main

import "fmt"

func linearSort(arr []int, s int) int {
	for i, v := range arr {
		if s == v {
			return i
		}
	}

	return -1
}

func main() {
	var n = []int{9, 1, 33, 21, 78, 42, 4}

	fmt.Println(linearSort(n, 78)) // 4
}
```

# Binary Search <a name="binary-search"></a>

Binary search is a famous and fast searching algorithm. This algorithm requires you to provide it with an already ascendingly sorted array. This sort basically examines the middle value of the array to find out if it is equal to our target or not. If the middle value is less than the target it means the target is beyond the middle value, and if it is larger it means the target is before the middle value. And the algorithm tends to find the middle value until it matches the target.

To understand this algorithm better you can watch the video below:

{% youtube 6ysjqCUv3K4 %}

```go
package main

import "fmt"

func binarySearch(arr []int, s int) int {
	var leftPointer = 0
	var rightPointer = len(arr) - 1
	for leftPointer <= rightPointer {
		var midPointer = int((leftPointer + rightPointer) / 2)
		var midValue = arr[midPointer]

		if midValue == s {
			return midPointer
		} else if midValue < s {
			leftPointer = midPointer + 1
		} else {
			rightPointer = midPointer - 1
		}
	}

	return -1
}

func main() {
	var n = []int{2, 9, 11, 21, 22, 32, 36, 48, 76}

	fmt.Println(binarySearch(n, 32))
}
```

# Jump Search <a name="jump-search"></a>

Jump search is an algorithm used for sorted arrays. You are going to jump by the square root of the length of the array until you find a value larger than or equal to the target. Then you have to implement a reverse linear search to determine the final result.

To understand this algorithm better you can watch the video below:

{% youtube 63kS6ZkMpkA %}

```go
package main

import (
	"fmt"
	"math"
)

func jumpSearch(arr []int, s int) int {

	var blockSize = int(math.Sqrt(float64(len(arr))))

	var i = 0
	for {

		if arr[i] >= s {
			break
		}

		if i > len(arr) {
			break
		}

		i += blockSize
	}

	for j := i; j > 0; j-- {
		if arr[j] == s {
			return j
		}
	}

	return -1
}

func main() {
	var n = []int{2, 9, 11, 21, 22, 32, 36, 48, 76, 90}

	fmt.Println(jumpSearch(n, 76))
}
```

---
I will complete this list by time.

BTW! Check out my free Node.js Essentials E-book here:

{% link https://dev.to/adnanbabakan/nodejs-essentials-free-e-book-5319 %}
Upload and preview a video using vanilla JavaScript
Tags: javascript, html, filereader
Published: 2020-11-11 22:37:01

I recently googled the title, and found several solutions on how to do it with jQuery, but I was working with Vue and needed a pure JS implementation. [Here's a codepen with the code.](https://codepen.io/tepexic/pen/BazYgJe)

We need an `input` field and a `video` tag in our HTML to begin with, like this:
```html
<input type="file" accept="video/*" id="input-tag"/>
<hr>
<video controls id="video-tag">
  <source id="video-source" src="splashVideo">
  Your browser does not support the video tag.
</video>
```

Now, in the JS, let's get the handles of our HTML elements
```javascript
const videoSrc = document.querySelector("#video-source");
const videoTag = document.querySelector("#video-tag");
const inputTag = document.querySelector("#input-tag");
```

With this ready, we can write the function that will read the video and show it inside the `video` tag, we're using the FileReader API:
```javascript
function readVideo(event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();
    
    reader.onload = function(e) {
      videoSrc.src = e.target.result
      videoTag.load()
    }.bind(this)

    reader.readAsDataURL(event.target.files[0]);
  }
}
```
The trick here consists on reading the selected file as URL. This way, it can be read by the `video` tag. 

When the file has been uploaded (`.onload` event), we simply point the `src` property of the video to the result of the FileReader instance. Then execute the `load()` method from the `video` tag.

That's it. I hope it was helpful. [Here's a codepen with the code again.](https://codepen.io/tepexic/pen/BazYgJe)


Header image by [Kushagra Kevat](https://unsplash.com/@kushagrakevat)
Hacktoberest 11111100100
Tags: hacktoberfest
Published: 2020-11-11 22:21:07

### Background

I am actually a brand new to open source. Though I developed a lot of open-source pet-projects, I have never made any meaningful changes to other OS repos.

### Progress

I have fulfilled all the Hacktoberfest requirements in a while - searching on Github for repos with specific labels helped a lot. It was kind of easy but the greatest thing are the feelings you perceive while contributing to OS.

### Here are my contributions

Even though they are pretty simple this time, the main thing is that I gained some experience in dealing with OS so next time I can do not spend time on this and concentrate more on the content I deliver.
- [SimpleSoftwareIO/simple-qrcode](https://github.com/SimpleSoftwareIO/simple-qrcode/pull/188)
- [bumbummen99/laravel-modelsearch](https://github.com/bumbummen99/laravel-modelsearch/pull/21)
- [openshift/openshift-docs](https://github.com/openshift/openshift-docs/pull/26073)
- [pprathameshmore/QuoteGarden](https://github.com/pprathameshmore/QuoteGarden/pull/22)

### Reflections
This Hacktoberfest was my first one, but definitely not the last! I have gained a lot of confidence and knowledge and the things I made here will not stop - I will continue making some impact to OS community even out of Hacktoberfest timeframe and, IMO, it's one of the most valuable goals of the project.
JSON to python object
Tags: python, json, encoding, decoding
Published: 2020-11-11 22:20:23

---
title: JSON to python object
published: true
description: Different approaches to mapping json to python objects and vice versa
tags: python, json, encoding, decoding
cover_image: https://pythontic.com/json_encoding_python.png
---

This is a very fast how-to encode and decode python objects to json.

* For decoding we will use the parameter object_hook. With it, we can pass a function to the json.loads function.
* For encoding we will use a Custom JSON encoder.

### Mapping incoming object with standard library

```python
import json
my_json_str = '{"name":"John", "age":31, "city":"New York"}'
my_dict_json = json.loads(my_json_str)
print(my_json_str)
# output: {"name":"John", "age":31, "city":"New York"}
```

Now, with a dictionary we have different approaches for making the object mapping

### Mapping approach with dict and constructor´s parameters

```python
class MyObject(object):
    def __init__(self, age:int, city:str, name:str):
        self.name = name
        self.age = age
        self.city = city

    def __repr__(self):
        return f"{self.name} {self.age} {self.city}"

my_obj = json.loads(my_json_str, object_hook=lambda data: MyObject(**data))

print(my_obj)

# output: John 31 New York
```

### Decode class with a Custom encoder

```python
class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if issubclass(type(obj), MyObject):
            return json.dumps(obj.__dict__, default=lambda _: None)
        return json.JSONEncoder.default(self, obj)     

obj_str = json.dumps(my_obj, default=CustomJSONEncoder().default)
print(obj_str)
#output: "{\"name\": \"John\", \"age\": 31, \"city\": \"New York\"}"
```

### Mapping approach with NamedTuple

```python
from typing import NamedTuple

class MyObjectTuple(NamedTuple):
    name:str
    city:str
    age:int

my_obj = json.loads(my_json_str, object_hook=lambda data: MyObjectTuple(**data))

print(my_obj)
# output: MyObjectTuple(name='John', city='New York', age=31)
print((my_obj)._asdict())
# output: {'name': 'John', 'city': 'New York', 'age': 31}
```
### Decode class without custom encoder

```python
obj_str = json.dumps(my_obj._asdict())
print(obj_str)
# output: {"name": "John", "city": "New York", "age": 31}
```

Do you any other method to object decode/encode? Do you think that it can be done better?. Leave your thoughts below, feedback is always welcomed :)
From Medium to Markdown to Dev.to
Published: 2020-11-11 22:06:49

Recently, I've been transferring my Medium posts to DEV.to, mainly for philosophical reasons 😇

One thing I love about Dev.to is that you write in plain markdown. Editing an article is then editing Markdown. Nothing simpler.

### Medium to Markdown
Sadly, Medium doesn't give a simple way to get the markdown of your post.

Luckily `mediumexporter` from [@xdamman](https://github.com/xdamman) is a very useful CLI tool.

You will need [nodejs](https://nodejs.org/) to use it. Nowadays, node comes with `npx`, no need to install `mediumexporter` globally nor set up a local working dir with it.

Simply, download your article with :

```
npx mediumexporter https://medium.com/your-medium-url > your_post.md
```

After executing that command, your Medium post is located in the current directory named `your_post.md`.

### Resources
Photo by [Jake Blucker](https://unsplash.com/@jakeblucker)</a> on [Unsplash](https://unsplash.com/s/photos/transportation)
Participei da Hacktoberfest e plantei uma árvore 🌳
Tags: hacktoberfest
Published: 2020-11-11 22:02:38

Sempre ouvi falar sobre o evento [hacktoberfest](https://hacktoberfest.digitalocean.com), realizado todos os anos pela *Digital Ocean* no mês de outubro, incentivando a contribuição em repositórios *open source*. 

Este ano eu já estava contribuindo com o [repositório de pacotes](https://github.com/microsoft/winget-pkgs) do [Winget](https://github.com/microsoft/winget-cli/releases), que é um gerenciador de pacotes que a Microsoft está criando para o Windows, e eu como um usuário linux 🐧 que convive com Windows diariamente curti demais a ideia. 

Esse ano eu vi que o além da opção de receber uma camisa ao completar o desafio, existia a opção de plantar uma árvore e como o repositório fazia parte não pensei duas vezes, "tô dentro" !!!! 

Consegui completar a quantidade de *commits* necessários pra plantar a árvore, mas acabei conhecendo alguns repositórios que meu deu vontade de ajudar, e que vou ajudar assim que possível.

A experiência foi muito boa, e espero que árvore cresça forte e feliz 😁.

E se você não participou este ano participe da próxima, ou melhor já comece agora, existem muitos projetos bacanas precisado de ajuda e você vai aprender muito.
O que é Audit Log?
Published: 2020-11-11 22:01:12

---
title: O que é Audit Log?
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---

A ideia do Audit Log é que sempre que acontecer algo importante, isso seja registrado, indicando o que aconteceu e quando aconteceu. 

Existe alguns formatos que podem ser  um audit log, como por exemplo;
  * um arquivo
     * Caso use um arquivo precisará de um formato, um formulário ASCII ajuda a tornar mais legível a um ser humano sem software especial.
  * uma tabela de banco de dados
  * Estruturas mais complexas podem ser em formato XML

Os registros são fáceis de escrever, mas difíceis de ler, principalmente quando ficam grande. 
Lembre-se sempre que a data de registro é sempre a data de processamento atual.

A limitação do registro de auditoria é a dificuldade de processar o registro. 
É possível usar o audit log somente em algumas partes do modelo e outros padrões em outros. Sendo assim você pode usar o histórico em tempo real em algumas partes do projeto e outras com propriedade temporal, usando histórico de registro. 


[Resenha do texto de Martin Fowler]( https://martinfowler.com/eaaDev/AuditLog.html)
How to implement a simple countdown timer in JavaScript
Tags: javascript, ecmascript, math, oop
Published: 2020-11-11 21:50:14

---
title: How to implement a simple countdown timer in JavaScript
published: true
description: Want to count down how many days, hours, minutes, and seconds remain until a big event? This is a good vanilla javascript way to do it.
tags: javascript,ecmascript,math,oop
//cover_image: https://direct_url_to_image.jpg
---

This is going to be a pretty quick little post.  I was asked yesterday about how I would implement a countdown timer in just plain vanilla javascript.  Here is my solution ...

{% codepen https://codepen.io/steinbring/pen/BazGYpv %}

You'll see that I am using setInterval() to recreate the countdown object once every 1 second.  Once it is recreated, I am using document.getElementById().innerHTML to refresh the page.

Have any questions, comments, etc?  Feel free to post a comment, below.
Looking for an iOS developer (Any experience level)
Tags: startup, ios
Published: 2020-11-11 21:40:28

Looking to hire or share equity with an iOS developer interested in helping make a live-streaming/social media platform as a part of our startup, Good Vibrations. Contact me at (216) 308-4923 or james.m.rogers@yale.edu if interested. Thanks.


Our movement is rooted in an online platform consisting of hosted gatherings (e.g., worldwide prayers, meditations, debates, etc.), direct connection to services for living a better life, and user content as unbiased and uncensored as possible. It is a place where you can nourish your soul with the growth that comes physically, mentally, and spiritually when someone wants to reach happiness, and others from all walks of life are there to support that journey.

In contrast to current platforms—which in fact are serious perpetrators of unhappiness and derision—Good Vibrations is set up in such a way to prevent echo chambers while still generating communities of like-minded individuals. Perhaps most importantly, the stance of the platform’s content implicitly expected by its users is commitment to what is good. Companies like Facebook, Twitter, and Google could not make such a platform. It is only possible because the managers of Good Vibrations are unconditionally committed to good and respect for the individual.
My #100daysOfCode Challenge - Python 100 projects in 100 days - Journal Entries - Day 2
Tags: beginners, python, 100daysofcode, programming
Published: 2020-11-11 21:32:10

Day two - Tip Calculator

#If the bill was $150.00, split between 5 people, with 12% tip. 
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: You might need to do some research in Google to figure out how to do this.

print("Welcome to the tip Calculator.")

bill = float(input("What is the total bill? $"))

tip = int(input("What percentage tip would you like to give? 10, 12, or 15? "))

people = int(input("How many people to split the bill? "))

payment_per_person = round(float((bill / people ) * (tip / 100 + 1)), 2)

print(f"Each person should pay: ${payment_per_person}")


Output:
Welcome to the tip Calculator.
What is the total bill? $100
What percentage tip would you like to give? 10, 12, or 15? 10
How many people to split the bill? 5
Each person should pay: $22.0

Key Takeaways:
1. Learned about Data types
2. Numbers
3. Operations
4. Type Conversion
5. f-Strings
Your CPAN Dashboard
Tags: perl, cpan, dashboard
Published: 2020-11-11 20:52:23

---
title: Your CPAN Dashboard
published: true
description: 
tags: perl, cpan, dashboard
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/m9tklxpx9vjpnbtq1yk2.png
---

It's only a few days since [I last wrote about my CPAN dashboard project](https://dev.to/davorg/a-cpan-dashboard-i1o), but things have already moved on quite a lot. In the last blog post, I mentioned that I was considering setting up a service making it easy for any CPAN author to have a dashboard like mine. Well, I've now done that.

The site is at [cpandashboard.com](https://cpandashboard.com). And [adding your own dashboard](https://cpandashboard.com/add/) is as simple as sending me a pull request including a JSON file that contains the configuration details for your dashboard.

(Ok, it's not really **quite** that simple - you also need to set up the CI services that you want to use. But let's assume that you want to report on services that you already use :-))

I already have two users - [BDFOY](https://cpandashboard.com/BDFOY/) and [SZABGAB ](https://cpandashboard.com/SZABGAB/). Hopefully, a few more will follow over the next few days.

And the best users are the ones who suggest improvements to the service (and the even better users are the ones who send patches adding the improvements that they want). From ideas and patches from my users, the site now has a few improvements:

* We display the date of the last release to CPAN
* You can sort the list by either the name of the distribution or the date of the last release
* There's a search box that filters the table
* The site no longer shows broken images if you're not using a particular CI service for some of your modules
* You can track multiple Github Actions for each of your modules (this doesn't look quite right yet, but we're working on it)

Oh, and breaking news as I was writing this blog post:

* We now support [Codecov.io](https://codecov.io/) for reporting code coverage as an alternative to [Coveralls.io](https://coveralls.io/)

And I still have more plans. Top of the list is to support more CI systems - CircleCI and Appveyer are definitely on the list, but feel free to tell me about any other systems that might be useful.

Another user has appeared while I've been writing this - [SLU](https://cpandashboard.com/SLU/). Why not add your modules as well?
How to Setup Next.js with Typescript
Tags: react, typescript, nextjs, setup
Published: 2020-11-11 20:35:56

---
title: How to Setup Next.js with Typescript
published: true
description: Next.js with Typescript setup
tags: react, typescript, next, setup
//cover_image: ![NextJs with Typescript](https://dev-to-uploads.s3.amazonaws.com/i/jpikcnvxv0tbokco1ojh.png)
---

I'm a big fan of Typescript and I love to use it with Next.js for any of my React projects no matter how small, I just love it. 

But I find myself googling for setup when I need it, and this has prompted me to write an article about it, I believe writing will also help me understand the setup better and hopefully help you too. 

## Setup
First, let’s make sure that your development environment is ready.
- You’ll need Node.js version 10.13 or later.
To check your Node.js version, simply type `node -v` in your terminal. Or you can download the latest version [here](https://nodejs.org/en).

**P.S**: We will be using `yarn` for this setup.
## Step 1

Run `yarn create next-app`
You will be asked, "What is your project named?" Type in your project name and click enter (i.e. nextjs-typescript-starter).

![Screenshot 2020-11-11 at 18.45.22.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1605116761358/e7jGpo4rF.png)

## Step 2
cd into the directory, for me it is `cd nextjs-typescript-starter` and type `code .` to open the project in vscode.

## Step 3
We need to inform the project that we need typescript, hence we have to create a new file at the **root** of our project. To do that,  type `touch tsconfig.json` and hit enter. 

## Step 4
Install the necessary development dependencies 
`yarn add --dev typescript @types/react @types/node`

## Step 5
Run `yarn dev`

![Screenshot 2020-11-11 at 18.56.37.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1605117429958/ctnGKfOUF.png)

`tsconfig` file is automatically updated and that completes the setup.

## Conclusion 
While I'm still learning how to use Typescript better in React apps, It's a tool I can't do without. 
Thank You for reading.
.NET Interactive lowers the barrier
Tags: notebook, jupyter, dotnet, scripting
Published: 2020-12-09 05:24:05

---
title: .NET Interactive lowers the barrier
published: true
date: 2020-11-11 20:35:52 UTC
tags: notebook,jupyter,dotnet,scripting
canonical_url: 
---

My time learning .NET with C# in the past has mostly dwelled in experimentation by creating sandbox [solutions](https://docs.microsoft.com/en-us/visualstudio/get-started/tutorial-projects-solutions?view=vs-2019). Though it made it easy to scale it was also overkill for Hello World-like projects — the only exception would be ASP.NET. A more ideal way be to use something like Jupyter notebooks, but .NET was not built for that in it’s original incarnation as the .NET Framework.

[Jupyter notebooks](https://jupyter.org/) are an interactive computing environment that enables writing code and presenting it’s output in a document-like format. It enables sharing of research, particularly in the statistics and machine learning fields. Jupyter notebooks were originally designed for Python and were formally known as IPython Notebooks until the project removed that dependency and made the whole system modular and rebranded.

Such a concept requires treating the .NET as a scripting language too when it was meant for developing Windows desktop applications and servers. Scaling it outside of Microsoft’s intended usage proved problematic in the past with platforms like Mono. Mono was incredibly slow and inefficient when it came to embedding because it was not official, at the time, and the Framework was the only source of reference. Sims 3 is an example of this very problem.

![](https://cdn-images-1.medium.com/max/320/1*R7yTBqWSHewPCYGS01E-nQ.png)

But .NET Core challenged this perception. It started off as a slim spin-off of the Framework that is open source, modular and cross-platform. It’s modular design meant it eventually became the replacement as API coverage starting to catch up to the Framework with 3.0. That expanding API coverage allowed for machine learning, microservices, scripting, mobile and game development. It’s slim design meant it was possible to work with ARM at a general purpose level. It’s now been rebranded .NET 5.

The scripting capabilities come from [Try .NET](https://dotnet.microsoft.com/platform/try-dotnet) & [.NET Interactive](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.dotnet-interactive-vscode), respectfully, along with C# 9 introducing top-level coding, removing the need for entry-point method, classes and namespaces. But .NET Interactive is the true winner here in that it brings the platform to Jupyter notebooks natively through VS Code. These “notebooks” lower the barrier of entry in learning the platform by removing the normal Visual Studio from the equation entirely. This is also really useful for machine learning development and research with [ML.NET](https://dotnet.microsoft.com/apps/machinelearning-ai).

It is a great time to be or become a .NET developer.