teleren/devto huggingface dataset:
Conditional Assignment in Bash
Tags: bash
Published: 2023-01-06 03:00:33

---
title: Conditional Assignment in Bash
published: true
date: 2022-06-19 22:49:47 UTC
tags: Bash
canonical_url: https://brandonrozek.com/blog/conditional-assignment-bash/
---

Many programming languages include an quick way to perform a conditional assignment. That is, assigning a variable with a value based on some condition. Normally this is done through a ternary operator. For example, here is how to write it in Javascript

```
age = 16;
ageType = (age > 18) "Adult": "Child";

```

The variable `ageType` is dependent upon the value of `age`. If it is above 18 then `ageType = "Adult"` otherwise `ageType = "Child"`.

A more verbose way of accomplishing the same thing is the following:

```
if (age > 18) {
    ageType = "Adult"
} else {
    ageType = "Child"
}

```

How do we do conditional assignment in Bash? One way is to make use of subshells and echoing out the values.

```
AGE_TYPE=$([$AGE -gt 18] && echo "Adult" || echo "Child")

```

A common programming feature called _short-circuiting_ makes it so that if the first condition (`[$AGE -gt 18]`) is false, then it will skip the right side of the AND (`&&`) expression. This is because`False && True` is always `False`. However, `False || True` is equal to `True`, so the language needs to evaluate the right part of an OR (`||`) expression.
Developing with Intention
Tags: beginners
Published: 2022-06-19 19:18:10

One of the things I've overlooked while learning software engineering in the past and up until recently is the incredible usefulness of maintaining systematic inventory of my knowledge. I realized this (quite painfully!) after diving back into programming after a 2-year hiatus. In short, my concern is with being able to answer with certainty: **What do I know?**

In designing my knowledge-tracking system, I'm still experimenting with finding the platform that works best for me, whether online, handwritten, or a combination of the two. But at this point, I'm not allowing the format to become a distraction or constraint. I've accepted that the "best" format is the one that allows me to unload the mental struggle of trying to keep track of all this information.

Here are the main areas I am tracking so that I learn and develop with intention:

