teleren/devto huggingface dataset:
Sieve of Eratosthenes
Tags: algorithms, datastructures
Published: 2020-11-07 00:00:00

---
title: "Sieve of Eratosthenes"
date: "2020-11-07T00:00:00.000Z"
tags: ["algorithms", "datastructures"]
---

The [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) is an ancient algorithm for discovering primes in a consecutive sequence of natural numbers. 

Given a consecutive sequence of natural numbers such as:

> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Starting with `2` (`0` and `1` are not prime), eliminate every subsequent second number:

> 2, 3, ~~4~~, 5, ~~6~~, 7, ~~8~~, 9, ~~10~~

Starting with `3`, eliminate every third number:

> 2, 3, ~~4~~, 5, ~~6~~, 7, ~~8~~, ~~9~~, ~~10~~

Repeat the process, each time starting with the next smallest number in the sequence that has not been eliminated. When the limit of the sequence is reached the numbers remaining are the primes.

## An implementation
~~~typescript
// TypeScript
export class SieveOfEratosthenes {
	public static findPrimes(upperBound: number = 2): number[] {
		const sieve = new Array(upperBound + 1).fill(true);

		// 0 and 1 are not prime by definition.
		sieve[0] = false;
		sieve[1] = false;

		for (let i = 2; (i * i) <= upperBound; i++) {
			if (sieve[i] === false) {
				// The number is not a prime, therefore its multiples will also not be primes.
				continue;
			}

			for (let multiplier = 2; (multiplier * i) <= upperBound; multiplier++) {
				// A multiple of a prime is not a prime.
				sieve[multiplier * i] = false;
			}
		}

		const primes: number[] = [];
		for (let i = 2; i < upperBound; i++) {
			if (sieve[i] === true) {
				primes.push(i);
			}
		}

		return primes;
	}
}

// Test
import { SieveOfEratosthenes } from "../sieve-of-eratosthenes";

describe("SieveOfEratosthenes", () => {
	it("is exported", () => {
		expect(SieveOfEratosthenes).toBeDefined();
	});

	describe("findPrimes()", () => {
		it("returns all prime numbers in a given bound set", () => {
			const knownPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47];

			expect(SieveOfEratosthenes.findPrimes(50)).toEqual(knownPrimes);
		});
	});
});
~~~

