teleren/devto huggingface dataset:
C++ round double to 2 decimal places.
Tags: cpp, oop, programming
Published: 2020-12-18 18:51:54

Rounded floating-point numbers to two decimal places can be done by using various methods.

---
title: C++ round double to 2 decimal places.
tags: cpp
canonical_url: https://kodlogs.com/blog/878/c-round-double-to-2-decimal-places
---

#Using the float precision:
```
int main()

{

               float var = 37.66666;



               // Directly print the number with .2f precision

               printf("%.2f", var);

               return 0;

}
```
**Output:**

37.67

#By using integer typecase:
This method is applied if we are using a function that will tell how to return two decimal point values.

```
float round(float var)

{

               // 37.66666 * 100 =3766.66

               // 3766.66 + .5 =3767.16 for rounding off value

               // then type cast to int so value is 3767

               // then divided by 100 so the value converted into 37.67

               float value = (int)(var * 100 + .5);

               return (float)value / 100;

}



int main()

{

               float var = 37.66666;

               cout << round(var);

               return 0;

}
```

**Output:**

37.67
#By using the speintf() and sscanf():
```
float round(float var)

{

               // we use array of chars to store number

               // as a string.

               char str[40];



               // Print in string the value of var

               // with two decimal point

               sprintf(str, "%.2f", var);



               // scan string value in var

               sscanf(str, "%f", &var);



               return var;

}



int main()

{

               float var = 37.66666;

               cout << round(var);

               return 0;

}
```

**Output:**

37.67
What is the difference between a float and a double?
Tags: cpp, oop, programming
Published: 2020-12-18 18:48:24

For representing floating-point numbers, we use float, double and long double.

---
title: What is the difference between a float and a double?
tags: cpp
canonical_url: https://kodlogs.com/blog/706/what-is-the-difference-between-a-float-and-a-double
---

#Float:
Float is a 32 bit IEEE 754 single-precision floating-point Numbers in which 1 bit is used for the sign, 8 bits for the exponent, and 32* for the value. The float data type has 7 decimal digits of precision.

**Example:**
```
float a = 1.f / 81;

float b = 0;

for (int i = 0; i < 729; ++ i)

 b += a;

printf("%.7g\n", b);
```
##Output:
9.000023
#Double:
Double is a 64 bit IEEE 754 double-precision floating-point numbers in which 1 bit is used to represent the sign, 11 bits for the exponent, and 52* bits for the value. The double data type has 15 decimal digits of precision.

**Example:**
```
double a = 1.0 / 81;

double b = 0;

for (int i = 0; i < 729; ++ i)

b += a;

printf("%.15g\n", b);
```
##Output:
 8.99999999999996
Note:
The maximum value of float is about 3e38 and double is about 1.7e308. So, using the float can hit “infinity” much more easily than double for something simple like computing the factorial of 60.
How to exit a C++ program?
Tags: cpp, oop, programming
Published: 2020-12-18 18:45:09

When we first started learning about programming and C++ we learnt many new things about a program. Every book says that the return statement tells the program when the program should terminate. But there are other ways also.

---
title: How to exit a C++ program?
tags: cpp
canonical_url: https://kodlogs.com/blog/1116/how-to-exit-a-c-program
---

#Methods
In c++, you can exit a program in three ways:

* Call the exit function
* Call the abort function
* Execute a return statement

 

##Exit function
The exit function is defined in the <stdlib.h> header file. As the name suggests it terminates the program. As in return statement we have to return any valid value to exit a program, similarly, exit provides a value as argument to the OS as the return code of the program. By convention, every return code of zero i.e., return 0; defines that program completed successfully. 

We can also use the literals defined in <stdlib.h>, EXIT_FAILURE and EXIT_SUCCESS. As the name suggests it indicates the success or failure of the program.

In simple words, we can say that the return statement from the main function has equivalent use as calling exit function with return value as arguments.

 

##Abort function
The abort function is also defined in the <stdlib.h> header file. And it also terminates or exits the program. 

The difference in abort and exit function is that exit function allows C++ run-time termination processing to take place whereas abort function exits the program immediately.

