teleren/devto huggingface dataset:
Power ball lottery simulator
Published: 2020-01-12 17:14:24

A lottery test system that continues creating lottery tickets until every one of the 6 numbers coordinate. 

Powerball is played over the whole nation, and the one everybody out of nowhere wants to play once the bonanza goes over $300M. Which bodes well, clearly. Since there is no point at all in playing if it's any lower than that. 

This test system was composed for my own interest and to come to a meaningful conclusion. The fact of the matter is that the chances of winning are galactic! The interest is, exactly how cosmic is that? 

Somebody can let you know, "The chances of making it big are 1 of every 175,223,510". However, that number is completely useless in light of the fact that it's so large. Things being what they are, what was to occur on the off chance that you played multiple times? Okay, win even once?

I attempted it, with this program. It takes some time. Be that as it may, it will restore an outcome. Or on the other hand, it may crash your program. I prescribe holding the number to a progressively sensible level.

A MAJOR note about what I just composed there. Those chances were 100% right as of October 2015. I recently understood that they changed the guidelines of the game. There are presently 69 white balls and 26 red. This implies the chances of winning are really: 1 out of 292,201,338.

Here is the recipe, on the off chance that you have to dazzle anybody: (69*68*67*66*65)/(5*4*3*2*1) * 26 

The program here has been refreshed appropriately. I left the first arrangement of chances on here so you can perceive what they did. They made the game increasingly a good time for everybody by making it WAY more troublesome than it previously was.

For More details you can visit us at: <a href="https://infertilitytreatments.org/">파워볼사이트</a>
Lexical Analysis
Tags: automata, compiler, computerscience
Published: 2020-01-12 17:10:13

The first phase of a compiler design is called Lexical Analysis or scanner.  The Lexical Analysis read the Stream of characters that make up the source of file and group the significative sequences, known as a lexeme.

                              <token class, attribute value>

For example
int doc=8;

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/9hf9k5q2pae8b7dn6noh.PNG)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/j5bdmmwrf47exezh264c.PNG)



In the next table will be the lexemes classes used in the development of the practice.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/a1g8kp473zpm1tg1swh6.PNG)
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/4q7gxg0teemglmqq7zzl.PNG)

In the next Figure 1, it shows the first Automata called A1 which recognize identifiers:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/tmfe1m0f86otxth3k6oh.PNG)

The next Figure 2, it shows the Automata A2 which recognize Octal numbers, Hexadecimal number and Real number:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/phup8try77fhbqml47a2.PNG)

The next Figure 3, it shows the Automata A3 which recognize Delimitation characters, Arithmetic operators, Punctuation marks and Assignment Operator:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/5u2lmkrcjiid2odmo7yh.PNG)

The next Figure 4, it shows the Automata A4 comments:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ctbnj01tcjujcmmvipqt.PNG)

In this automata the number 10 represents New Line in ASCII code.

Conclusions:

As a conclusion, it was difficult to understand and solve the EOF, Blacks and comments. Because when I was using fgetc() function whit a char variable, the char variable was changing it for another number and never reach to EOF. So that was freaking me out but finally I solve it. Sometimes when the lexical analysis read a black it was doing a loop infinite but it was solved. Also, I consider that this practice was a huge challenge, but I made it.

The code: https://github.com/martincorona007/Lexical_analysis
Interview Prep #3: Two Sum
Tags: career, beginners, cpp, interview
Published: 2020-01-12 17:08:43

## Problem

We are given an array of integers and another a target integer. We'd like to find the indices of two numbers in that array such that the sum of these integers add up to the target. We cannot use the same number in the array twice and there is exactly one solution. This problem is on [leetcode](https://leetcode.com/problems/two-sum/).

```
Example

input:[2, 7, 11, 15], target = 9,
output: [0, 1]
```

## Solution

The first thing that came to my mind is to sort the arrays. But sorting would not work because as soon as we sort the array we change the original indices of the array.

