teleren/devto huggingface dataset:
How to run Cassandra Container locally?
Tags: nosql, hacktoberfest, database, docker
Published: 2021-10-19 16:45:32

Most of us have heard about [Apache Cassandra](https://github.com/apache/cassandra), it is an open sourced distributed NoSQL Database which is used by large corporations like Facebook, Uber, etc

I will be explaining how to create a container with cassandra and connect into it to execute the Cassandra Query Language(CQL) statements.

**Cassandra offers various advantages like:**
-	Scalability
-	Maximum Fault Tolerance across NoSQL databases
-	Multi Data-Center support and Hybrid Cloud support

In this tutorial, I will be explaining how to create an instance on Docker and execute basic cqlsh commands

Basically, all docker containers can be established with a yaml, the compose file for this is
```yaml
version: '3.9'

services:
  db:
    container_name: cassandra-dev
    image: cassandra
    ports:
      - 9042:9042
    environment:
      CASSANDRA_USE_ASTRA: "false" 
      CASSANDRA_USER: "cassandra" 
      CASSANDRA_PASSWORD: "cassandra" 
      CASSANDRA_LOCAL_DC: "datacenter1" 
      CASSANDRA_CONTACT_POINTS: "db:9042"
      CASSANDRA_KEYSPACE_CQL: "CREATE KEYSPACE test_keyspace WITH REPLICATION = {'class':'SimpleStrategy','replication_factor':1};" 
      MONITORING_PROMETHEUS: "false"
      MONITORING_GRAFANA: "false"
      DISTRIBUTED_TRACING_ENABLED: "false"

```
Once you've created this yaml, open your CLI and run the following command, I have explained what it does down below
```zsh
docker-compose up -d
```

In a nutshell, this yaml tells docker to spin up a container with the following details
-	Pull up the Cassandra Image
-	Spin it up on the container named “Cassandra-local”
-	Expose it on ports 9042
-	Create a Cassandra user with the following parameters
-            username: Cassandra, password: Cassandra
-	[Create a keyspace]( https://cassandra.apache.org/doc/latest/cassandra/cql/ddl.html) (similar to database if you’re from a SQL background) , called test_keyspace
To access the database/keyspace you can access the shell by using the following command
```sh
>docker exec -it cassandra-dev /bin/bash
>cqlsh
```
To create a keyspace use the following commands:
```cqlsh
	CREATE KEYSPACE test_keyspace_2;
	USE test_keyspace_2;
	CREATE TABLE IF NOT EXISTS test_table(
	  id         uuid,
	  first_name text,
	  last_name  text,
	  address    text,
	  city       text,
	  telephone  text,
	  PRIMARY KEY ((id))
	);
```
You can consider using the [DDL and DML]( https://cassandra.apache.org/doc/latest/cassandra/data_modeling/data_modeling_rdbms.html) commands from the docs here

The connection to docker has been successful and now you can connect it to learn CQL.
Upload base64 encoded image with Laravel
Published: 2021-10-19 16:30:51

I am going to be really straight to the point on this one. If you need to upload a base64 encoded image or you just want to learn how to do it for future use, then bookmark this page now.

I won't talk about the User Interface or the input form. I will only talk about the actual method within your controller. I will assume you have that part covered already and your are building a RESTful API. **So let's call the method UploadImage**

### What does this method do? 🤓

The method uploads multiple image types, such as: *jpeg, png, svg, gif and base64 encoded images. So it handles all our image upload needs* 🏌🏼‍♂️

<code>
public function UploadImage(Request $request) { 
//method body goes here
 }
</code>

<a href="https://victorighalo.medium.com/how-to-upload-base64-encoded-image-and-other-image-types-with-laravel-f2f85e9cb6f6">continue</a>
Most Common Design Patterns
Tags: oop, java, programming, design
Published: 2021-10-19 16:30:00

Welcome to this new eight part series where we'll discuss about one of the most influential and controversial topics in programming, which is design patterns.

You may be familiar with the term, I can even bet that you've heard a workmate or a colleague talking about Design Patterns before. But, what are they and what benefits bring to the table? Let's take a look.

##Design Patterns
A design pattern is a reusable solution to a recurring problem within a given context. It means, they are well tested solutions to general problems in software porgramming, they're usually regarded as best practices by some experts.  

Design Patterns were officially presented in the book "Design Patterns - Elements of Reusable Object-Oriented Software" which was written by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. The authors are also known as Gang of Four (GoF).

There were originally 23 Desing Patterns specified by GoF. However, with new programming paradigms and new programming stacks releasing more frequently, we currently don't know the official amount but we expect a much higher number. 

Design Patterns can be classified in three main categories:
* Creational Patterns: They deal with object creation mechanisms.
* Structural Patterns: They help designing large structures.
* Behavioral Patterns: They are concerned with algorithms and assigment of responsibilities.

##Benefits
The main benefit of Design Patterns is that they provide well-tested solutions to known problems. However, we can also list the following benefits:

* They provide a common language and jargon for programmers. For instance, when a programmer states that he/she implemented "X" pattern in a given class it's usually common knowledge for the rest of the team.
* They help you write code faster by implementing well-known and testable solutions.
* They help you write more legible and maintainable code.

##Criticism
Some experts claim that Design Patterns introduce innecesary complexity into your code. This is partially true, Design Patterns have developed some kind of "lazyness" in programmers because they won't look for more simple solutions before going straight to desing patterns, this is specially true on junior developers. Rememeber, there must be a "common" context for using a desing patterns and even then, we must try to look for simpler solutions before implementing a new Design Pattern that you just read. 

Design Patterns are good practices, well tested solutions to common problems. They are not some magic recipe to solve all our problems. It's up to you to decide where you apply a specific pattern and how to accommodate it to your chosen language, framework and solution.

##Most common Design Patterns
We'll explore the most common and used patterns:

* Singleton
* Strategy
* Observer
* Factory
* Adapter 
* Builder  
* State

In the next post, we will talk about the Singleton Pattern.
Should layout markup be a component in React?
Published: 2021-10-19 16:23:35

Do layout markup  need to be a component of its own?

For example 

Do we need a Card component that adds a border and padding to a card like soo


<Card>
 ....

</Card>

Instead of using a pure html + css solution like 

<div className="card">
...

</div>



I really like the second approach and I feel like lesser components are a better solution from a performance perspective. 

On the other hand the second solution follows atomic design.
How to use iOS simulator in full-screen
Tags: ios, reactnative, programming, productivity
Published: 2021-10-19 16:11:38

When working on React Native or Expo applications, it is important to create focus to get in a flow. Sometimes, there are a lot of tasks to cover and very little time. To help focus on the task ahead, one way to speed up development is to use full-screen mode for iOS simulators. For example, a focused environment on my laptop screen includes zero visibility for Dock and the menu bar.

Before Xcode version 12, the full-screen support was hidden behind a user flag. The below command can be run to solve the issue for older Xcode versions.

```shell
defaults write com.apple.iphonesimulator AllowFullscreenMode -bool YES
```

With the latest version of Xcode and each new macOS version trying to outperform its previous one, it has never been easy to enable full-screen mode for an iOS simulator.

![ss1](https://i.imgur.com/mvSX1u2.png)

In the above image, observe that [VSCode editor](setup-macbook-m1) is on the left and the iOS simulator is on the right.

To enter the full-screen mode, click on the resize window icon (green icon) on the application (iOS simulator and the editor/IDE of your choice).

![ss2](https://i.imgur.com/nhkQdNs.png)

Then, you can position one application on the left and another on the right.

![ss3](https://i.imgur.com/ZjU2UUi.gif)

It's already challenging to keep distractions at bay. But, sometimes, a little bit of focus can go a long way.
Automate React.Context creation
Tags: react, context, javascript, hooks
Published: 2021-10-19 16:10:37

When the React team implemented Context API, developers started to have a better way to pass data through the components. I love to use many local contexts to wrap some parts of the app and have shared data without props chaos.

This is how we can automate React.Context creation, by passing in it our custom hook function:
```typescript 
import * as React from 'react';

type Hook<T, P> = (props: P) => T;

type ContextHook<T> = () => T;
type Provider<P> = React.FunctionComponent<P>;
type CreateContextHookReturn<T, P> = [Provider<P>, ContextHook<T>];

export function createContextHook<T = unknown, P = unknown>(
  useHook: Hook<T, P>,
  args: { name: string }
): CreateContextHookReturn<T, P> {
  const Context = React.createContext<T | undefined>(undefined);

  function useContextHook(): T {
    const context = React.useContext(Context);

    if (context === undefined) {
      throw new Error(
        `${args.name} Context value is undefined. Make sure you use the ${args.name} Provider before using the context.`
      );
    }

    return context!;
  }

  function Provider(props: React.PropsWithChildren<P>) {
    const value = useHook(props);
    return <Context.Provider value={value}>{props.children}</Context.Provider>;
  }

  return [Provider, useContextHook];
}
```

Then create your hook and pass it to the createContextHook:


```typescript
import React from 'react';
import { createContextHook } from '../createContextHook';

// 1. Create your custom hook
type UseMyCustomHookProps = {
  someInitialValue: number;
}

function useMyCustomeHook(props: UseMyCustomeHookProps) {
  const [count, setCount] = React.useState(props.someInitialValue);
  return { count, setCount };
}

// 2. Create and get the Context Hook and Provider
Wrapped your application tree to the provider.

const [MyCustomHookProvider, useMyCustomHookContext] = createContextHook<
  // the return value of the hook
  ReturnType<typeof useMyHook>,
  // the hook input parameter
  UseMyHookProps
>(
  // Pass your hook reference
  useMyCustomHook,
  {
    // `name` is used only for debugging propose when you failed to connect the hook
    name: "MyCustomeHook"
  }
);

export { MyHookProvider, useMyHookContext };
```
Or use npm package:

```typescript
import { createContextHook } from '@straw-hat/react-hooks';
```
🥴💭Don’t be afraid to ask or to admit that you need help
Tags: beginners, programming, devjournal, productivity
Published: 2021-10-19 16:06:20

## Help, I need somebody! .... The Beatles would say.


Today I am writing this post from an experience that happened to me last week. I was working on my current project when it came up that there was a very important functionality, which had a bug. A bug that had to be fixed as soon as possible.

A bug that took me about one week to fix.🥴

But my goal today is to talk about the fear we feel about asking when we don't know something or don't know how to move forward.

😵🌳 When we were kids, we were planted the seed that it's not okay to ask. We learned that if we ask, we'll get a finger pointed at us like we have a big "I'm a fool" in the face. But that's not true.


```
When I was younger, so much younger than today
I never needed anybody's help in any way
But now these days are gone, I'm not so self assured
Now I find I've changed my mind and opened up the doors
```


### Learning is an continuos process. 

It never ends. Even more so in the field of computer science. New tools, frameworks and languages emerge every day.  We learn every day, with small steps, small changes. 🧐 So we have no obligation to know everything. But we can take responsibility for our actions. 🤗

💡 Someone once told me that there are no dumb questions, but there are fools who don't ask.💡 So true! 

So here I was, in the middle of my frustrated and stressed work week. So I decided to ask for help. 

Think of it this way: we're here at Dev.to to ask and learn. To be better. And that's great. So why not do it at work too?

Not to be told how to do it. I looked for solutions, possible ways forward and asked if I was on the right path. I asked the questions I felt were necessary to understand the context in which I was working. 

I think the most important thing is that I told myself was I could. I could solve this. Whatever it cost me. 💪💪

### When you find yourself saying: **I don't know** , make sure follow it with **but I will find it**.

As I read in the pages of the book The Pragmatic Programmer: 

### It's a great way to admit what you don't know but then take responsibility like a pro.

🧐 And taking responsibility means that many times you're going to have to ask for help. So to solve my big problem, I asked for help, and that's fine. And it's part of being a good professional, being a programmer. ***It helps us grow***. Personally and professionally.🤗❗❗

I always say that we always learn from others. So let's not be afraid to ask when we don't know something. Because we will learn it. A lot! 

```
Help me if you can, I'm feeling down
And I do appreciate you being round
Help me, get my feet back on the ground
Won't you please, please help me?
```
CodeChef - ATM Problem
Tags: codechef, programming, beginners, java
Published: 2021-10-19 15:46:34

CodeChef ATM Problem- Problem Code: HS08TEST

Basic Programming Series....

>Problem Statement:- Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction.

### Input
Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw.

Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance.

### Output
Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.

### Explanation
Entered amount must be multiple of 5 that's why we are checking it by using modulus operator which returns the remainder of the numbers after dividing it with 0, if the remainder is 0 then it is multiple of 5. Second condition is to check whether the withdraw amount is available in her bank account after adding the 0.50$ charges, If both the condition are true then this expression is executed **"balance = balance-amount-charges"**. If both condition doesn't satisfy then the available balance needs to be printed. 

Also the output is required  number with two digits of precision i.e balance must be shown with two decimal points. for that the below printf statement is used to format the output as per our need.
 
```
if(amount%5==0 && amount+charges<=balance) {
			balance = balance-amount-charges;
```
```
System.out.printf("%.2f", balance);
```
>Example - Successful Transaction

Input:

```
30 120.00
```

Output:
```
89.50
```

>Example - Incorrect Withdrawal Amount (not multiple of 5)

Input:

```
42 120.00
```

Output:
```
120.00
```
>Example - Insufficient Funds

Input:

```
300 120.00
```

 Output:
```
120.00
```
Check output here:- [CLICK HERE](https://blog.atharvasid.me/atm-problem)

Link to the Series:- [CLICK HERE](https://blog.atharvasid.me/series/basic-programming)

Link to original problem [https://www.codechef.com/problems/HS08TEST](https://www.codechef.com/problems/HS08TEST)

LIKE! SHARE! COMMENT!

More problems will be added regularly to this series.
Learning Python Intermediate Course- yearning for suggestions
Tags: discuss, learningpython
Published: 2021-10-19 15:46:10

The intermediate part of the Learning Python course ended last week.
In case you missed it, you might check out the series [here](https://dev.to/aatmaj/series/13315). So I am asking you all for any suggestions you might want to add to help me improve.


____

So guys if anyone of you have any suggestions of doubts or anything to add, please comment them below. 😊
Coffee and Code: Explore Front-End Documentation best practices using Docz and React!
Tags: opensource, docz, documentation, react
Published: 2021-10-19 15:39:23

Want to establish a career in front-end development or just a beginner? Then join us for a live event on Do's and Don'ts of Front-End Documentation led by Hillary Nyaykundi.

### Meet Hillary who’ll sail you through your front end journey

Hillary officially began his developer’s journey back in 2018 and has been contributing to open-source ever since. With an upper hand in python, Django, and complex AI systems, Hillary has been an active contributor to FreeCodeCamp, React, and Docz communities.

### Why should you join?
- 
Getting started on your Front-end documentation journey? We have got you covered. Hillary will revisit the basics of front-end documentation from the very beginning.
- 
If you have been actively contributing to Docz, join the session to strengthen your foundations
- 
To end your procrastination and finally begin with React
- 
Networking opportunities with fellow developers, Hillary, and other open-source enthusiasts

Mark your Calendar: 📆  **21st October, Friday**

Time: **6.00AM PST | 9.00AM EST**

Join here 📌
https://bit.ly/2Z14tv3

To view the next event lineup, tap [here] (https://aviyel.com/events).

The countdown begins now!

Team Aviyel
Calculate Distance between 2 Geo Locations in PHP MySQL
Tags: mysql, webdev, php, sql
Published: 2021-10-19 15:36:46

Geolocation serves in a multitude of contexts. In this internet era, everything is on the single palm. Various technology uses various methods to get geolocations and distance between two locations. 
We are going to use PHP MySQL as technology to calculate the distance between two geo coordinates.

# How can I do that?

# Using MySQL Query
So, I have a table `geo_cord` containing two fields `latitude` and `longitude` and I need to calculate the user input `distance` in km with another user inputs `user_latitude` and `user_longitude`. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vua1o2u94wn5kicrhgtu.PNG)


Well! we need to write a query:
> We need to find all results from Database within user input distance
```
$distance = 50; // user input distance
$user_latitude = '26.826999'; // user input latitude
$user_longitude = '-158.265114'; // user input logtitude

$sql = "SELECT ROUND(6371 * acos (cos ( radians($user_latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($user_longitude) ) + sin ( radians($user_latitude) ) * sin( radians( latitude ) ))) AS distance,geo_cord.* FROM geo_cord HAVING distance <= $distance";

```
* To convert to miles, multiply by 3971.
* To convert to kilometers, multiply by 6373.
* To convert to meters, multiply by 6373000.
* To convert to feet, multiply by (3971 * 5280) 20914080.

There are other methods to achieve the same result, but I prefer this simple method with less coding and quick result.

# Using PHP

I have found a formula in Wikipedia [Haversine formula](https://en.wikipedia.org/wiki/Haversine_formula) which determines the great-circle distance between two points on a sphere given their longitudes and latitudes.

So it also gives result:


```
function distance($latitude1, $longitude1, $latitude2, $longitude2) { 
        $pi80 = M_PI / 180; 
        $lat1 *= $pi80; 
        $lon1 *= $pi80; 
        $lat2 *= $pi80; 
        $lon2 *= $pi80; 
        $r = 6372.797; // radius of Earth in km 6371
        $dlat = $lat2 - $lat1; 
        $dlon = $lon2 - $lon1; 
        $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2); 
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); 
        $km = $r * $c; 
        return round($km); 
    }
```
# Conclusion
There are simple methods to achieve complex challenges. We just need to convert all challenges into opportunities. 😋

NOTE: *NOTE: The map image is only for example purpose. It is not actual output.*
I will be notified if you click this 😈
Tags: programming, tutorial, node, security
Published: 2021-10-19 15:24:33

Would you like to get notified when someone opens your **dev.to** article or reads your email? Yea that will be awesome. Okay then lets see how we can do that?

Lets talk about **Images** they are pretty cool right? Imagers are everywhere including in Articles and Emails.
So let see how image work.
In markdown you use images like this
```md
![alt text](https://yoursite.com/some_image)
```
Or in HTML you'd use the image tag
```html
<img src="https://yoursite.com/some_image" alt="alt text" />
```
and of course the markdown above is later compiled to HTML So lets focus on that.

So when a webpage have an image the browser will send an http request to the URL which is in the src of the image(**https://yoursite.com/some_image** in our case).
And then **https://yoursite.com** will send us and image which will be later shown to us in browser.
So the server-side code of **https://yoursite.com/** could look something like this
```js
app.get("/some_image", (req, res) => {
     res.sendFile('some_image.jpg')
})
```

But the question is, is it that all we can do? Well its our code we can do whatever we want. So why not just notify our self that someone viewed this image?
```js
app.get("/some_image", (req, res) => {
     notifyUser() //You can implement it the way you want
     res.sendFile('some_image.jpg')
})
```
Now we will be notified whenever a user sees our image. That also means that if we use this image in our article/email we will know when a user opens it/reads it.

So if you're seeing this image that means ...
![Meme image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16ay9r64s0rzzczwbdu2.png)