teleren/devto huggingface dataset:
Generic Binary Search in C# .NET
Tags: dotnet, csharp
Published: 2021-08-06 19:36:14

---
title: Generic Binary Search in C# .NET
published: true
date: 2021-08-05 00:00:00 UTC
tags: dotnet, csharp
canonical_url: https://swimburger.net/blog/dotnet/generic-binary-search-in-csharp-dotnet
---

Early this year, I decided to brush up on my algorithms and data structure knowledge. I took these great two courses ([1](https://www.pluralsight.com/courses/algorithms-data-structures-part-one), [2](https://www.pluralsight.com/courses/algorithms-data-structures-part-two)) on PluralSight by Robert Horvick.  
To practice what I learned in this course, I decided to create generic versions of the different algorithms and data structures.

What do I mean by generic versions? These types of courses always use integers or strings to demonstrate the algorithms. Instead of using those primitive data types, I'm reimplementing the algorithms and data structures using C#'s [generic type parameters](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-type-parameters).

Here's a console application with a generic method `BinarySearch` to perform a binary search on an enumerable:

```csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var r = new Random();
        var numbers = Enumerable.Range(0, 1000)
          .Select(x => r.Next(0, 1000))
          .Concat(new int[] {777})
          .Distinct()
          .OrderBy(x => x)
          .ToArray();

        var indexOf777 = Array.IndexOf(numbers, 777);
        Console.WriteLine($"Array.IndexOf: {indexOf777}");
        indexOf777 = BinarySearch(numbers, 777);
        Console.WriteLine($"Binary Search: {indexOf777}");
    }

    private static int BinarySearch<T>(IEnumerable<T> list, T needle) where T : IComparable
    {
        int left = 0;
        int right = list.Count() - 1;

        while (left <= right)
        {
            int median = (left + right) / 2;
            T item = list.ElementAt(median);

            var comparison = needle.CompareTo(item);
            if(comparison == 0)
            {
                return median;
            }

            if (comparison < 0)
            {
                right = median - 1;
            }
            else
            {
                left = median + 1;
            }
        }

        return -1;
    }
}
```

By using a generic type parameter with the constraint that the type has to implement the `IComparable` interface, you can perform the binary search algorithm without knowing the exact type you are working with.

If you want to understand the logic behind the binary search algorithm, I recommend checking out the courses mentioned earlier. There's also a lot of other great resources out there online!

Disclaimer: This code works, but is only developed for the sake of practice. Use at your own risk or just use a sorting library. If you see some room for improvement, there most likely is, I'm all ears~
How to see the current directory the user is currently navigated on the Linux terminal?
Tags: resource
Published: 2021-08-05 00:00:00

---
  title: How to see the current directory the user is currently navigated on the Linux terminal?
  published: true
  tags: Resource
  date: Thu Aug 05 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/see-current-directory-user-navigated-terminal-linux
  cover_image: https://melvingeorge.me/_next/static/images/main-c1c067451d3b8dc3f69dc5b0a1b3c61f.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/see-current-directory-user-navigated-terminal-linux)
  
To see the current directory the user is currently navigated, you can use the `pwd` command (aka present working directory command) on the Linux terminal.

```bash
# See the current working directory
pwd

# OUTPUT
/Users/developer
```

- Using the `pwd` command will show the current working directory the user is currently on the Linux terminal.

See the execution of the above command live in [repl.it](https://replit.com/@melvin2016/see-the-current-working-directory-on-the-linux-terminal#main.sh).

That's all 😃!

### Feel free to share if you found this useful 😃.

---
How to Create Secrets in Python
Tags: python, security, secret
Published: 2021-10-26 11:04:51

---
title: How to Create Secrets in Python
published: true
date: 2021-08-05 00:00:00 UTC
tags: python, security, secret
canonical_url: https://tech.serhatteker.com/post/2021-08/create-secrets/
---

There are a lot methods to generate and manage secrets such as passwords, account credentials, security tokens, and related secrets.

One of them is python's built-in [secrets] module which is used for generating cryptographically strong random numbers suitable for managing secrets.

Let's assume I want to generate a strong password for my user account:

```python
# utils/secrets.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
import secrets

default_char_set = string.ascii_letters + string.digits + string.punctuation


def generate_key(length: int = 32, char_set: str = default_char_set):
    """Generate key from a character set with desired length

    Args:
        length (int): length of the key
        char_set (str): char_set to generate key from
    """
    return "".join(secrets.choice(char_set) for _ in range(length))


if __name__ == "__main__":
    import logging

    logging.basicConfig(level=logging.DEBUG)
    logging.info(generate_key())
```

Where `ascii_*` details are;

```python
In [1]: string.ascii_letters
Out[1]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

In [2]: string.ascii_lowercase
Out[2]: 'abcdefghijklmnopqrstuvwxyz'

In [3]: string.ascii_uppercase
Out[3]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

In [4]: string.punctuation
Out[4]: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

In [5]: string.digits
Out[5]: '0123456789'
```


If I run the module, I would get something like below:

```bash
$ python utils/secrets.py
INFO:root:tGs=d\%Q~Vp^<R_aS*D^0uUemRwX"&G-
```

You can remove `string.punctuation` or provide any subset of characters via
`char_set` *kwarg*.


> As mentioned python's documentation:
> 
> `secrets` should be used instead of default pseudo-random number generator in
the `random` module, which is designed for *modelling and simulation*, **not
security or cryptography**.




All done!




[secrets]: https://docs.python.org/3/library/secrets.html
Push Notification com One Signal
Tags: reactnative, react, mobile
Published: 2021-08-04 23:58:31

![imagem-expo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rknpscl74u0hjghfzc9s.jpg)

 Resolvi escrever esse breve tutorial após me deparar com um certo problema, onde precisava construir uma aplicação em Expo e que tive o Push Notification do One Signal. Procurei por diversos sites e até li na documentação a forma de implementar o One Signal no Expo, mas não estava claro lá. Após diversas pesquisas, eu achei a solução e com isso decidi compartilhar para ficar claro os passos de configuração do OneSignal. 

## Passos para configuração do OneSignal  
1) Inicie um projeto com Expo;
2) Abra a pasta de seu projeto no terminal;
3) Digite o comando "expo eject", esse comando irá criar as pastas para buildar sua aplicação no IOS e Android;
4) Após o procedimento acima, instale o OneSignal em seu projeto, para isso siga as etapas da documentação: https://documentation.onesignal.com/docs/react-native-sdk-setup.

 Feito todos os procedimentos acima, e também os da documentação, seu projeto irá rodar com sucesso. Espero que tenha gostado do post, um grande abraço e até o próximo.