The abort function bypasses the normal destruction process for global static objects and also by passes any special processing that was specified using the atexit function.

 

Atexit function
This function is automatically called when the program exits normally.

 

##Return statement
Calling return statement from the main function also terminates the program and it is equivalent to the exit function. C++ requires that functions have return type other than void. The return statement allows us to return a value from the main. 

**Note: return void and return 0 are two different things.**

 

###Example
```
#include <stdlib.h>
int main()
{
    exit( 3 );
    return 3;
}
```
Heroku, stages and idle time
Tags: help, devops, webdev, productivity
Published: 2020-12-18 18:33:01

This year I wanted to understand how to deploy my own apps and improve that path by adding improvements like code coverage upload through jobs or how to use different stages.
Now I've learned how to work with services like heroku and Github Pages/Actions, I come to you with this problem:

These days I have a couple of apps for demo purposes loaded on Heroku using free dynos/plan, these apps are working for my beta and production branches in separated apps
Thanks to the free dynos I don't have any cost, but this comes with the cost of idle time after the app is not been used for 20 minutes.
So far I have founded that each app (or dyno) has to be upgraded to be 24/7 for USD 7/month (thing that I approve, but it gets expensive in my country if I have to mantain several apps with that service)

Therefore, I need your advice about alternatives to heroku or a way of mix services (like use Heroku for the beta version and GitHub Pages for prod).

Any hint or idea is welcome :D
Thank you for your help.
Live by the Rules, but don't Die by the Rules
Tags: bestpractice, programming, python
Published: 2020-12-18 18:28:16

As developers, I believe we all have to set our priorities right.

Let me start with a short story about a dev boy.
> _In a land of myth, and a time of magic, the destiny of a great kingdom rests on the shoulders of a young boy (who screwed it up).
This dev boy wanted to build something innovative, so he would contribute to his community and humanity.
He decided to use python to build the future. Then he started learning python, but get stuck when he tried to strictly follow ALL rules (about clean code, proper documentation, optimization, best practices, and so on..). As he lived and died by the rules, he never pushed any code to production because he felt they all weren't good enough, yet‽_

