teleren/devto huggingface dataset:
Stupid Bash! Stupid me! Comparing Strings in Bash
Tags: mistakes, debugging, beginners, codenewbie
Published: 2020-12-04 06:42:57

---
title: Stupid Bash! Stupid me! Comparing Strings in Bash
published: true
description: A stupid bug that took me a while to spot. 
tags: #mistakes, #debugging, #beginners, #codenewbie
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/g30fgnmauagjgik5acm9.png
---

I usually don't write bash scripts. If use the terminal often to run AWS ClI commands, but if I need logic or something a bit more complex I'd rather go for a tiny NodeJs file.

It feels more natural to me, more readable and [I can debug](https://dev.to/dvddpl/the-biggest-advice-i-could-give-to-another-developer-3jme) what is going _wrong_.

Sometimes though I have to touch old bash scripts used for continuous integration.  Like today. Well, it was actually a YAML file used to run GilabCI Pipelines, but [the job script contained a bash script](https://forum.gitlab.com/t/how-make-a-if-statement-in-the-ci-file/40088/2), that wasn't working.


```
if [$CI_PIPELINE_SOURCE == "schedule"] && [[ -z "$STAGE" ]]; then
 # collapsed multi-line command
```

This condition was giving an error, which was swallowed by the CI giving a successful job, but with an, of course, unexpected behavior.

```
27/bin/bash: line 118: [schedule: command not found
```

I remembered that there was something about **Single Brackets or double Brackets** so I immediately changed that to 

```
[[$CI_PIPELINE_SOURCE == "schedule"]]
```

Nope.

Then I remembered there was something about **Wrapping Variables in Quotes** therefore I changed to 

```
[["$CI_PIPELINE_SOURCE" == "schedule"]]
```

Nope.

I checked [the docs](https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html) and [Stackoverflow](https://stackoverflow.com/a/2237103)
[After googling](https://dev.to/dvddpl/often-your-solution-is-one-more-google-search-away-574a) and trying to mix and match, Single Equal / Single Equals / Quotes in every possible allowed combination I was left staring at the script and at the StackOverflow example for a while. **Until it struck me.**

The space. 

T h e      f r e a k i n g      **m i s s i n g    s p a c e**

```
if [[ $CI_PIPELINE_SOURCE  == "schedule" ]] && [[ -z "$STAGE" ]]; then
```

![tableflip](https://media.giphy.com/media/2mG3TDbUTFY5UznyjS/giphy.gif)


I just repropose here the [Stackoverflow explanation](https://stackoverflow.com/a/2237103) as my own reminder

## = || == ?

Bash allows == to be used for equality with [ (but this is not standard)

![single or double equals?](https://dev-to-uploads.s3.amazonaws.com/i/sj6uxzis37rg07tbdc8j.png)


## To quote or not to quote?
Always wrap your variables with quotes, because if it is empty, your Bash script would encounter a syntax error. (_Not because it would try to compare something with a null value, but because the syntax itself would be kind of broken._)

![invalid equality](https://dev-to-uploads.s3.amazonaws.com/i/tu9frrw5y109z6qll6a1.png)


Hope it helps.
Hactoberfest 2020 Badge 
Tags: hacktoberfest
Published: 2020-12-04 06:19:02

Happy to share that I have received my hacktoberfest 2020 Challenge Badge. This is my first ever hacktoberfest participation, and it was really helpful for me to explore and contribute to open source projects.

Hacktoberfest is really great platform, contributing to open source projects is a great way to improve your skills, gain confidence, and practice coding.
File Test Operator | Shell Scripting 
Tags: linux, tutorial, beginners, devops
Published: 2020-12-04 06:01:09

**This is a multipart blog article series where I am going to explain the concepts of shell scripting and how to write a shell script in Linux, UNIX or Mac based systems. You can also follow this tutorial blog using windows but for that you have to install a bash from.**

_In this article we will see, that how can we check different properties related to a file._

1. If we want to keep the cursor on the same line after printing the echo command, we can do this by `echo –e “Enter any thing : \c”`. Here `\c` is being used to keep the cursor on the same line and if we do not use `–e` flag after echo then `\c` will also get printed on the screen, and the cursor will go in the next line.
2. If we want to check the file exist or not then in `if condition` we can use `-e` flag for it.
3. Similarly `-f` flag is used in `if condition` to check, that if file exist and is it regular file or not.
4. In the same way if we want to check for the directory we can use `-d` flag in `if condition`.
5. There are two types of file `block special` and `character special`
    - Block special file is the file which consists of binary data, pictures, videos etc.
    - Character special file is the file which consists of characters, some data or code.
    - To check it the file is block special we can use `-b` flag in `If condition` and to check for character special file we use `-c` in if condition.
6. If we want to check that whether the file is empty or not then we use `-s` flag 
7. If you want to check that file has read permission then use `-r` flag. If you want to check that file has write permission then use `-w` flag, and if you want to check that whether the file has execute permission or not then use `-x` flag.

[Practical code file related to this article](https://github.com/rahulMishra05/shell-scripting/blob/main/video6.sh)

_So, this was all about file test operator. Hope you liked it and learned something new form it._

If you have any doubt, question, quires related to this topic then or just want to share something with me, then please feel free to contact me. 

### 📱 Contact Me

[Twitter](https://twitter.com/r_mishra10)
[LinkedIn](https://www.linkedin.com/in/rahul-mishra-66210b185)
[Telegram](https://t.me/rahul_mishra10)
[Instagram](https://www.instagram.com/rahul_mishra10/?hl=en)

### 📧 Write a mail
<rahulmishra102000@gmail.com>

#### 🚀 Other links

[GitHub](https://github.com/rahulMishra05)
[HackerRank](https://www.hackerrank.com/rahulmishra10201)
Advent of Code 2020 - Day 3
Tags: adventofcode, python
Published: 2020-12-04 05:52:00

Here is my solution to Day 3:

```python
from typing import Tuple

with open('input.txt') as file:
    input = file.readlines()

puzzle_input = [line.strip() for line in input]

two_d_array = []
for line in puzzle_input:
    two_d_array.append([char for char in line])

horizontal_length = len(two_d_array[0])
vertical_length = len(two_d_array)

slopes = [
    {"horizontal_shifts": 1, "vertical_shifts": 1},
    {"horizontal_shifts": 3, "vertical_shifts": 1},
    {"horizontal_shifts": 5, "vertical_shifts": 1},
    {"horizontal_shifts": 7, "vertical_shifts": 1},
    {"horizontal_shifts": 1, "vertical_shifts": 2},
]

def over_three_down_one(
    current_row: int,
    current_column: int,
    horizontal_shifts: int,
    vertical_shifts: int) -> Tuple[int, int]:

    current_row += vertical_shifts
    current_column += horizontal_shifts
    if current_column > (horizontal_length - 1):
        current_column = (current_column%horizontal_length)
    return current_row, current_column

def traverse_slope(horizontal_shifts: int, vertical_shifts: int) -> int:

    current_row = 0
    current_column = 0
    tree_collisions = 0

    while current_row < vertical_length - 1:
        current_row, current_column = over_three_down_one(
            current_row,
            current_column,
            horizontal_shifts,
            vertical_shifts)
        if two_d_array[current_row][current_column] == '#':
            tree_collisions += 1

    return tree_collisions

answer = 1
for slope in slopes:
    answer *= traverse_slope(slope['horizontal_shifts'], slope['vertical_shifts'])

print(f'Answer: {answer}')
```

You can also view my solution on my [GitHub](https://github.com/njbrunner/adventOfCode/tree/main/2020/day_3).

Did you solve it differently?
Advent of Code 2020 - Day 2
Tags: adventofcode, python
Published: 2020-12-04 05:48:00

Here is my solution for Day 2:

```python
with open('input.txt') as file:
    input = file.readlines()

puzzle_input = [line.strip() for line in input]

# First Challenge
valid_passwords = 0

for item in puzzle_input:
    split_item = item.split()
    min = int(split_item[0].split('-')[0])
    max = int(split_item[0].split('-')[1])
    letter = split_item[1].replace(':', '')
    password = split_item[2]

    occurances = password.count(letter)
    if occurances >= min and occurances <= max:
        valid_passwords += 1

print(valid_passwords)

# Second Challenge
valid_passwords = 0

for item in puzzle_input:
    split_item = item.split()
    first_position = int(split_item[0].split('-')[0])
    second_position = int(split_item[0].split('-')[1])
    letter = split_item[1].replace(':', '')
    password = [char for char in split_item[2]]

    if password[first_position-1] == letter:
        if password[second_position-1] != letter:
            valid_passwords += 1
    elif password[second_position-1] == letter:
        valid_passwords += 1

print(valid_passwords)
```

You can also view my solution on my [GitHub](https://github.com/njbrunner/adventOfCode/tree/main/2020/day_2).

How did you solve today's challenge?
Advent of Code 2020 - Day 1
Tags: adventofcode, python
Published: 2020-12-04 05:45:43

Here is my solution for Day 1:

```python
with open('input.txt') as file:
    input = file.readlines()

puzzle_input = [int(line.strip()) for line in input]

for i in range(0, len(puzzle_input)):
    for j in range(i+1, len(puzzle_input)):
        for k in range(j+1, len(puzzle_input)):
            if (puzzle_input[i] + puzzle_input[j] + puzzle_input[k] == 2020):
                print(f'Answer: {puzzle_input[i]*puzzle_input[j]*puzzle_input[k]}')
```
You can also view my solution on my [GitHub](https://github.com/njbrunner/adventOfCode/tree/main/2020/day_1).

How did you do?
Built in String Functions in SQL
Tags: sql, mssqlserver
Published: 2020-12-04 05:36:12

Built in string functions in sql server 2008
Functions in SQL server can be broadly divided into 2 categories
1. Built-in functions
2. User Defined functions

There are several built-in functions. we will look at the most common string functions available.
ASCII(Character Expression) - Returns the ASCII code of the given character expression.
To find the ACII Code of capital letter 'A'

Example: Select ASCII('A')
Output: 65

CHAR(Integer_Expression) - Converts an int ASCII code to a character. The Integer_Expression, should be between 0 and 255.
The following SQL, prints all the characters for the ASCII values from o thru 255

Declare @Number int
Set @Number = 1
While(@Number <= 255)
Begin
 Print CHAR(@Number)
 Set @Number = @Number + 1
End

Note: The while loop will become an infinite loop, if you forget to include the following line.
Set @Number = @Number + 1

Printing uppercase alphabets using CHAR() function:
Declare @Number int
Set @Number = 65
While(@Number <= 90)
Begin
 Print CHAR(@Number)
 Set @Number = @Number + 1
End

Printing lowercase alphabets using CHAR() function:
Declare @Number int
Set @Number = 97
While(@Number <= 122)
Begin
 Print CHAR(@Number)
 Set @Number = @Number + 1
End


Another way of printing lower case alphabets using CHAR() and LOWER() functions.
Declare @Number int
Set @Number = 65
While(@Number <= 90)
Begin
 Print LOWER(CHAR(@Number))
 Set @Number = @Number + 1
End

LTRIM(Character_Expression) - Removes blanks on the left handside of the given character expression.

Example: Removing the 3 white spaces on the left hand side of the '   Hello' string using LTRIM() function.
Select LTRIM('   Hello vishal')
Output: Hello vishal

RTRIM(Character_Expression) - Removes blanks on the right hand side of the given character expression.

Example: Removing the 3 white spaces on the left hand side of the 'Hello   ' string using RTRIM() function.
Select RTRIM('Hello Vishal  ')
Output: Hello vishal

Example: To remove white spaces on either sides of the given character expression, use LTRIM() and RTRIM() as shown below.
Select LTRIM(RTRIM('   Hello   '))
Output: Hello

LOWER(Character_Expression) - Converts all the characters in the given Character_Expression, to lowercase letters.

Example: Select LOWER('CONVERT This String Into Lower Case')
Output: convert this string into lower case

UPPER(Character_Expression) - Converts all the characters in the given Character_Expression, to uppercase letters.
Example: Select UPPER('CONVERT This String Into upper Case')
Output: CONVERT THIS STRING INTO UPPER CASE

REVERSE('Any_String_Expression') - Reverses all the characters in the given string expression.
Example: Select REVERSE('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
Output: ZYXWVUTSRQPONMLKJIHGFEDCBA

LEN(String_Expression) - Returns the count of total characters, in the given string expression, excluding the blanks at the end of the expression.

Example: Select LEN('SQL Functions   ')
Output: 13




-----------------------------Thank You---------------------------
Effective Java! Use Varargs Judiciously
Tags: java, effective, varargs, architecture
Published: 2020-12-04 05:30:18

---
title: Effective Java! Use Varargs Judiciously
published: true
description: A dive into chapter 53 of Effective Java
tags: java, effective, varargs, architecture
series: Effective Java Review
canonical_url: https://blog.scaledcode.com/blog/effective-java/judicious_varargs/
---

A varargs parameter is a syntactic sugar feature of Java that allows you to define a parameter that allows the caller to provide zero or more arguments of the defined type. Inside the receiving function these values are provided as an array of the specified type. 

Let's look at a quick example:
```java
static int sum(int... args) {
  int sum = 0;
  for (int arg : args) {
    sum += arg;
  }
  return sum;
}
```

This method can be called like `sum(1,2)` which of course would produce `3` or `sum(1,2,3)` which of course would produce `6` or even `sum()` which would produce `0`. 

This capability can be of great use but there are some problem areas when using varags. Let's consider some of them and how we might overcome the challenge. 

Sometimes you may want to have a minimum number of parameters that you want to accept. As pointed out above, varags by itself allows 0 to n parameters to be passed in. We could consider checking the size of the array at runtime. While this would work it does have the downside of errors being found at runtime not compile time. This solution can also be ugly and gets in the way of the true logic. There is a better way though. Consider if we wanted to take a minimum of one argument. The solution to this would be to give our method two parameters. One simply of the type and the second as the vararg parameter. This would force the caller to provide at least one parameter at compile time. That may look something like:

```java
static int min(int firstValue, int... restOfValues) {
  int currentMin = firstValue;
  for (int value : restOfValues) {
    if ( value < currentMin) {
      currentMin = value;
    }

  }
  return currentMin;
}
```

Another potential pitfall of using vararg parameters is in performance critical applications. The reason for this is every method call requires the creation of an array. If this occurs on a loop this can produce avoidable memory pressure that can hurt the performance of your application. A possible mitigation strategy to this is, if for example 95% of the callers of the function will include 3 or less parameters you can create three functions that take 1, 2, and 3 parameters of the argument type to handle the 95% and a fourth that takes three parameters and a vararg parameter to handle the rest of the 5%. This is what the `EnumSet` object does to help it keep its great performance. Many times this optimization won't be appropriate but in the cases it does it can be a lifesaver. 

In summary, varargs parameters are a useful feature as part of the Java language. As with all features there are some rough edges to this feature that we should be aware of. However, as we keep these things in mind we can make some great improvements to our code.
How to create a bootable flash drive with command prompt(cmd)
Tags: windows, cmd, bootableflashdrive, format
Published: 2020-12-04 05:12:46

In order to install windows to a computer that no DVD ROM, you need to prepare a bootable flash drive for that.

### Formatting the flash drive
First of all, plug-in a flash drive with a minimum of 4GB of capacity. Now, go to windows explorer, right-click on your flash drive and format it in a regular way.

### Create a partition in the command prompt

Next, you have to set up your flash drive to make it a bootable drive. To do that, you have to open your command prompt with *Run as administrator*. And then, type the following command in your cmd.

```
diskpart
```
This opens the diskpart.exe program. Now type,
```
list disk
```
And hit enter. This command shows information about all the drives that are connected at the time. Now you have to identify your flash drive with its capacity and remember its disk number. (eg: Disk 1)
![List disk results](https://dev-to-uploads.s3.amazonaws.com/i/odna0knyn7ma3u9e7rff.png)

Then, type the following command and hit enter.
```
select disk 1
```
This will show a message that “Disk 1 is now the selected disk.” Now you have to remove the default setting in your flash drive. Type,
```
clean
```
and hit enter. This will show the message “DiskPart succeeded in cleaning the disk.”
![clean result](https://dev-to-uploads.s3.amazonaws.com/i/re2aoj1zjlb5p6cwj5m4.png)

To create a bootable disk, you need to have a separate partition for that. For that, type
```
create partition primary
```
and hit enter. This will show “succeeded in creating the specified partition.” Now you need to select the partition. For that, type,
```
select partition 1
```
and hit the enter key. This shows “Partition 1 is now selected partition.” message. Now you have to make that partition active. Type,
```
active
```
This will show you “DiskPart marked the current partition as active.”
![active results](https://dev-to-uploads.s3.amazonaws.com/i/1tw9bzemjzlt1e3vqe0i.png)

### Formatting the partition
Now, you need to format the partition as suitable. In order to do that, Type,
```
format fs=fat32 quick
```
and enter. Now, flash drive will be formatted, then shows “100 percent completed” and “DiskPart success fully formatted the volume.”

Now you have to assign a dive letter to the flash drive. Type,
```
assign
```
and enter. This will show the message “DiskPart successfully assigned the drive letter or mount point.” 
![assign results](https://dev-to-uploads.s3.amazonaws.com/i/2bxu6jc99qo5rzbe4eg5.png)
Now you are done with the command prompt and you can close it by typing `exit` and hit enter.
Now, you are almost done! :)

### Copy the setup files
This is the last step of the process. You need to copy all the windows installation files to your flash drive.

Now you can install windows to a computer using this flash drive.
Binary Search Tree in cpp
Tags: cpp, beginners, computerscience
Published: 2020-12-04 05:07:43

```cpp
#define COUNT 10  
struct node
{
    int data;        
    node *left,*right;
};
node *p,*root,*l;
void push()
{
    int x;
    cin>>x;
    p=new node;
    if(root==NULL)
    {
      p->data=x;
      p->left=NULL;
      p->right=NULL;
      root=p;
    }
    else
    {
           p=root;
                 while(p!=NULL)
              {
              if(p->left==NULL && p->data >x)
              {
                  l=new node;
                  p->left=l;
                  l->data=x;
                  l->left=NULL;
                  l->right=NULL;
                  break;
              }
              else if(p->right==NULL && p->data <x)
              {
                  l=new node;
                  p->right=l;
                  l->data=x;
                  l->left=NULL;
                  l->right=NULL;
                   break;
              }
                 else if(p->data > x)
                 {
                     p=p->left;
                 }
                 else 
                 {
                   p=p->right;
                 }

              }
       }
}
void print2DUtil(node *root, int space)  
{  
    if (root == NULL)  
        return;  
    space += COUNT;  
    print2DUtil(root->right, space);  
    cout<<endl;  
    for (int i =  COUNT; i < space; i++)  
        cout<<" ";  
    cout<<root->data<<"\n";  
    print2DUtil(root->left, space);  
}  
  
 
void print2D(node *root)  
{  
    print2DUtil(root, 0);  
}  
int main()
{
    root=NULL;
    push();
    push();
    push();
    push();
    push();
    push();
    push();
    print2D(root);
     
}

```
My Journey from Vim to Emacs
Tags: vim, emacs, codenewbie
Published: 2020-12-04 04:59:48

# A Kingdom of Vim:Vimdom
I was a astute vim user for the last 5 years. I read hundreds of books on Vim and Neovim . Saw every last screencast of Drew Neil and worshipped Tim Pope and Junnegun . I followed closely with the neovim repository . Experimented with making my perfect neovim config . Tried Spacevim and multiple distributions of vim just for getting the feel of a complete config of vim . Spent atleast 5 hours per week on making Vim more efficient . 
## Living in the Vimdom.
The biggest thing that I hated was that I could not live in vim. I tried living in the terminal so that I could run my life from a terminal. Tried running st(terminal) as a the only root window in Xorg so that I could run every software inside Vim with the terminal emulator integrated into it. You could say I was mostly successfully . But there some thing's that always bugged me . Vim was implemented as a text editor it only succeeds as a text editor. The way everything is implemented it just makes sense for efficiency and speed. 
## My Views
After much thought I saw the idea behind Vim . It was not a text editor . It was a editing racer.It was build so that you just race through whatever you were editing.It was not build as a environment.It was not build as a way of life.It was build to fit in your life . Not become your life.
## A Forgotten Ruin.
I thought about using emacs as a text editor for a while and tried and failed to adopt it as a text editor multiple times . My pinky finger pained for multiple days after using emacs for a week.I could not imagine using it for my life. But I knew about Doom Emacs from Distrotube's video and decided to try it as a text editor.I failed again because of my habit to open everything in neovim by typing nvim in the terminal.I decided to move to vim again but I did not delete the Doom Emacs configuration.I just kept it in my home folder.
## A lost treasure.
Distrotube posted a video about how exwm could make Emacs your window manager.I was quite intrigued by that and decided to try it. So I installed Emacs Again but due to my Doom Emacs config already  there I was happy that I did not have to install anything.I just moved to ExWM.And after a  week of using it.I cannot tell how happy I am.The joy of using absolutely one software for everything is phenomenal.I don't think I would switch atleast for a few months.It has been a month since I have typed 'nvim' in a terminal.I have uninstalled everything except the base necessary and Emacs.I am writing this post in emacs.

## My Summary.
If you are not able to adapt to the Emacs world . It would be good to switch to EXWM as this forces you to literally live in emacs.I would tell that Emacs as a editor is not efficient and definately not speedy.But Hell Yeah!It is convenient for everything I do.

Drop you comments below on your editor journey. And let us discuss about it.