The correct solution involves the use of [hash maps](https://en.wikipedia.org/wiki/Hash_table). We iterate over the array and   store the number in a map along with the index. We also check in the map if we can find a pair for the current number to get the sum to the target.
If we can, we return the current index along with the index of the complement number from the hash map. This takes linear time complexity ie. _O(n)_

```cpp
pair<int, int> find_sum(vector<int>& nums, int target) {
  map<int, int> m;
  for (auto i = 0; i < nums.size(); ++i) {
    int c = target - nums[i];
    if (m.find(c) != m.end()) {
      // pair found
      return {m[c], i};
    }
    m.insert({nums[i], i});
  }
  // If we cannot find a pair
  return {-1, -1};
}
```

> References: [Leetcode](https://leetcode.com/problems/two-sum/)
Have a beautiful day 🤗
Swift 5 language study
Tags: swift, tutorial
Published: 2020-01-12 15:16:18

## Idiomatic Swift
As a wretched perfectionist, I am tantalized to seek the correct way to do certain things. The standard library provides some clues, sure, but even that changed over time in C++, likewise in Swift (since 2.0 beta, yes, I am old enough to know the dropped conventions and adopted others). It was nearly 5 years ago since introduction of the language, and now, I am all in. 
~~Congratulate me, I require social approval to keep on going.~~

As a person coming from different language, 
Swift resembles everything likable from C++, low-level twiddling, 
yet rooted out undefined behaviours (think *null pointer exceptions*). 
The lightweight trailing closure syntax of `map` or `filter` are similar to that of **Ruby**.
Generics are similar C++ templates with additional type constraints to ensure generic functions integrity at the time of definition rather than runtime.
Flexible higher order functions and operator overloading means I can write code that's similar to JavaScript!
And the `@objc` and `dynamic` keywords allow me to use selectors and runtime dynamism in ways I could in Objective-C, **Wonderful**.

Given all that familiarity, I thought I could adopt all the same mental models from knowledge I have. Well, I am, indeed, capable of doing so, for conversion of Objective-C into Swift is 1 click away. Case point: familiar Object Oriented Design patterns apply.

I started coding... And hit a wall. Several times. I can't use protocol extensions with associated types like interfaces in Java (Arrays are not covariant). `functor` isn't here either. Thought, sure enough, there are ways of doing everything in a different manner.

Swift is a programming language unlike any one else, and this is promising, for it bring together the best practices, or so it says. (At least I need not to call C libraries to write a collection type).

### Thus I am into learning this language.
To write succinct, elegant code, get things in Apple application development done.

### This series of articles is about my journey. 

I promise to answer as many "Why does Swift behave like that?" as I may muster.  
Each article will cover fundamental concepts like optionals and strings one by one.
Python: What are *args and **kwargs?
Tags: python, beginners, learning
Published: 2020-01-12 16:32:31

---
title: Python: What are *args and **kwargs?
published: true
description: Understanding variable-length arguments (*args and **kwargs) in Python.
tags: python, beginners, learning
---

We may encounter Python function definitions that look something like this:
```python
def a_function(*args, **kwargs):
    ...
```

The asterisks denote parameters able to receive variable-length arguments. (The `args` and `kwargs` names don't matter — they're merely conventions, and stand for 'arguments' and 'keyword arguments' respectively. Any appropriate parameter names may be used.)

Say we need a function enabling users to share their hobbies, but we don't know in advance how many hobbies a given user will have:

```python
def my_hobbies(*hobbies):
    print("My hobbies: " + ", ".join(hobbies))
```

Our function now accepts one or more arguments:
```
>>> my_hobbies('reading', 'writing')
My hobbies: reading, writing

>>> my_hobbies('reading', 'writing', 'hiking', 'learning Python')
My hobbies: reading, writing, hiking, learning Python
```

Conveniently, we can also call our function by passing it a tuple, using similar asterisk syntax:
```
>>> some_hobbies = ('reading', 'writing', 'hiking', 'learning Python')
>>> my_hobbies(*some_hobbies)
My hobbies: reading, writing, hiking, learning Python
```

Now say we want a function enabling users to share their favorite things in various categories, but we don't know in advance how many categories a given user will select:
```python
def my_faves(**favorites):
    print("My favorite things...")
    for category, fave in favorites.items():
        print(f"{category}: {fave}")
```

Our function now accepts one or more [keyword arguments](https://dev.to/adamlombard/python-what-are-keyword-arguments-c1o):
```
>>> my_faves(Color='green', Fruit='persimmon')
My favorite things...
Color: green
Fruit: persimmon

>>> my_faves(Season='winter', Language='Python', Website='dev.to')
My favorite things...
Season: fall
Language: Python
Website: dev.to
```

We can also call our function by passing it a dictionary, using similar double asterisk syntax:
```
>>> some_faves = {"Animal": "whale", "Summer Hobby": "hiking"}
>>> my_faves(**some_faves)
My favorite things...
Animal: whale
Summer Hobby: hiking
```

A function may be defined with a mixture of formal parameters, variable-length parameters, and variable-length keyword parameters. When doing so, they must appear in the definition in the following order:
```python
def a_function(arg, *args, **kwargs):
    ...
```

More information can be found in the [Python documentation](https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments).

---

Was this helpful? Did I save you some time?

## {% cta https://www.adamlombard.com/support-me %} 🫖 Buy Me A Tea! ☕️ {% endcta %}

---
Interview Prep #2: Are Strings Permutations of Each Other
Tags: career, beginners, cpp, interview
Published: 2020-01-12 16:20:36

## Problem

We are given two strings and we are to decide whether one of the string is a permutation of the other.

```
Example

input: coffee fefeoc
output: true

input: day dea
output: false
```

## Solution

On top of my mind the first thing that comes is to sort both the strings and then check if they are equal. Sorting of the strings will take _O(nlogn)_ time and then comparing them will take _O(n)_ time. Thus the total time complexity will be and _O(nlogn)_.

```cpp
bool compare_strings_slow(string a, string b) {
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  return a == b;
}
```

The bottleneck of the current approach is the sorting part which takes  _O(nlogn)_ time. Let's think of what does it mean that two strings are permutations of each other. It means that both the strings have same characters the same number of times. So we need to store all the characters and their count of both the strings. For doing this we can use [hash maps](https://en.wikipedia.org/wiki/Hash_table). 

We will iterate over the strings and store the number of times each character appears in a map. Then we can check hash maps of both of these strings and if both are equal then this means that the strings are indeed the permutations of each other. In this approach we iterate over each of the strings once and then we iterate over the hash maps for comparison. This makes the total time complexity of this approach linear that is _O(n)_, where n is the length of strings.

An additional optimization we can add is to check if the string lengths are equal before making the maps.

```cpp
bool compare_strings(string a, string b) {
  if (a.length() != b.length()) {
    return false;
  }
  map<char, int> map_a, map_b;
  // fill a map
  for (auto c : a) {
    if (map_a.find(c) == map_a.end()) {
      // character inserted for the first time
      map_a.insert({c, 1});
    } else {
      ++map_a[c];
    }
  }
  // fill b map
  for (auto c : b) {
    if (map_a.find(c) == map_b.end()) {
      // character inserted for the first time
      map_b.insert({c, 1});
    } else {
      ++map_b[c];
    }
  }

  return map_a == map_b;
}
```

Additionally, can you find a way to minimize the space usage of hash maps? Is there a simpler data structure for this purpose?

> References: Cracking the Coding Interview - Gayle Laakmann McDowell
Have a productive day 🚀
What is the algorithm for dev.to's feed?
Tags: discuss, help
Published: 2020-01-12 15:51:55

My feed is full of people who I do not follow and tags I do not follow. I have checked various posts. It seems all of dev is being shown to me. What is happening here?

e.g. I am seeing this post
https://dev.to/koddr/how-to-create-a-native-macos-app-on-go-golang-and-react-js-with-full-code-protection-part-1-463k

I do not follow the person and do not follow any of tags in it so why am I seeing this post in my feed?

---

If you want to know when I write more articles join telegram channel for [Data posts](https://t.me/aseem_data), [software posts](https://t.me/aseem_software) or [other posts](https://t.me/aseem_life). I don't spam, promise.
Is It Advisable To Start Blogging in 2020
Tags: blogging, startablog, bloggingin2020
Published: 2020-01-12 15:41:17

Blogging is very popular these days as people came to know that blogging can generate income. But is this the only reason that you should [start blogging in 2020](https://www.bloggingjoy.com/start-a-blog/)? Well, I believe this is not 100% true.

There are multiple benefits of blogging besides, just making money online. In fact generating income from a blog is the last step of this process and it is quite difficult. Here I will share some amazing benefits of blogging besides making money.

1) **Become An Expert in Your Skill**: You can become an expert in your subject or niche by sharing useful knowledge with many people. In fact that's the ultimate purpose of blogging.

2) **Share Your Passion**: Blogging is the career where you can actually listen to your heart and write about the topic where you love to write. It is very difficult for people to blog who don't have a defined passion for something. Even if you are working on something, you can continue your passion

3) **Improve Your Writing Skill**: Blogging is the profession where you have to write a lot. Definitely you can hire a writer to keep your blog updated. But that's not what you would love to do to continue your blogging career for long time. That's where you will find the need of [writing good content](https://www.bloggingjoy.com/how-to-write-content/) and with time you will become a good writer.

4) **Help Others**: Through blogging you can actually help people who want to create a blog & make money online. Personally I love to help people through my Facebook group and help them to set up their blog and be a better blogger with time.

5) **Build A Solid Network**: Networking is the key to get success in any field. And blogging has huge potential to grow your network with like-minded people. 

So, these are few of the benefits of blogging besides just making money. You will find some interest which can generate income in future. At the same time you will find many like minded people and engage with them regularly to stay motivated. Make sure to invest your time and patience for blogging.
Linear Congruential generator
Published: 2020-01-12 15:40:24

This is a basic explanation of linear congruental generator, a method of generating random numerical values, the generating formulae is described by the equation

X<sub>n+1</sub> = (A x X<sub>n</sub>+B) Mod M

A,B and M are constants
The value X used to initialize the sequence is called the *seed*. The sequence of numbers generated are random however they have a period in which the whole function repeat its values, making it a random but a predictable generator.

The implementation of this algorithm in javascript would be as follows

```javascript

var m =11,
    a =7,
    c =5;
var z = 0;

var rand = function(){

z=(a*z+c)%m;

return z;
};

for(i=0;i<20;i++){
  console.log(rand());
}

```
AWS Cost Visualization and Savings
Published: 2020-01-13 14:27:18

---
title: AWS Cost Visualization and Savings
published: false
date: 2020-01-12 15:38:14 UTC
tags: 
canonical_url: https://kambanthemaker.com//posts/aws-cost-visualization-and-savings/
published: true
---

I have been using AWS for a few years now. I love the eco system, how easily the services can work together, starting from S3, DyanmoDB,SES to Lambda. One thing that kept me bothering was the billing interface. I love simplicity, though the AWS Cost explorer is good, sometimes it feels clunky. For a technical person it might look fine, but what about the top level people who want to know where they spend money, how much is the unreserved cost.

Having built https://flatga.io, decided to take advantage of the codebase and built a simple tool to view AWS Cost called [https://cloudsavings.io](https://cloudsavings.io). The key features are,

- Cost breakup by service
- Reservation coverage and utilization
- Cost breakup by accounts and regions
- Cost forecast
- Savings recommendations

All the information are pulled using official AWS API. The cost breakup should give you the high level overview of which services are costing you a lot, along with the filters, you can drill down on a few items, like data range, service-wise filtering, region-wise filtering.

Recommendations are split into two, one

- Reservation recommendation - The default reservation system
- Savings plan recommendation - The new reservation system specifically for compute devices.

One caveat is AWS Cost Explorer costs $0.01 per request, but we use 48 hour caching to keep your access cost around $1 to $2 per month. As of now, [cloudsavings.io](https://cloudsavings.io) costs from $0 to $29 per month based on your monthly bill. If your bill is less than $1000, it's free.

I hope this could help a few people out there who find it difficult to navigate the AWS billing dashboard.
i wish there was a browser that "lets me set limits on how much RAM, CPU and network usage it takes up"
Tags: browser, throttling, gaming
Published: 2020-01-12 15:14:40

well actually (as many gamers have already found out) opera have already done that !

its called opera gx https://www.opera.com/gx#network-limiter

*Need every ounce of power your machine can give you? No need to close your browser. GX Control lets you set limits on how much RAM, CPU and network usage your browser takes up.*
Download all Flickr photos of a user with only 20 lines of Python 🐍
Tags: python, flickr
Published: 2020-01-12 15:11:14

# Introduction

Today, a friend wanted to download all photos of a photograph he likes a lot on Flickr.. but that's a long and a boring task.. especially when the user has many photos.

So, I just asking myself how I can automate this task.. and Python is the answer!

# Prerequisite

- Python and Pip (the higher is better!)
- [venv](https://docs.python.org/3/library/venv.html) : optional, but I advise you to use it.

# Let's jump into the code!

- At the root of your working directory run the following command to install `flickr_api` as a dependency

```bash
pip install flickr_api
```

- Next you have to create an account on Flickr and log you in to get your `api_key` and your `api_secret` with the following [link](https://www.flickr.com/services/api/keys)
- Then use this code and replace `API_KEY`, `API_SECRET` and `USER_NAME` with your credentials 🙂

```python
import os
import flickr_api

flickr_api.set_keys(api_key = 'API_KEY', api_secret = 'API_SECRET')
os.makedirs(os.path.join(os.getcwd(), "photos"), exist_ok=True)

user = flickr_api.Person.findByUserName("USER_NAME")
pages_nb = user.getPublicPhotos().info.pages
total = user.getPublicPhotos().info.total
current = 0

for page_nb in range(1, pages_nb+1):
    for index, photo in enumerate(user.getPublicPhotos(page=page_nb)):
        sizes = photo.getSizes()
        biggest_size = list(sizes.keys())[-1]
        filename = photo.title.replace("/", "-") + "_" + photo.id

        current += 1
        try:
            print(f"{current}/{total}", filename)
            photo.save(os.path.join(os.getcwd(), "photos", filename), size_label = biggest_size)
        except Exception as e:
            print(e)
```
Some Fish Aliases for a More Productive Programming
Tags: fish, docker, kubernetes, aliases
Published: 2020-01-12 15:01:29

I believe that the shell prompt shouldn't be too much cluttered. Here's how mine looks:

![myprompt](https://thepracticaldev.s3.amazonaws.com/i/9botmp6uri0tdoqygomx.png)

It contains the PWD, followed by the current Git branch and the K8s context I'm using. This is achieved by the following `~/.config/fish/config.fish`:

```sh
function custom_prompt
    set_color normal
    set -l git_branch (git branch 2>/dev/null | sed -n '/\* /s///p')
	set -l kube_context (kubectl config current-context | cut -d. -f1)
	set_color 2eb82e
    set_color cyan
    echo -n (prompt_pwd)
    set_color normal
    echo -n ' ['
    set_color 0087ff
    echo -n "$git_branch"
	if [ ! -z "$git_branch" ]
	  set_color normal
	  echo -n "/"
	end
	set_color 00b386
	echo -n "$kube_context"
    set_color normal
    echo -n ']'
	set_color cyan
    echo -n '$ '
end
``` 

Addiotianly, sometimes I want to hide the prompt in order to get more space in my terminal. For that, I have the following aliases:

```sh
function fish_prompt --description "Custom fish prompt"
    custom_prompt
end

function show --description "Show fish prompt"
    function fish_prompt
        custom_prompt
    end
end

function hide --description "Hide fish prompt"
    function fish_prompt
        echo -n '> '
    end
end
```

which gives me the following:

![showandhide](https://thepracticaldev.s3.amazonaws.com/i/5vmum4gydmmuo81lntna.gif)

Additionally, here are some of my favorite aliases for K8s and Docker:

```sh
# switch between K8s contexes
abbr -a -g kubedev kubectl config use-context <dev-context>
abbr -a -g kubestaging kubectl config use-context <staging-context>

# edit deployments
abbr -a -g edit-deployment kubectl edit deployment <deployment>

# exec to your common pod
function exec-pod
    set pod_id (kubectl get pods -l app=<app> -o custom-columns=":metadata.name")
    kubectl exec -it $pod_id bash
end

# display the current deployed image
function current_image
    set image (kubectl get deployment <deployment> -o=jsonpath='{$.spec.template.spec.containers[:1].image}')
    printf "$image\n"
end

# docker stuff
abbr -a -g drm docker rm
abbr -a -g dri docker images
abbr -a -g dexec docker exec -it
abbr -a -g dstopall docker stop (docker ps -q)
abbr -a -g dps docker ps
abbr -a -g rmidang docker rmi -f (docker images -f "dangling=true" -q)
```

I have the same aliases also for Bash, if someone is interested I'll happily share them.

I'd appreciate it if you share your useful aliases too!
Laravel Treeview | Structure and Display Hierarchical Data Example
Tags: laravel, treeview, hierarchical
Published: 2020-01-12 14:54:25

I was working on application where I had to create hierarchical relationship for a Model entity and also figure out a way to display it in HTML.

I decided to write an article on this as I came across similar questions over the internet and the process which I have gone through might help someone looking for similar solution.

https://www.codechief.org/article/laravel-treeview-structure-and-display-hierarchical-data-example