![dev boy](https://dev-to-uploads.s3.amazonaws.com/i/yj0koio6kosm84lhvbb9.jpg)

---

Just like the dev boy, so many developers fall into this sh*t of not figuring out what matters the most (which is building stuff). If only they could take a trip to the "land of Production" and find out how a lot of messy codes are lying there and hell hasn't broken loose.
![working messy code](https://dev-to-uploads.s3.amazonaws.com/i/6v5kg1pifytk0o4zosue.jpeg)

---

#### So one quick advice,
just as Mark, said:
> _Move fast and break things_

---
I say to you all delaying the future,
 ___Move fast and build things.___

---
######Make sure you give me a kudos by hitting the ❤️ button
DO Hackathon: Phase 2 - The Design
Tags: dohackathon, digitalocean
Published: 2020-12-18 18:21:41

---
title: DO Hackathon: Phase 2 - The Design
published: true
description: Mocking up the design
tags: #dohackathon #digitalocean
series: "DigitalOcean Hackathon"
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/yrfio068wzk6qkkcvyd5.jpg
---

Now that I have an idea it’s time to work on the design.  I usually start by thinking about the UI and how it will flow.  So I fired up [Figma](https://figma.com) and created a rough sketch of the UI.  For this project I need something simple, 2 or 3 views and a couple of inputs.

## The Workflow

1. User begins at the landing page:
 * A random image will appear for a set amount of time.
 * They will enter a description of what they saw in an input box.
 * They will then click the Submit button, which navigates them to the results page.
2. User finishes at the results page:
 * The original image will be displayed.
 * The user’s input describing the image will be displayed.
 * They can then click the Share Results button, which will copy the link to the results page.

## The Landing Page

![Landing page mockup](https://dev-to-uploads.s3.amazonaws.com/i/ha7tpxo7v0dv3ta1r3ck.png)

## The Results Page

![Results page mockup](https://dev-to-uploads.s3.amazonaws.com/i/qsdq5doy215tlxjyy8pg.png)

#### See you on the next post!

---
<span>Photo by <a href="https://unsplash.com/@firmbee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">William Iven</a> on <a href="https://unsplash.com/s/photos/design?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>
Laravel Fortify Kullanımı
Tags: turkish, php, laravel, fortify
Published: 2020-12-18 18:10:33

Detaylar için laravelin kendi dökümanından yararlanabilirsiniz : https://laravel.com/docs/8.x/fortify

<h1>Kurulum</h1>
Kurulum için aşağıdaki kodu projenizin içerisinde açtığınız cmd penceresine yapıştırın.
```
composer require laravel/fortify
```
Şimdi ise vendor komutunu kullanarak, Fortify dosyalarını publish etmemiz gerekiyor.
```
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
```
Şuan database/migration klasörü altında 4 adet migration oluşturulmuş olması gerekiyor. Bu migrationları veritabanına göndermek için tabiki de bir veritabanına ihtiyacınız var.
Veritabanınızı oluşturduktan sonra aşağıdaki kod yardımı ile migrationları veritabanınıza iletebilirsiniz.
```
php artisan migrate
```
Veritabanımız hazır olduğuna göre artık config klasörünün altındaki app.php dosyasına FortifyProvider'ı çağırabiliriz. Bunun için config/app.php dosyasındaki providers alanına aşağıdaki gibi fortifyı eklemeliyiz.
```
\App\Providers\FortifyServiceProvider::class,
```
Şimdi ise /login ve /register yollarını oluşturmamız gerekiyor. Bunun için FortifyServiceProvider.php dosyasının boot fonksiyoununa aşağıdaki kodları ekliyoruz.
```
Fortify::loginView(function (){
           return view('auth.login');
        });

        Fortify::registerView(function (){
            return view('auth.register');
        });
```
Buradaki 'auth.login' ve 'auth.register' yerine giriş yap ve kayıtol sayfalarınızın route isimlerini yazabilirsiniz.
|Middleware| Middleware: The Key to Express
Tags: javascript, html, css, webdev
Published: 2020-12-18 18:03:14

---
title: |Middleware| Middleware: The Key to Express 
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---


-Intro to Express Middleware 
-Using Morgan - Logger Middleware 
-Defining Our Own Middleware 
-Setting Up a 404 Route 


###Intro to Express Middleware 
Middleware are functions that run at some point during the request and response lifecycle. The functions run between the time a request enters express and by the time the response leaves and the code stops executing. Each middleware function has access to the request object into the response object. 
Middleware can end the HTTP request by sending back a response with methods like res.send() or middleware can be chained together one after another 

The main job of the middleware is to parse the incoming body of the request and add it to the request object. 

###Using Morgan - Logger Middleware 
https://github.com/expressjs/morgan

Morgan - is a simple logger that helps log HTTP requests information to our terminal. Very useful when debugging things. 


###Defining Our Own Middleware 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/peh7rqahh17dwb0ffppw.png)

```javascript 

app.use(morgan('common'))
app.use((req, res, next) => {
 console.log('This is the first middleware!')
 next(); 
})


app.use(morgan('common'))
app.use((req, res, next) => {
 console.log('This is the second middleware!')
 next(); 
})

```
the next() statement is there to keep the code moving forward, otherwise the code would end after the console.log statement. 


###Setting Up a 404 Route 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xcsb8q0g9b0vj31evp2b.png)

```javascript 

app.use((req, res, next) => {
  req.requestTime = Date.now(); 
  console.log(req.method, req.path); 
  next(); 
}) 

app.use((req, res) => {
 res.status.(404).send('Not Found')
})

```
Javascript Array Basics
Published: 2020-12-18 17:44:17

Recently I was asked to make a 5 minute video teaching someone about javascript arrays and objects. They wanted the material presented to a person who just started to learn how to code. I started to think about what I wanted to present in just 5 minutes. I came to the realization that there is SO much more to javascript arrays when you are starting out as a beginner than you realize after using them for awhile. I decided to start with the very basics.

An array in javascript is a numbered list or a collection of items. It can be very beneficial to have when it comes time to iterate through all of your values compared to creating an individual variable for each value you have. 

Using array literals is one of the easiest ways to create a new array. That looks like this:

``` let variableName = [ "value1", "value2", "value3" ]```

Another way to create a new array is by using the javascript keyword Array.

``` let variableName = new Array( "value1", "value2", "value3")```

I think it's important to note that while I was using strings to create the values of my arrays you also have the option to use pretty many any of the other datatypes. 

The next step after learning how to create an array is to learn how to access the different values in that array. This leads to another important note for beginners. You might look at the array list and assume that "value1" is going to be the first index on the list, however programmers like to start counting with zero. So it's important to know that every list item you see matches the index that is one less than its place on the list. Now that we have that out of the way here is how you access those values. 

Let's say we want to access the 2nd index of our array we made earlier. We would write it like this:

``` variableName[2] ```

This would return back to use "value3", as that is our current value as the 2nd index (or 3rd item in our list).

Those are some of the very basics to javascript arrays. If you'd like to learn more, stay tuned for my next blog. Where I'll be going over some of the properties of arrays and shifting around indexes of an array. 

Thanks for reading!
Where do I feature my dev tool start-up?
Published: 2020-12-18 16:47:00

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mipee3vokkbwofdkntpz.png)

I'm looking for places where I could feature my start-up. Here is our website: https://www.glue.codes. In short, we are low-code platform for developing interactive web frontends faster and simpler. It’s a tool for full stack developers who find frontend overcomplicated. Instead of going all over drag & drop, we let you code basics (as when web dev use to be just about HTML, CSS, and JavaScript) and underneath all the complex stuff is just happening for you. You code in a setup free online code editor with live preview. You are guided by live notifications which suggest what needs to be implemented next. Then, you can download scalable code which meets the newest web standards and either keep tinkering with it or build it with Webpack. At the end you'll receive production-optimised code that delivers excellent page-load time. We are at bootstrapping stage and we already have MVP. 

Can you advise/help?
What was your win this week?
Tags: discuss, weeklyretro
Published: 2020-12-18 17:40:32

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Happy Friday!


**Looking back on your week — what was something you're proud of?**

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Landing a new job
- Spending time with family... or whatever else might spark joy ❤️

---

Have a great weekend!

![Brad Pitt Happy Dance](https://media.giphy.com/media/Q8IYWnnogTYM5T6Yo0/giphy.gif)
Rapid development with JHipster and Vaadin - as simple as it sounds!
Tags: java, jhipster, vaadin
Published: 2020-12-18 17:12:21

Maybe it's too obvious, maybe it's too simple... Nonetheless, the lazy backend engineer that I am, I was looking for a solution to make my life as easy as possible when it comes to repeating tasks like implementing data models as well as building business UI (no fanciness, just a user interface to work with!).

## JHipster for backend generation

When it comes to generating data models and all the stuff related like repositories, service classes etc. I think JHipster is a quite fair solution.

## Vaadin for frontend implementation

Regarding UI building as a java developer Vaadin is amazing for it spares me all the communication handling between server and client while also supporting very advanced interface components.

## Combining them...

Bringing them both together is as simple as it can be. Create a JHipster application with the jhipster cli, add the Vaadin dependencies to the application _pom.xml_ and you are ready to go! Building UI classes with `@Route` annotations works out of the box.

Next step for me is to find out how to implement a useful authentication and authorization solution. My experiences will appear here soon.

P.S.: Though for now I am really happy with the "JHipster/Vaadin combo", feel free to suggest alternatives for backend generation / UI implementation! I am really interested to broaden the focus :-)
Shorten your feedback loop
Tags: frontend, feedbackloop
Published: 2020-12-18 17:08:44

---
title: Shorten your feedback loop
published: true
description: One of the key satisfiers in the development experience is knowing the results of your actions immediately.
tags: frontend, feedbackLoop
---

  One of the key satisfiers in the development experience is knowing the results of your actions immediately.
  That's why apart from the constant aim of simplifying everything as a software developer, there can be an aim of a constant shortening the feedback loop.

  A short feedback loop is a fundamental idea in some core programming practices, such as TDD.

  In the perspective of frontend development, here's what you can consider:

  **1. Shorten UI feedback during development.**

  Pay attention to the time it takes between the UI change in development mode and its reflection in the browser.
  Ensure you're leveraging [react-refresh](https://www.npmjs.com/package/react-refresh) and use proper [webpack devtool config](<https://webpack.js.org/configuration/devtool/>) if you're on this ecosystem.

  **2. Know how to simulate the state of the app, i.e. to stay on the same page on refresh during development.**

  With the growing complexity of the application, the number of states, in which this application can is growing as well.
  It is worth to consider a mechanism for state simulation, like [make your own dev tools](https://kentcdodds.com/blog/make-your-own-dev-tools/)
  so you can quickly jump to a certain app state, and/or stay in it during development.

  **3. Know how to Deploy the application on the test environment from your local machine.**

  Depending on your setup, this can save you from running build or test steps on CI just to quickly check some ideas.
  Even better: know how to simulate the test environment locally.

  **4. Know how to run and scope tests locally.**

  Rather than waiting on CI to check if the tests are green, know how to run your unit/integration tests and scope them to certain files/suits for faster outcomes.

  **5. Know how to test things without redeploying the app.**

  Sometimes, to validate ideas, there's no need to deploy the app on a test environment - leverage browsers' devtools features like blocking API requests or local overrides. This way you got some answers to your questions immediately.

  **6. Ensure IDE assists you.**

  Seeing fast lint-check or type-check errors right in IDE gives you great (probably the fastest) feedback about potential problems. Make sure your lint & type-check solutions are integrated tightly with the IDE.

  For a delightful developer experience, speed of ideas validation is a key player for your mental health and sometimes sets the mood for the whole day. Make "shorten your feedback loop" a motto for your setups, don't be lazy to think about how can you validate ideas faster and enjoy your work even more.
Maximum subarray sum🤖
Tags: algorithms, javascript
Published: 2020-12-18 17:06:10

Subarray questions require looping through an array but with some extra logic/conditions which can make them challenging. However, I think this solution can be straightforward to understand as there are only a couple of conditions. 

This problem asks to find the biggest sum of consecutive numbers in the array:

```javascript
let nums = [ -3, 1, -4, 1, 2, 1]
// solution -> 4 ( from 1,2,1 subarray)
```

The approach, in this case, involves accumulating the sum of the numbers in the previous element, while we check for the highest sum between the new sum that includes the current element and the previous sum. So the first subarray `sum` would only be the first value of the array, which is used to accumulate the sum of the next elements.

```javascript 
sum = nums[0]
```

In the base case, there are no more elements to loop through so we just return the first element by skipping the loop.

But if there are more elements to loop over we start with the second element (index 1) until the end of the array. Starting at index 1 allows comparing the current element to the previous element from the first loop.

```javascript 
if (nums[i - 1] > 0) { 
// only if the previous accumulation sum (previous element) is positive
  nums[i] += nums[i - 1]; // accumulate current element by adding last to current
}
```

After we accumulate the sum of the previous elements in `nums[i]` and `nums[i-1]`, we can compare the current sum (`nums[i]`) to the highest sum (`sum`) so far.

```javascript
sum = Math.max(nums[i], sum)
```

In the first loop `sum` will be the first element of the array and after it will become the highest sum we found so far.

The whole algorithm:

```javascript
const maxSubArray = (nums) => {
    let sum = nums[0];

    for (let i = 1; i < nums.length; i++) { 
// starts at index one to compare and acculumate 

        if (nums[i - 1] > 0) { 
// if the accumulation sum is positive
            nums[i] += nums[i - 1]; 
// accumulate current element by adding current to last
        }

        sum = Math.max(nums[i], sum); 
        // save highest number either current sum of previous higher sum
    }
    return sum;
};
```

To review, we loop over the array and check to see if the previously accumulated sum is positive and if true add the current element. Last we compare the current sum to the highest sum so far with `Math.max` after we iterated over the whole array we return the answer: `sum`.

Feel free to reach out with any thoughts/ideas!

[At LinkedIn](https://www.linkedin.com/in/santiago-salazar-pavajeau/) [or twitter](https://twitter.com/santispavajeau)