* **Discovering** - These are new concepts and terms I have either actively or passively encountered through lessons, assignments, YouTube videos or elsewhere, which require me to dig deeper to properly grasp. I simply make a note of them for my upcoming study sessions.
* **Understanding** - These are concepts I often pull from the above. At any given time, there should not be too many concepts or terms in this category or else I am risking information overload. Each of these will likely require me to invest numerous hours in developing an app with them. I will also search sites like [LeetCode](https://leetcode.com/problemset/all/) for learning them through problem solving. 
* **Learned** - If I can correctly use and explain a concept or term, I consider that I have reached a proficient level in it and track it here. Keeping track of this helps me stay motivated and encouraged in my learning when I see how far along I’ve come... and to avoid the dreaded imposter's syndrome!
* **Toolkit** - These are my code snippets, recipes, and common refactoring patterns. This is all code that I understand but tend to come back to when considering how to solve certain problems.
Beautiful Masonry Gallery with Bootstrap and Unsplash Random Photos
Tags: javascript, css, showdev, codepen
Published: 2022-06-19 22:17:43

This beautiful gallery combines the Bootstrap framework with Masonry, Animate.css and random photos from Unsplash.

I needed an example for a client, where after each call to the gallery, a certain number of random images are loaded, and also the image sizes are determined randomly.

What could be more obvious than tapping into an image database, I thought. While researching, I came across picsum.photos and their API.

**But first, here's the working example:**

{% codepen https://codepen.io/typo3-freelancer/pen/jOZRKLx  %}

[VIEW PEN IN FULLSCREEN MODE](https://codepen.io/typo3-freelancer/full/jOZRKLx)

## What happens under the hood?

1. Load list with images in JSON format
2. Preload images with [ImagesLoaded](https://github.com/desandro/imagesloaded), then hide preloader
3. Dynamically generate Bootstrap HTML with JavaScript
4. Set CSS classes for [Animate.css](https://animate.style/) with delay on each image
5. Put everything in a cool shape with [Masonry](https://masonry.desandro.com/)

## Pure Vanilla

No JavaScript library is used for the gallery. Everything is 100% JavaScript. For me personally, jQuery has had its day anyway.

## No additional CSS so far...

So far, no additional CSS has been used, except for a few small inline styles to control the animations. Imagine what you can do with this gallery and some extra CSS! You could make it look really cool, and add a lightbox if you want.

---

## Libraries I have used, with great thanks to the respective developers

### Bootstrap 5 Framework
https://getbootstrap.com/

### ImagesLoaded
https://github.com/desandro/imagesloaded

### Masonry
https://masonry.desandro.com/

### Animate.css
https://animate.style/

### Picsum Photos
https://picsum.photos/

---

## Your feedback is appreciated

If you like this **Bootstrap Masonry Gallery** PEN, feel free to leave your feedback. Also, I'm always very happy when others can use my work as the basis for great projects.

**What would you improve, add, or do differently?**

---

## More Stuff

### Sign up for my Newsletter!
https://simonkoehler.com/newsletter

### PHP Developer
https://simonkoehler.com/php-developer

### TYPO3 Freelancer
https://simonkoehler.com/typo3-freelancer
How to solve Problem with date method in the Yii2?
Tags: yii22
Published: 2022-06-19 21:45:28

0


Have timestamp for the task in the MySQL - 1654423473. https://babyapk.com/genshin-impact-mod-apk/ correctly transforming this timestamp into the GMT: Sunday, 5 June 2022 г., 10:04:33. That is date of task creation. Using this Yii2 method I outputting this data in the view - ` public function getWasOnSite() {

    $timePeriod = strtotime('now') - strtotime($this->dt_add);
    return \Yii::$app->formatter->asDuration($timePeriod);
}
` And expecting some days, minutes, etc, but seeing this -1450 years, 11 months, 30 days, 17 hours, 3 minutes, 45 seconds ago

How to remake into the correct variant?
Flask Mail Type Error: missing 1 required positional argument: 'message' on Mail.send(msg)
Tags: flask, webdev
Published: 2022-06-19 21:39:12

0


Getting this error "TypeError: _MailMixin.send() missing 1 required positional argument: 'message'" when trying to email a forgot password message via flask-mail. Feel like I'm following the model to a tee, but I'm obviously missing something.

Here is the relevant code:

Init.py

app.config['MAIL_SERVER']='smtp.mailtrap.io'
    app.config['MAIL_PORT'] = 2525
    app.config['MAIL_USERNAME'] = 'e1f8a312670b7d'
    app.config['MAIL_PASSWORD'] = '7a56dfdd316300'
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USE_SSL'] = False
    mail = Mail(app)
models.py

class User(db.Model,UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique = True)
    password = db.Column(db.String(150))
    username = db.Column(db.String(150))
    birthdate = db.Column(db.Date)
    gender_id = db.Column(db.Integer)
    createDate = db.Column(db.DateTime(timezone = true),default = func.now())
    token = db.Column(db.String(32), nullable=False, unique=False)
    notes = db.relationship('tbl_note')
views.py The code is failing on the line mail.send(msg)

if request.method =="POST":
        user = User.query.filter_by(email = form.email.data).first()
        if user:
            #generate new token
            token = str(uuid4()).replace('-','')
            #update user token in db
            user.token = token
            db.session.add(user)
            db.session.commit()
            link = 'http://' + getenv('DOMAIN') + url_for(
                    'update_password',
                    email=my_user.email, token=token)
            msg = Message('Password Reset Request',
                  sender='noreply@demo.com',
                  recipients=[user.email])
            msg.body = 'To reset your password, visit the [following link](https://apkhobby.com/total-conquest-mod-apk/): ' + link +              
            '. If you did not make this request then simply ignore this email and no changes will be made.'
           
            Mail.send(msg)
            flash('We have sent an email to change your password. [Please check](https://apkhobby.com/total-conquest-mod-apk/) your Spam folder if not found.', category = 'success')
            return redirect(url_for('auth.login'))
How can I subtract from inventory using Stripe Elements
Tags: stripe
Published: 2022-06-19 21:34:03

0


I was using a pre-SCA Stripe integration in my webapp that used Checkout. The flow basically:

Did \Stripe\Order::create against a selected SKU and quantity so that I ensured that inventory was [still available](httpS://minimilitiaapkmod.net/) (for products with 'finite' quantity)

Then an \Stripe\Order::retrieve and $order->pay using the token passed back to me by Checkout in the client.

I've rebuilt my integration with an SCA-compliant flow, now with Stripe Elements, for a better UX.

However, I don't see how I can check against inventory when using Elements. There doesn't seem to be a way to use Elements with a similar Order, Retrieve, Pay flow.

Can anyone that's got a similar Elements based integration point me toward how to making sure I don't oversell products with limited quantity.

TIA.
Day 72: The walking day (fun)
Published: 2022-06-19 21:09:24

Hi!
So today was fun! much fun! I had a chance to meet my friends and some of people that I haven't seen in a long time. Yesterday I had a plan to take rest from work but today  I was hesitating and I wanted to call off a meet up I had with a friend until another friend came at home to pick me up. so I was meeting people from then (sounds funny hahah!). 
now I'm so tired so I will be making the Week plan tomorrow and get ready Figma designs for tomorrow's demo.

Signing off...
Data Structures 101: Introduction to Data Structures and Algorithms.
Tags: beginners, algorithms
Published: 2022-06-19 20:58:12

**A data structure** is a particular way of organizing data in a computer so that it can be used effectively.As developers, we must have good knowledge about data structures as it is a key topic when it comes to Software Engineering interview questions.
The most commonly used data structures include;

1. Arrays
2. Linked lists
3. Stack
4. Queues

## Algorithms
An Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. They are normally independent of any programming language, as they can be implemented in more than one programming language.

### Characteristics of a good algorithm 

1. Input − should have 0 or more well-defined inputs.
2. Output −should have 1 or more well-defined outputs, and should match the desired output.
3. Finiteness − they must terminate after a finite number of steps.
4. Feasibility − Should be feasible with the available resources.
5. Independent − should be independent of any programming code.
6. Unambiguous − Each of its steps, and their inputs/outputs should be clear and must lead to only one meaning.

### Example of an algorithm

Algorithms are mostly writen in a step by step manner. For example, an algorithm to ad two numbers would look something like this

```
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values for num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum=num1+num2
Step 5: Display sum
Step 6: Stop
```

That is the basic introduction to algorithms, of course this is a much deeper topic which we will continue to explore. Till next time, happy coding✌!
[Conceito] - Hash vs Criptografia: Não Confunda os Dois
Published: 2022-06-19 20:14:44

> Conteúdo original [nessa thread do Twitter](https://twitter.com/zanfranceschi/status/1538614925739773952)

---

Ei dev,

Thread expressa: não confunda "fazer o hash" com criptografar  (apesar de hash ser uma forma de criptografia).

cc @sseraphini

↓

![img](https://pbs.twimg.com/media/FVpCHpXUUAAF_sI?format=png&name=small)

---

Já vi frequentemente devs usarem os termos "fazer o hash" e "criptografar" sem distinção.

Pega uma explicação super simplificada aqui em baixo pra entender a diferença ↓

---

Hash:

A gente faz o hash pra algo que não queremos reverter ─ algo como ~unhash~ não existe.

Por exemplo, devemos guardar senhas de usuários nos bancos depois de terem passado por uma função hash e usá-las mais ou menos como no pseudo código aqui pra verificá-las.

![img](https://pbs.twimg.com/media/FVpCIIeVEAIOAEU?format=jpg&name=900x900)

---

Criptografar:

Você criptografa algo quando quer transportar e/ou armazenar de forma segura e deseja poder descriptografar essas informações posteriormente. Ou seja, reverter o formato criptografado. Algo como no pseudo código aqui.

![img](https://pbs.twimg.com/media/FVpCIggVIAAnZGW?format=jpg&name=small)

---

Não vou entrar em muitos detalhes, mas só pra você ir atrás caso goste do assunto, existem duas formas de criptografia: assimétrica e simétrica. E esses termos têm a ver com como você criptografa e descriptografa as informações ─ usando uma chave para tudo ou duas.

---

Na forma simétrica você usa a mesma chave tanto para criptografar quanto pra descriptografar.

Na forma assimétrica você usa uma chave pra criptografar e outra pra descriptografar ─ chaves privada e pública respectivamente.

---

Era isso que tinha pra falar. Queria mais é desmistificar esses dois termos mesmo. Estou longe de ser um expert no assunto, mas a vida me obrigou a conhecer o básico sobre ele.

Obrigado se leu até aqui! 💕
INTRODUCTION TO DATA STRUCTURES AND ALGORITHIMS.
Tags: programming, python, opensource, github
Published: 2022-06-19 20:00:19

**_INTRODUCTION_.**
_Data_ - Data can be defined as facts or figures, or information that's stored in or used by a computer.

_Structures_ - A structure is used to represent information about something more complicated than a single number, character, or Boolean can do.

Therefore data structures are a way of collecting and organizing data in such a way that we can perform operations on data. Some of the examples that we know include graphs, trees and linked lists.

**_Types of Data Structures_**
Linear Data Structures - Items are arranged in a sequence. Example: Array
Non-linear - Data items are not arranged in a sequence. Example: Tree, Graph
Dynamic - It expands or shrinks depending on the program requirements
Static - Are those whose size and structures associated memory locations are fixed.
Algorithms - They are a set of instructions(finite or logical) that are used to solve a problem
Algorithms are said to be efficient and fast when they take less time to execute and consume less memory.

**_Properties of an Algorithm_**
Input
Output
Finiteness
Definiteness
Correctness
An algorithm generally requires the following components:

_Instruction Space_: A space to store the the executable version of the program.
_Data Space_: Space required to store the constants and variables.
_Environment Space_: Stores the environment information.

Data Structures and Algorithms come in handy in problem solving.
A problem can be described as something that has an initial state, goal state and the number of steps taken to achieve from the initial to goal state.
Introduction to Open Source
Tags: beginners, opensource, community, computerscience
Published: 2022-06-19 19:55:16

_Open source_ is more about the people. The people make the community and the community makes collaboration possible.

- Contributing to open source helps one grow their skills as well as  build their network .
- One of the major motivations to contribute to open source is the impact that the contribution makes to the community and all the user base.
- Open Source programs help you gain practical knowledge and the fact one get's to connect with some great people also ensures that they never lack mentorship.
- Being a part of the Open Source Ecosystem, one learns to Communicate, to Collaborate and to asynchronously work with their peers.
- Don't be afraid to make mistakes. One can always ask questions from the community (without feeling like an imposter).
- Once a person gets a bit familiar to open source contributions, they should try to pass on the knowledge  and creating a happy place for  fellow contributors.
- Non-code contributions are equally important .
- While choosing an open source project to contribute to, it is important to self-evaluate and understand your interests.

Don't wait, go ahead and make your first contribution. _All the best!!_
I wrote a free book on React
Tags: react, book, testing, patterns
Published: 2022-06-19 19:47:56

---
title: I wrote a free book on React
published: true
description: This is a free book I'm constantly updating
tags: react, book, testing, patterns
---
![](https://thepracticaldev.s3.amazonaws.com/i/7o4gsvz5cl0xn5oeg3s9.jpg)

Follow me on [Twitter](https://twitter.com/chris_noring), happy to take your suggestions on topics or improvements /Chris

I'm writing a free book on React, it will always be free :)

## Links

- [Book link](https://softchris.github.io/react-book/#/)
- [GitHub repo](https://github.com/softchris/react-book) in case you want to contribute

### Video course

It's also available as a video course (just started, but please comment in you're excited about seeing more parts)

{% embed https://www.youtube.com/watch?v=0MZ2MkPCk1Q %}

## Content

Hope you enjoy it :)

It covers:
- Basics
- Forms
- Routing
- Testing
- Redux

A lot of my articles here is based on things I wrote in the book. Hope it can help someone :)
Biggest CSS Mistakes to avoid
Tags: css, codenewbie, beginners
Published: 2022-06-19 19:22:59

<!-- wp:paragraph {"imagePinMeta":{}} -->
<p>If you're not a fan of CSS, or if you're brand new to front end coding, you might run the risk of making needless errors when you're developing the styling of your products. Learn the biggest CSS mistakes to avoid and how to prevent them, and even how to fix them when you find them.</p>
<!-- /wp:paragraph -->

_**Links in this post will forward you to a longer, 14 minute, informative blog post.**_

<!-- wp:heading -->
<h2 id="h-why-do-i-need-to-learn-this-i-hate-css">Why do I need to learn this? I hate CSS.</h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"imagePinMeta":{}} -->
<p>If you hate CSS, trust me when I say, the rest of us can tell.  Regardless of your feelings on the language, best practices should always be followed, and CSS can be pretty cool actually.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"imagePinMeta":{}} -->
<p>We need to know these things because Web Development is all about building on top of others' code.  CSS is no exception, it is in fact designed to build upon itself.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"imagePinMeta":{}} -->
<p>Whether you're working with the latest supported version of a language, a new framework, or trying to make your product work with someone else's code; to scale you need a solid foundation.</p>
<!-- /wp:paragraph -->
<!-- wp:heading -->
<h2 id="h-let-s-get-right-into-the-biggest-css-mistakes-to-avoid">Let's get right into The Biggest CSS Mistakes to Avoid:</h2>
<!-- /wp:heading -->

<!-- wp:list {"imagePinMeta":{}} -->
<ul><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#h-not-relying-on-browser-defaults-with-your-html">Not relying on Browser Defaults with your HTML</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#sytax">Syntax &amp; Parsing Errors</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#relative-meas">Improper Use of Relative Measurements</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#floats">Don't Use Float Layouts</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#side-scroll">Avoid Side Scroll</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#state">Not styling State</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#color-contrast">Not testing Color Contrast</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#z-index">Position &amp; Z-Index</a></li><li><a href="https://allmaddesigns.com/biggest-css-mistakes-to-avoid/#important">Using !important - But is it?</a></li></ul>
<!-- /wp:list -->
Just released a FREE book on Go/Golang on LeanPub and GitHub
Tags: go, tutorial, beginners, programming
Published: 2022-06-19 19:12:39

---
title: Just released a FREE book on Go/Golang on LeanPub and GitHub
published: true
description: Here's a new free book on Go. You can either download it from LeanPub or read it online
tags: golang, tutorial, beginner, programming
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pq2dxu7ci22w25bjzt1b.jpg
---

Hey friends.

I just released a FREE book on Go. 

## Video course

> There's also a video format of this book currently being produced, check it out:

> {% embed https://www.youtube.com/playlist?list=PLRbYLREdOhfnLJl0xJxKEPe4BhlDU66Zj %}

## Where to get the book and what it contains

> Get it here, https://leanpub.com/go-from-the-beginning

It covers:

- **Fundamentals**, like data types, flow control and more.
- **Project management**, how to create your own projects, create and publish your own packages as well as consuming external packages.
- **Web development**. Learn how to create a Web API and work with JSON.
- **IO**, Work with files and directories.
- **Databases**. Reading and writing to a database.
- **Core libraries**. Work with core library packages like log, regex, strings and more.

> Get the PDF here, https://leanpub.com/go-from-the-beginning
> The repo is here, https://github.com/softchris/golang-book I welcome PRs.

> Instead of money, please consider donating to Ukraine.
- Here's one org that provides aid to Ukraine, [UNICEF](https://www.unicef.org/emergencies/war-ukraine-pose-immediate-threat-children)