Create a Tilt Hover Effect Card with react-vanilla-tilt & react-parallax-tilt
Tags: react
Published: 2021-08-04 23:19:08

{% twitter 1422949991027548163 %}

This post will explain how to create a card that has tilt hover effect with reactjs and react-vanilla-tilt.

The library this post used is the following.
{% github siddharthkp/react-vanilla-tilt %}

react-vanilla-tilt is based on vanilla-tilt.js.
{% github micku7zu/vanilla-tilt.js/%}

[document]
https://micku7zu.github.io/vanilla-tilt.js/


[myCode]
https://codesandbox.io/s/polished-breeze-rrbsx?file=/src/App.js:1216-1234

The thing is that react-vanilla-tilt is easy to use, but it hasn't been updated more than 3 years. Probably, for many of us, it won't the first choice.

Then I found another similar library, react-parallax-tilt. The way to use the lib is very similar to `react-vanilla-tilt`. The difference would be some `props`.

{% github mkosir/react-parallax-tilt %}

Also, react-parallax-tilt is great because it offers [`Storybook`](https://storybook.js.org/) which is awesome!

https://mkosir.github.io/react-parallax-tilt/?path=/story/react-parallax-tilt--default

Here is the sample code on codesandbox.io
{% twitter 1423059078880825345 %}


[myCode]
https://codesandbox.io/s/happy-moon-fh9gk?file=/src/App.js

I will use react-parallax-tilt to add tilt effect to my website!!!
Quick tip : How to stick your footer down in your page whatever its size?!
Tags: html, css, webdev, beginners
Published: 2021-08-04 22:48:10

`1- in css give the parent class which wrap the whole page lets say container display flex with direction column with min-height 100vh
2- go to footer class for css and give it margin-top auto

#example:

.container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}
.footer{
margin-top: auto;
}

I hope it helps you!!`
Hey, so I created my first React web app!
Tags: react, webdev, showdev
Published: 2021-08-04 22:34:32

## website can be found here:
https://paperworld.netlify.app/
<hr>

![website thumbnail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ngo6wzrzx7mg46mdmq2.png)

<hr>

**Hi!**
 so hello there, good people of the internet, this is my first post here, I created this site for the purpose of learning and trying new technologies, I must say working with Google books API was a little harsh, There are a lot of "holes" in returned data, for example: missing book  thumbnails , no description for some books.

The app probably isn't the best in the world, but I had fun making it, I can't wait to hear what you people think, what is good, and what can be improved!


<hr>
### Stack:
* React
* Axios
* mailgo
* react-query
* react-toastify

website hosted on: Netlify.
Terminal BlackJack!
Published: 2021-08-04 22:32:24

For the final project on Codecademy's CS 101 I had to create a game that ran on terminal. I ended up choosing blackjack because I felt I could easily envision the code I'd have to build. 

The game runs just like a casino game would minus the betting. It starts off by printing welcome messages and then using an input to get your name. After that it randomizes card selections and places them into variables that act as yours and the dealer's hands. Once the hands are created they are printed. Two cards show for you and one for the dealer. After that a series of if statements are used long with inputs to simulate hitting and staying. If you choose to hit, there will be another randomized card pulled from the dealing deck. You'll be asked to hit or stay again immediately after seeing your full hand. If you choose to stay the if statement breaks and your points will be added up and compared with the dealer's. Another series of if statements will be ran to print out the results (if you win, lose, tie, etc.). 

Some special situations that are also ran include: a five card charlie that's inputted as an if check at the end of the hit or stay, going over 21 automatically ends the hit or stay section and tells you you lost, and finally there is an input for an ace choice so you can pick if you want to use it as a 1 or 11 value. 

https://github.com/UglyClancy/Codecademy-101-Final
Day 423 : I see it coming
Tags: hiphop, code, coding, lifelongdev
Published: 2021-08-04 21:37:45

_liner notes_:
- Professional : Not a bad day today. Had a meeting with my manager's manager. haha Really nice guy. Asked if I need anything. Told him I'm pretty low maintenance, haha. I did tell him that when we all meet again for our team outing, I'd like to go to Japan. We'll see. So then I worked on my blog post for the day. Just need to add some screenshots and some code snippets. The text is pretty much done.

- Personal : Last night, I finished watching "Fire Force". I also went through some tracks for this week's radio show. I verified that the fix I made for the Twitter link hashtag bug worked, so we should be good to go next Sunday.

![Looking out into the ocean from a lagoon in Phuket, Thailand with green water surrounded by mountains and a large stone mass sticking up out of the water.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rr4nbmgqlag2ze2ezk4o.jpg)

Going to find a new anime series to watch. Maybe I'll catch up on "Baruto" because I have not watched that in a while. I want to go through some tracks. Maybe look up some articles and stories for the shows. I may even start a new experiment I've been thinking about since everything with https://untilit.works is at a point where it's working good enough for now. I can see it coming in the future where I may need to add more functionality, but till then, I want to work on other projects.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube aikaQwoVUxk %}
Our biggest product release ever - Tabnine for Teams!
Tags: programming, productivity, tooling
Published: 2021-08-04 21:34:11

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

by Dror Weiss, Tabnine's CEO

We are thrilled to announce Tabnine for Teams. This update marks a major milestone on our journey to deliver a top-to-bottom AI-assisted development workflow for individual developers, as well as teams.

The most common reaction we hear from developers using Tabnine is how amazed they are with Tabnine’s ability to learn and adapt to their personal styles and coding patterns.

The second most common reaction we hear is “Can you make Tabnine work for teams?” This has always been the next logical step in Tabnine’s evolution. After all, developers working in a team are using the same project-specific modules, APIs, code patterns, and conventions, so what the AI learns from each one of them is very likely useful for the rest of the team when working in the same context.

Tabnine now helps teams create high-quality software together faster and more consistently. With Tabnine, teams can get code suggestions tuned for their specific project patterns and conventions, thanks to models that adapt to the code that the team members write and the suggestions they accept or reject.

Create your team now, and add teammates at my.tabnine.com

Under the Hood
Tabnine is built from three AI engines working in conjunction to provide the best coding assistant for teams:

* Team Trained AI (Optional – Trained & run locally or on cloud)
Trained on your team’s projects, preferences, and patterns. Every interaction improves AI accuracy.

* Private Codebase Trained AI (Trained & run locally)
Trained privately on your local code. Learns from every line of code you and your team create

* Open-Source Trained AI (Runs locally or on cloud)
Trained on more than 1 billion lines of trusted open-source code with permissive licenses
The Private Codebase Trained AI (available now for all users) and Team Trained AI (gradual rollout) work in conjunction to provide the best team-specific assistance to developers.

Absolute Privacy
Tabnine is designed to serve teams and organizations with strict code confidentiality policies. Tabnine allows every customer to choose whether they want to use our cloud service or run in a completely local setup with self-hosting so that no code leaves your network.

Whether you choose cloud or self-hosted architecture, everything Tabnine learns from you stays completely private and available to your authorized team members only.

We are all incredibly excited about adding team collaboration to our Basic, Pro, and Business Tabnine plans. Team collaboration will continue to be a major focus for us moving forward, so expect to see the product evolve quickly over the next few months. Thanks for joining us on this first step! Now is a great time to get started with Tabnine for Teams.
Pop!_OS - The first week!
Tags: linux
Published: 2021-08-04 21:31:01

Hey everyone.

So, I'm an avid Apple Mac user, and I've used macOS as my primary dev environment for over 10 years.

This has been mostly down to that my employer provided me with a top end Macbook Pro, so I have done everything within the apple ecosystem.

My current employer, the boss was pretty cool, I could set my mac's up how I wanted, have personal emails/icloud on it, use it for personal stuff and side-work (out of work hours ofcourse), So I've had no real reason to switch.

I have just taken a new job, and decided that I want my own machine, keep work and personal stuff separated.

Dell were doing an amazing deal on their outlet website for the XPS range of laptops, and I managed to pickup a brand-new XPS 13 9305 with 16GB Ram, and i7 Quad Core, with 512GB M2 SSD, for £800.

The only problem is that it came with Windows 10 Home edition. I tried to use Windows with WSL2, but felt like it was a fight to get even the basics to work. Windows lasted less than a day on the laptop before I decided to install Linux.

I've used Mint/Ubuntu before, and I know of System76 (who make awesome Linux machines by the way!) System76 also have developed Pop!_OS, a Ubuntu/Debian based OS that is, well, fucking amazing!

It's aimed at developers and is built from the ground up with that in mind. The keyboard shortcuts for multi-tasking is outstanding. I love the tile-view that comes and the global launcher/search makes me feel right at home, just like macOS and its Spotlight.

Now, for installing it on the XPS, it was a simple case of heading over to the Pop!_OS website and grabbing the correct ISO that you need.

I grabbed the 21.04 Non Nvidia version (as my laptop just has the Intel Iris XE graphics). Create a bootable USB and installed it on the XPS.

Aside from turning safe-boot off in the BIOS of the XPS, I did nothing else. Followed the on-screen instructions when installing the OS, I wiped my SSD and only have PopOS! as my main operating system.

Once it was installed, I opened the Pop!_Shop to let it check for updates and install them.

So far, I've been running PopOS! for over a week, and haven't had a single issue.

I have the XPS plugged via USB-C to DisplayPort for a Iiyama 34" Ultrawide running at 144hz, and a Seagate Barracuda Gaming Dock via Thunderbolt (Which has a 4TB Spinning drive and a 512GB M2-SSD inside it) and everything is working perfectly.

I have things like Docker, PHP, Node, Jetbrains (WebStorm, PhpStorm and DataGrip), Visual Studio Code, Mailspring (For emails) and it even plays nicely with my Corsair Virtuso Headset.

I could seriously see Pop!_OS replacing my Mac as a daily driver. 

I've never had such a great experience with a Linux distro before.

You can checkout Pop!_OS here.
[https://pop.system76.com](https://pop.system76.com/)
Mocking function calls with Jest
Tags: javascript, testing
Published: 2021-08-04 21:27:09

Imagine you have an API class, that you use to make all of your api calls with.

```js
class API {
  login(username, password){ /* logic */ }
  logout(){ /* logic */ }
  getCurrentUser(){ /* logic */ }
}
```

When we write automated tests using Jest (https://jestjs.io/) we want to "mock" these calls, since we don't want to be hitting the api each time we run our tests.

Luckily, Jest has this functionality for us, built-in :) 

Let's create our mock function:

```js
function mockLogin(){
  jest.spyOn(API, 'login').mockImplementation(() => {
    return {
      success: true
    }
  }
}
```

Now in our test, we can mock this call before we make it:

```js
it('user can login with correct username and password', () => {
  mockLogin();
  const api = new API();
  const response = api.login('colbygarland', 'hunter12');
  expect(response.success).toBe(true);
});
```

You can rinse and repeat this for any API functions you want to mock - you can decide what data to return back, as if the api was actually sending it back :)
Welcome Thread - v136
Tags: welcome
Published: 2021-08-04 21:17:37

---
title: Welcome Thread - v136
published: true
description: Welcome to DEV! A thread of hellos and intros.
tags: welcome
canonical_url: 
---

![Goat saying "heyyyy" via text message](https://media.giphy.com/media/xT1XGDKwOxacd92rYI/giphy.gif)

### Welcome to DEV!

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself.

2. Reply to someone's comment, either with a question or just a hello. 👋 

**Great to have you in the community!**
Die besten WordPress Security Plugins für mehr Performance
Tags: wordpress, performance, security, wordpressplugins
Published: 2021-08-05 13:02:17

---
title: Die besten WordPress Security Plugins für mehr Performance
published: true
date: 2021-08-04 20:44:51 UTC
tags: WordPress,performance,security,WordPressPlugins
canonical_url: https://bloggerpilot.com/security-plugins/
---

![WordPress Security Plugins](https://bloggerpilot.com/wp-content/uploads/2021/08/security-plugins.png)

Was genau hat die Sicherheit eines Blogs mit seiner WordPress Performance zu tun?

Lies den ganzen Artikel über [WordPress Security Plugins](https://bloggerpilot.com/security-plugins/)
Warum weniger Plugins mehr Performance bedeuten
Tags: wordpress, performance, wordpressplugins
Published: 2021-08-05 13:05:16

---
title: Warum weniger Plugins mehr Performance bedeuten
published: true
date: 2021-08-04 20:24:50 UTC
tags: WordPress,performance,WordPressPlugins
canonical_url: https://bloggerpilot.com/weniger-plugins/
---

![Weniger Plugins mehr Performance](https://bloggerpilot.com/wp-content/uploads/2021/08/weniger-plugins.png)

Die größte Stärke von WordPress ist zugleich auch eine enorme...

[Weniger Plugins mehr Performance](https://bloggerpilot.com/weniger-plugins/)

In den letzten zwei Jahren ist die Anzahl der Plugins, die ich installiert habe, stark angestiegen. Die durchschnittliche Anzahl der Plugins, die ich installiere, liegt zwischen 5 und 10, obwohl ich auch schon mal 15 oder 20 installiert habe. Ich habe nicht wirklich darauf geachtet, wie viele Plugins ich installiert habe, aber ich habe einen Trend festgestellt: Je mehr Plugins ich installiere, desto mehr sinkt die Leistung von WordPress.
Display Formatted Durations in TypeScript 🗓️
Tags: typescript, javascript
Published: 2021-08-04 20:00:21

```typescript
const formattedDuration = (duration: number): string => {
  const sec = duration % 60
  const min = Math.floor(duration / 60)
  return `${min}min${sec > 0 ? ` ${sec}s` : ''}`
}

formattedDuration(600)
//=> "10min"

formattedDuration(640)
//=> "10min 40s"

formattedDuration(6640)
//=> "110min 40s"
```

[▶️ Try it out](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZiATgWwIZSgUwCYBECui6AluDALwwAU2hJ4AXDGPsgEaaICUT0ixYAOYUAfDADeAKBgxQkWBEzAKMWkSikwMAKQwAbAAZps8NBjIBKgLLoAFgDo4AGxBIadDWQD0+g12OImFCEWgAGACTiFmAAvtGRispiBjAA-DChMAlKMRCZTADkBTGhkjGSkggo6Fh4HppUhn6SXl7kYgBEAIwG0R0VVWgYOATqDXoALM2t7TDdvZZTEP2SchAgTpj2LoJUgzUj9eCNk35cQA)