[Code on Github](https://github.com/dereklawless/algorithms-and-data-structures-katas/tree/master/src/algorithms/prime-numbers)
Onde Instalar Programas no Linux?
Tags: portugues, linux, freebsd
Published: 2020-11-07 01:37:15

# TL:DR

Use o path '/opt'!

# Motivação

Você não quer depender dos repositórios da sua distro ou eles não possuem o programa, ou última versão, que você deseja instalar ou ainda você quer compilar e configurar seu próprio aplicativo.

# Entendendo

Ambos diretórios foram pensados para instalação de programas que não pertencem ao sistema operacional, visto que os apps do sistema ficam em /bin. Entretanto eles não foram planejados para os mesmos tipos de softwares, enquanto o primeiro /usr/local foi concebido para conter compilações feitas pelo administrador(in house software), padrão  FreeBSD, o segundo path é intencionado para pacotes que não fazem parte do SO e de origem de terceiros.

# Saiba Mais

Quer entender as entranhas desse tema? Se ligue nos recursos abaixo:

https://en.wikipedia.org/wiki/UNIX_System_V
https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
https://unix.stackexchange.com/questions/11544/what-is-the-difference-between-opt-and-usr-local      
https://www.freebsd.org/cgi/man.cgi?query=hier&sektion=7&manpath=freebsd-release-ports
WHO AM I?
Tags: testing, java, csharp, welcome
Published: 2020-11-07 00:51:17

Nice to meet you!

This is the first article that was written by myself. 
The article just mentions some information about my purpose.

I write my blog to share my knowledge of automation testing.
I will describe all my work experience and review experiments on testing tools, frameworks, and libraries with many different programming languages. Currently, Java and Csharp is will be focused on the blog. Then, I will vary the programming languages on it with Python, the most popular programming language, and javascript.

Please send me an email to "w33haaproo@gmail.com" to ask any questions about automation testing such as issues, reviewing for new tools.

Thanks,
W33
React Drawer like a Champ!
Tags: react, drawer, coding
Published: 2020-11-07 00:26:24

Hi there!!! Hope everything goes fine with you on the other side of the screen wherever you are!

I just found out today about this amazing app for VSCode (Thanks to Cody, the master of Tests!), CodeSpan, and man! I can't hold myself so I decided to write an article with some cool screenshots taken with this app, and what a better example to show than a drawer that I'm building from scratch for the latest component library I'm building!

##Here we go... 
Oh, wait I'm using TS and styled-system to build this out so "Box" component may look a little weird, if I don't, let you know about this. Now ... here we go ...

React Component!

![code1](https://dev-to-uploads.s3.amazonaws.com/i/kx82tnd4uerazu1ifkrk.png) 
 
So nothing fancy here, just a Box component with some props, typed by this interface right here

![code12png](https://dev-to-uploads.s3.amazonaws.com/i/h0ommkqsmh4h06q04cxr.png)
  
What is missing? The direction and that is where the magic is ...

![code5png](https://dev-to-uploads.s3.amazonaws.com/i/tkhj0ip38cngm96ahn5y.png)
 

So with the helper from above you and based on the isOpen prop you can translate your drawer from the selected direction using the direction props spreading the helper in the component style like this ...

![code4png](https://dev-to-uploads.s3.amazonaws.com/i/e2zyfb1zwceoc1i19uv3.png)
 
So that's it ... Or since I've always hated those dev who share only images... here is your code!

##Component

```javascript
import React from 'react'
import { Box } from '../../structural'
import { directions } from './directions'

export default function Drawer({
  children,
  isOpen = false,
  speed = 0.5,
  width = '100vw',
  height = '100vh',
  bgColor = 'white',
  direction = 'right',
  zIndex = 99,
  className,
  style
}: DrawerProps) {
  return (
    <Box
      className={className}
      position='fixed'
      height={height}
      width={width}
      backgroundColor={bgColor}
      zIndex={zIndex}
      boxShadow='0 0 15px 3px rgba(0, 0, 0, 0.1)'
      style={{
        transition: `all ${speed}s ease`,
        ...directions(isOpen)[direction],
        ...style
      }}
      data-testid='drawer'
    >
      {children}
    </Box>
  )
}

export interface DrawerProps {
  children?: React.ReactNode
  isOpen?: boolean
  speed?: number
  width?: number | string
  height?: number | string
  bgColor?: string
  zIndex?: number
  direction?: 'top' | 'left' | 'right' | 'bottom'
}

```

## Direction helper 

```javascript
export const directions = (isOpen: boolean) => ({
  right: {
    transform: isOpen ? 'translateX(-100%)' : 'translateX(100%)',
    top: 0,
    left: '100%'
  },
  left: {
    transform: isOpen ? 'translateX(100%)' : 'translateX(-100%)',
    top: 0,
    right: '100%'
  },
  top: {
    transform: isOpen ? 'translateY(100%)' : 'translateY(-100%)',
    left: 0,
    bottom: '100%'
  },
  bottom: {
    transform: isOpen ? 'translateY(-100%)' : 'translateY(100%)',
    left: 0,
    top: '100%'
  }
})

```

##Now

Now? You know how to build a Drawer that opens from every side of your window! :)
More Mistakes Freelancers Should Avoid
Tags: productivity, beginners, career
Published: 2020-11-07 00:14:20

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**


Freelancing is something that may be tough for some people. If we avoid some mistakes, we can save ourselves from some grief.

In this article, we’ll look at some advice to follow as freelancers.

### Overestimating What You can do Well in a day or Week

It’s better to underbook than overbook yourself so you won’t be too stressed.

It’s hard to do a good job if you’re in a rush.

### Leaving Holes in a Contract

Make sure you think of all the points to protect yourself and your client and all the expectations from both sides are met.

### Not Calculating Your Rate

You have to calculate your rate in order for your work to be profitable.

### Compromising Work-Life Balance

Everyone needs to take a break once in a while.

Working too hard will leave you stressed and unhappy.

It’s hard to do a good job in this situation.

### Venturing Too Far From Your Niches

Better stick to what you’re good at so you can do a good job.

Make sure you can actually do a good job before you accept a project.

### Trust Your Gut When You Choose What Project to Accept

Your gut feeling is usually accurate when choosing what to pick.

### Getting Too Emotional About Business Relationships

Business relationships should stay as such.

Never get too emotional about business relationships and make yourself miserable.

### Not Tracking Your Time

Time tracking is needed for accurate billing, project time estimation, and managing productivity.

### Not Taking Care of Yourself

Never skip meals, take breaks often, don’t sit on your chair all day, and enjoy the sunshine once in a while.

### Selling Yourself Too Hard

Being genuine helps with getting sales than focusing only on sales.

Being too sales-y will be noticed by your prospect and that won’t leave a good impression.

### Trying to Sell to High-Quality Clients With the Same Methods That Works for Low-Quality Clients

High-quality and low-quality clients are different.

So they should be targeted differently.

Sales and marketing strategies should be different for both.

### Not Giving Samples Much Thought

You should retain rights to your sample work whenever possible.

This way, you can refer to them whenever you want since you’re in control of them.

### Not Asking for Help

Asking for help will help you solve problems much faster.

It’s also better to work with a support network that can help you get through the problems you face.

### Not Having an Onboarding Checklist

Having a checklist will make sure you won’t forget what you have to do to onboard clients.

### Forgetting to Celebrate Small Wins

Celebrating small wins is a great way to keep yourself positive and become more successful.

### Conclusion

If we follow the advice above, we can all be successful freelancers.
Top Mistakes Freelancers Should Avoid
Tags: productivity, beginners, career
Published: 2020-11-07 00:14:19

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**


Freelancing is something that may be tough for some people. If we avoid some mistakes, we can save ourselves from some grief.

In this article, we’ll look at some advice to follow as freelancers.

### Forgetting that I’m a business owner 

You aren’t working for anyone as an employee. Your client is a partner you’re working with.

So you shouldn’t expect clients to dictate what you do.

### Trying to Sell Your Skills Instead of Solutions to Clients

Clients want solutions, so selling them solutions you can offer them is better than selling what skills you have.

### Competing Mainly on Price

Good clients are willing to pay you good prices, so don’t compete on price.

You don’t want to work hard for low pay.

### Viewing Other Freelancers Solely as Competition and not Building a Network 

Some freelancers can be your competitors, but they can also help you find work and refer you to people they know.

### Niching Down Too Much and Too Fast

The narrower the niche, the harder it is to find people that need your specialization.

### Not Marketing Until Your Run Out of Projects

It’s a good idea to maintain your presence all the time so that you get noticed by potential clients.

It takes time for you and clients to find each other, so it’s better to start early so it’s less likely that you run out of work.

### Not Saving Enough Money

There’re always unexpected expenses and slow months, so saving money is always important in case you need the money.

### Dipping to Rock Bottom Rates

If you work for a rate that’s too low, you may be working on projects that aren’t profitable.

That means you’re wasting money.

### Wasting Time on Useless Things

You should prioritize useful things for clients and making money freelancing.

Anything else can wait.

Of course, taking breaks is also important.

### Relying Too Much on One Source of Work

Always diversify in case one source of income runs out.

### Relying on Freelance Platforms

Freelance platforms may work for some people.

But you don’t control them and they can cut you off with a click of a button.

You don’t want them to cut you off from your clients.

Always diversify on sources of client and income.

### Keeping Bad Clients for Too Long

If they’re shady or you aren’t profitable working with them, then cut them off as soon as you can.

### Not Having Formal Processes

Processes speed things up and keep things consistent, so it’s worth having them.

Setting standards for quality and other workflows are helpful.

### Taking in Too Much Advice

There’re lots of advice online. They’re either conflicting or may not be relevant to your situation.

They may lead you in the wrong direction, so it’s a good idea to take a break from reading advice.

### Conclusion

If we follow the advice above, we can all be successful freelancers.
Detect if a PWA is Visible with the Page Visibility API
Tags: development, web, pwa, webdev
Published: 2020-11-08 04:51:31

---
title: Detect if a PWA is Visible with the Page Visibility API
published: true
date: 2020-11-07 00:00:00 UTC
tags: development, web, pwa, webdev
canonical_url: https://goulet.dev/posts/detect-pwa-visibility/
---

Need to figure out when your PWA comes to the foreground? The modern web has you covered with the [Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API).

```js
document.addEventListener("visibilitychange", () => {
  const state = document.visibilityState;
  if (state === "hidden") {
    // your PWA is now in the background
  }

  if (state === "visible") {
    // your PWA is now in the foreground
    refreshData();
  }
});
```

> Note: this API isn't specific to PWAs, it works for non-PWA websites/webapps as well.

Most documentation talks about how this event fires when switching tabs, but this also fires when a PWA is foregrounded/backgrounded.

Try it out yourself by going to [https://visibility-api.netlify.app](https://visibility-api.netlify.app/) and adding it to your home screen.

> Hopefully you found this post helpful, if you have any questions you can find me [on Twitter](https://twitter.com/wes_goulet).
How the client request and server response cycle works
Tags: javascript, beginners, webdev, tutorial
Published: 2020-11-16 07:35:06

---
title: How the client request and server response cycle works
published: true
date: 2020-11-07 00:00:00 UTC
tags: javascript, beginners, webdev, tutorial
canonical_url: https://jsmates.com/blog/how-client-server-request-response-cycle-works
---

Let's learn how the client request flows through the server.

![Request response cycle](https://dev-to-uploads.s3.amazonaws.com/i/f8cxx3oj8gfflo1mb15o.jpeg)

For understanding, request, and response flow. Let's consider the example of the Twitter home page.

- If you go to Twitter without logged-in, then it loads generic tweets based on user location.
- If you log in, then it loads the feeds personalized for you.
  Even for the same request, different data responses get sent based on the request context.

What exactly happens in-between the client request and server response?

The flow will be like this,

- Client browser sends a request to the URL – https://twitter.com
- The server gets the request, parses the request, and checks whether the requested URL is valid or not
- If not valid, then the server sends a 404 – not found response
- The server checks whether the request was from valid-user
- If not a valid user, then it tries to get the user location
- If it finds the user location, then it sends a response with user location-specific tweet data
- If it doesn't find the user location, then it sends a response with generic global tweets data
- If a valid user requested the data, then it sends the response with the user's personalized tweet feed
- This is how the request flows inside the server before sending a proper response from the server.

This example simplifies a lot of steps in-between to make it easy to understand. There might be many more steps like this before the server sends the response to the client.
How to check if a string ends with a specific string or a character in JavaScript?
Tags: javascript
Published: 2020-11-07 00:00:00

---
  title: How to check if a string ends with a specific string or a character in JavaScript?
  published: true
  tags: JavaScript
  date: Sat Nov 07 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/check-if-string-ends-with-specific-string-character-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-c8dcc152844341bcfe6b5a2692d167df.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/check-if-string-ends-with-specific-string-character-javascript)
  
To check if a string ends with a specific string or a word, you can use the `endsWith()` string method in JavaScript.

Consider this string `Hello, How are you?`,

```js
// a string
const str = "Hello, How are you?";
```

Let's check to see if the string ends with the character `?` using the `endsWith()` string method.

```js
// a string
const str = "Hello, How are you?";

// check if string ends with character "?"
const doesIt = str.endsWith("?");

console.log(doesIt); // true
```

We can also check to see if it ends with a specific word and not a single character like above. For example, we can check to see if it ends with a word called `you?`

```js
// a string
const str = "Hello, How are you?";

// check if the string ends with the string "you?"
const doesIt = str.endsWith("you?");

console.log(doesIt); // true
```

Another cool thing with this method is that you can define the end of the string instead of the default length of the string. For example, in the above example what if we don't need to check till the `?` character and only need to check if the string ends with the word `you`.

You can do that by passing the length up to which you need to check as the second argument.

Here we don't need to check till the character `?`. So let's pass the length subtracted by one index as the second argument to the method like this,

```js
// a string
const str = "Hello, How are you?";

// check if string ends with the string "you"
const doesIt = str.endsWith("you", str.length - 1);

console.log(doesIt); // true
```

See this example live in [JSBin](https://jsbin.com/zuqorubeka/edit?js,console).

Key takeaways:

- the method accepts a string to check if it's present at the end as the first argument.
- the method accepts an optional length parameter to define the ending point for the string. If nothing is provided as the second argument, it defaults to the `length` property of the string.
- the method returns a boolean `true` if string present at the end and `false` if not.

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

---
TokenVortex.web.app
Published: 2020-11-06 23:35:43

Working on an Ethereum contract or curious about blockchain development? TokenVortex is an app that helps you test it out using Ethereum test networks in an easy and fluid way.

1. Create a random blockchain account.
2. Create a contract and compile it using Remix.ethereum.org and copy into TokenVortex.
3. Create a new transaction sequence
4. Add transaction steps (methods to be run)
5. Run the transaction and view the results

Go to [TokenVortex](https://tokenvortex.web.app) to find out more.
How to analyze news articles and get a sentiment score with Watson NLU without writing any code
Tags: nocode, video, ibmwatson, tutorial
Published: 2020-11-09 21:58:47

---
title: How to analyze news articles and get a sentiment score with Watson NLU without writing any code
published: true
date: 2020-11-06 23:04:25 UTC
tags: NoCode,  Video, ibmWatson, tutorial
canonical_url: https://maxkatz.org/2020/11/06/how-to-analyze-news-articles-and-get-a-sentiment-score-with-watson-nlu-without-writing-any-code/
---

I recorded another no-code video that I hope you will find useful. This video shows how to analyze news articles, get a sentiment score with [Watson Natural Language Understanding](https://www.ibm.com/cloud/watson-natural-language-understanding) (NLU) and save the score into Google Sheets. All this done without wring any code.

After watching the video you will have a good understanding of the following:

- How to get the latest news from [http://newsapi.org](http://newsapi.org)
- How to pass news article URLs to Watson NLU to analyze and determine the article sentiment score
- How to save the sentiment scores into Google Sheets
- You will build this application (flow) in [Parabola](http://parabola.io) without writing any code

{% youtube UzcNDdYJlAs %}

If you liked this video, check out my other [nocode videos](https://www.youtube.com/watch?v=UzcNDdYJlAs&list=PLSAWywyhniCOpvlFSfUWVNAbclc2-1Kne).
What should a programming language do "out of the box"?
Tags: discuss, programming
Published: 2020-11-06 22:57:11

It seems to require a lot of boilerplate in most mature programming languages to accomplish things that we do frequently.  For instance: database access, making RESTful web service calls, receiving RESTful web service calls, file IO (especially with commonly-used formats such as CSV), and GUI work.  Alternatively, you can usually find a third party library/framework that provides a decent implementation, but the ability is rarely built into the standard library.

What are your thoughts?  (Also curious if someone has counter-examples of languages that implement common tasks in the standard library.)