Tuesday 28 April 2020

Prepend to every line in Visual Studio Code

Problem:

I want to add a string to the beginning of every line in a selection of code or text.

For example, I am reformatting what used to be a liquid templating list to a YAML list, e.g.

From:

item1
item2
item3

To:

  - item1
  - item2
  - item3


One solution - overview:

There are many ways to prepend to code quickly in bulk. One of the more versatile ways is by using the replace tool in Visual Studio Code combined with regex (i.e. regular expressions).

The "find" field will have the caret character ^ which indicates the beginning of a line. The "replace" field will have whatever you want to add at the beginning of lines.

Example:

For example, if I have the code in the screenshot below that I want to prepend the string " - " to:

First, select the code to prepend to:

Then invoke the "replace" tool:

Make sure you select the option to replace in your selection only. Then use a regex search for "^" as the beginning of a line, and replace with what you want to prepend. Do this for each line one by one until you have the results you desire.

After you are done, the lines should now be prepended with the desired string.



Notes:

There are many other ways that you can prepend lines in Visual Studio Code. The how-to above shows the regex replace method because it's a powerful tool that can handle many scenarios, not just prepending to lines.

Other methods may include installing plugins, using Visual Studio's multi-line cursor/select tools, etc.

References:

Friday 17 April 2020

How to fix notch overlap in Flutter Basic Widgets example code

Problem:

I am learning Flutter, and the app bar on top in the Basic Widgets section of the Introduction to widgets section of the Flutter docs is being blocked by the notch of an iPhone or phone simulator, as seen below. How can I fix this?

Notes:

This bug was confirmed in April 2020. It's possible that the Flutter team has updated their documentation by the time you are reading this. (If so, thank you Flutter team!)

Also note that this how-to is just one way to workaround the issue. The later code in the Flutter documentation shows better practices on which widgets to use, etc., to avoid the notch. That being said, this workaround is for anyone who is trying to debug this before moving on.

Workaround:

The workaround is highlighted below, followed by a brief explanation:

import 'package:flutter/material.dart';

class MyAppBar extends StatelessWidget {
  MyAppBar({this.title});

  // Fields in a Widget subclass are always marked "final".

  final Widget title;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 56.0, // in logical pixels
      padding: const EdgeInsets.symmetric(horizontal: 8.0),
      decoration: BoxDecoration(color: Colors.blue[500]),
      // Row is a horizontal, linear layout.
      child: Row(
        //  is the type of items in the list.
        children: [
          IconButton(
            icon: Icon(Icons.menu),
            tooltip: 'Navigation menu',
            onPressed: null, // null disables the button
          ),
          // Expanded expands its child to fill the available space.
          Expanded(
            child: title,
          ),
          IconButton(
            icon: Icon(Icons.search),
            tooltip: 'Search',
            onPressed: null,
          ),
        ],
      ),
    );
  }
}

class MyScaffold extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Material is a conceptual piece of paper on which the UI appears.
    return Material(
      child: SafeArea(
        // Column is a vertical, linear layout.
        child: Column(
          children: [
            MyAppBar(
              title: Text(
                'Example title',
                style: Theme.of(context).primaryTextTheme.title,
              ),
            ),
            Expanded(
              child: Center(
                child: Text('Hello, world!'),
              ),
            ),
          ],
        ),
      ), // SafeArea
    ); // Material
  }
}

void main() {
  runApp(MaterialApp(
    title: 'My app', // used by the OS task switcher
    home: MyScaffold(),
  ));
}

The above code encloses the other widgets in the example code within the safe area of the device via the SafeArea widget - a class that adds appropriate insets for a given device.

If all went well, your results should now look similar to the image below and you can now move on to learning more Flutter, free from the iPhone-notch-overlap.

If you'd like to learn more, please check out the references below.



References:

Wednesday 15 April 2020

Get the sitemap of Blogger and Blogspot blogs

Problem:

I want to get or generate the xml sitemap of my Blogger.com or Blogspot blog.

I am using these sitemaps for Google Search Console, Bing Webmaster Tools, and other webmaster tools.

Solution:

The good news is that blogger already generates these sitemaps for you. For your own blog, use the following pages at the root level of your blog's domain: "sitemap.xml" and "sitemap-pages.xml".

For example, this blog's URL is grammarofdev.blogspot.com, so its sitemaps can be found at

Now that you know your Blogger weblog's sitemap URLs, you can submit those URLs to the webmaster tools of your liking. For example, here's what the sitemaps above look like after being successfully submitted to Bing Webmaster Tools:



References:

1 way to add vertical rulers in Visual Studio Code

Problem:

How do I add vertical rulers in Visual Studio Code's editor views?

I want to add standard guide rulers at the 80 and 120 character columns.

Solution:

In VSCode 0.10.10 or newer:

  1. Open Settings
    (Windows: File→Preferences→Settings; OS X/MacOS: Code→Preferences→Settings)
  2. Search for "editor.rulers", then select to edit
  3. Add the number of columns the rulers should be at. For example, the classic standards of 80 characters and 120 characters are shown below:
  4. You should now see vertical rulers in your editor if done correctly and if your Visual Studio Code version is compatible. For older versions, restarting VSCode may be required to see the change.

Notes:

The solution above was tested to work on Visual Studio Code 1.44.0. Your results may vary in other versions.

References:

Monday 6 April 2020

bash scripting reminders of basics

Problem:

I want quick reminders for bash shell scripting because I don't write bash scripts often enough to memorize everything.

Notes:

The following reminders assume you're already familiar with the basics of bash shell scripting and simply need a reminder of more commonly used syntax, etc. These reminders are for myself but I hope you also find them useful.

Reminder shortcuts

As the number of reminders grow I hope this index will help you find what you need. (It certainly helps me.)



Reminders:

Top of script starts with #!/bin/bash

#!/bin/bash
See this tldp.org reference page for details.

Simple variables

Examples of simple variables

NAME="Delta"
echo "Hello $NAME!"

Concatenate strings


HELLO="Hello, "
NAME="Lily"

echo $HELLO$NAME
# output: Hello, Lily

HELLO="Hello, "
NAME="Alex"
GREET="${HELLO}${NAME}!"

echo "$GREET"
#output: Hello, Alex!


GREET="Hello, "
GREET+="Ninja"

echo "$GREET"
#output: Hello, Ninja

String quotes of bash scripting

DIRECTION="Right"
echo "Turn $DIRECTION"  # => Turn Right
echo 'Turn $DIRECTION'  # => Turn $DIRECTION

Bash for-loop


VAR=""
for NAME in 'alpha' 'bravo' 'charlie' 'delta'; do
  VAR+="${NAME} "
done

echo $VAR
# output: alpha bravo charlie delta 

Bash if-and, bash if-or

if [ $FILENAME == 'important.txt' ] && [ -f $FILENAME ]; then
  echo "this is an important file"
fi
if [ $NAME == 'Hector' ] || [ $NAME == 'Miguel' ]; then
  echo "this person is on a hero's journey"
fi

Bash check if directory exists

DIR="/usr/mydir/"

if [ -d "$DIR" ]; then
  echo "directory exists"
else
  echo "directory not found"
  exit 1
fi
DIR="/usr/mydir/"

[ "$DIR" == "" ] && { echo "directory string is empty"; exit 1; }
[ -d "${DIR}" ] && echo "directory exists" || echo "directory not found"

Bash if directory does not exist


DIR="/usr/mydir/"

if ! [ -d "$DIR" ]; then
  echo "directory does not exist"
else
  echo "directory exists"
fi

Bash check if file exists

if [ -f "/opt/myfile.txt" ]; then
  echo "file found"
else
  echo "file not found
fi

For items in bash array

DIR3="/opt/mydir3"
DIRTOCHECK=("/opt/mydir1" "/opt/mydir2" $DIR3)

for dir in "${DIRTOCHECK[@]}"
do
  if [ -d "${dir}" ]; then
    echo "found directory ${dir}"
  else
    echo "did not find directory ${dir}"
  fi
done

Command line arguments in bash scripting

# example: yourscript.sh arg1 2nd-arg

echo "All arguments values:" $@
# output: All arguments values: arg1 2nd-arg

echo "First argument:" ${1}
# output: First argument: arg1

echo "Second argument:" ${2}
# output: Second argument: 2nd-arg

echo "Total arguments:" $#
# output: Total arguments: 2

For more detailed information, please refer to this tecadmin.net tutorial

How to check if git repo needs update from remote upstream with bash scripting

This how-to assumes you already have a git repository installed, a remote upstream setup, and have navigated into the local repository via your script.

git fetch
if [ $(git rev-parse HEAD) == $(git rev-parse @{u}) ]; then
  # add logic for when no update is needed, e.g.
  echo 'already up to date.'
else
  # add logic for when update is needed, e.g.
  echo 'updating to latest.'
  git pull
fi

How to check if script is on correct git branch for bash script

The following example assumes master branch is desired and the script has already navigated to the local repository.

if ! [ $(git rev-parse --abbrev-ref HEAD) == "master" ]; then
  echo "NOT in master branch."
else
  echo "in master branch."
fi

Why these reminders?

This page is intended to remind myself quickly without requiring too much reading. I hope it's helped you out, too.

References: