Category: Coding & Scripting

HTML: how to vertically center an object with CSS?

There are several ways to vertically center an object with CSS:

Flexbox

<div class="container">
  <div class="center-item">
    <!-- content goes here -->
  </div>
</div>
.container {
  display: flex;
  align-items: center;
  height: 100%;
}

This method uses the CSS flexbox layout to center the child element vertically within the parent container. The align-items property set to center aligns the child element along the cross axis.

Grid Layout

<div class="container">
  <div class="center-item">
    <!-- content goes here -->
  </div>
</div>
.container {
  display: grid;
  place-items: center;
  height: 100%;
}

This method uses the CSS grid layout to center the child element vertically and horizontally within the parent container. The place-items property set to center aligns the child element both vertically and horizontally.

Table Cell

<div class="container">
  <div class="center-item">
    <!-- content goes here -->
  </div>
</div>
.container {
  display: table-cell;
  vertical-align: middle;
  height: 100%;
}

This method uses the CSS table layout to center the child element vertically within the parent container. The display: table-cell and vertical-align: middle properties treat the parent container as a table cell and vertically center the child element within it.

Transforms

<div class="container">
  <div class="center-item">
    <!-- content goes here -->
  </div>
</div>
.container {
  position: relative;
  height: 100%;
}
.center-item {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

This method uses CSS transforms to center the child element vertically within the parent container. The top: 50% property positions the child element vertically halfway down the parent container, and the transform: translateY(-50%) property moves the child element upwards by half its own height, effectively centering it vertically within the parent container.

Foto von Jackson Sophat auf Unsplash.

 

Flutter: how to create a better MaterialColor from Color

In Flutter, MaterialColor is a class that defines a color palette to be used within a Material Design app. It creates a set of shades for a given primary color, which can be used in various components of the UI, such as buttons, text fields, and navigation bars. MaterialColor objects can be created from a single color value and then generate shades based on a specified brightness factor. This allows for a consistent and harmonious color scheme throughout the app.

To create a MaterialColor from a Color, you can use the MaterialColor class in Dart. The MaterialColor constructor takes two arguments:

  • The value of the color in RGB.
  • A map of shades of the color with keys representing the shade level and values representing the Color of that shade.

Let’s say we want to create a MaterialColor from the RGB color 176 / 255 / 38:

To use an implementation, let’s create a static method in a MaterialColorGenerator class and call:

Color color = Color.fromARGB(255, 176, 255, 38);
MaterialColor material = MaterialColorGenerator.from(color);

Now there are different ways to define the shades. Most tutorials propose to change the opacity for each shade, which will result in such a code:

import 'package:flutter/material.dart';

class MaterialColorGenerator{
  static MaterialColor from(Color color) {
    return MaterialColor(color.value, <int, Color>{
      50: color.withOpacity(0.1),
      100: color.withOpacity(0.2),
      200: color.withOpacity(0.3),
      300: color.withOpacity(0.4),
      400: color.withOpacity(0.5),
      500: color.withOpacity(0.6),
      600: color.withOpacity(0.7),
      700: color.withOpacity(0.8),
      800: color.withOpacity(0.9),
      900: color.withOpacity(1.0),
    });
  }
}

Let’s take our color example and look at the result:

Color values from shade50 (top) to shade900 (bottom).

This is a good result for lighter colors, but results in very similar colors for the “darker” shades. To create some real color variations, it’s better to adjust the color values itself by using:

import 'package:flutter/material.dart';

class MaterialColorGenerator{
  static MaterialColor from(Color color) {
    List strengths = <double>[.05];
    final swatch = <int, Color>{};
    final int r = color.red, g = color.green, b = color.blue;

    for (int i = 1; i < 10; i++) {
      strengths.add(0.1 * i);
    }
    for (var strength in strengths) {
      final double ds = 0.5 - strength;
      swatch[(strength * 1000).round()] = Color.fromRGBO(
        r + ((ds < 0 ? r : (255 - r)) * ds).round(),
        g + ((ds < 0 ? g : (255 - g)) * ds).round(),
        b + ((ds < 0 ? b : (255 - b)) * ds).round(),
        1,
      );
    }
    return MaterialColor(color.value, swatch);
  }
}

Let’s take our color example and look at the result:

Color values from shade50 (top) to shade900 (bottom).

Now the result is good for “darker” shades (> 500), but there is less variation for the “lighter” colors. Let’s find a version that combines both of the advantages:

import 'dart:math';
import 'package:flutter/material.dart';

class MaterialColorGenerator{
  static MaterialColor from(Color color) {
    return MaterialColor(color.value, {
      50: tintColor(color, 0.9),
      100: tintColor(color, 0.8),
      200: tintColor(color, 0.6),
      300: tintColor(color, 0.4),
      400: tintColor(color, 0.2),
      500: color,
      600: shadeColor(color, 0.1),
      700: shadeColor(color, 0.2),
      800: shadeColor(color, 0.3),
      900: shadeColor(color, 0.4),
    });
  }

  static int tintValue(int value, double factor) =>
      max(0, min((value + ((255 - value) * factor)).round(), 255));

  static Color tintColor(Color color, double factor) => Color.fromRGBO(
      tintValue(color.red, factor),
      tintValue(color.green, factor),
      tintValue(color.blue, factor),
      1);

  static int shadeValue(int value, double factor) =>
      max(0, min(value - (value * factor).round(), 255));

  static Color shadeColor(Color color, double factor) => Color.fromRGBO(
      shadeValue(color.red, factor),
      shadeValue(color.green, factor),
      shadeValue(color.blue, factor),
      1);
}

Let’s take our color example and look at the result:

Color values from shade50 (top) to shade900 (bottom).

This is a much better result, which corelates with the color palettes of the Material Design. This implementation is also used by the material_color_generator package.

Foto von Zden?k Machá?ek auf Unsplash.

 

LaTeX: how to insert a PDF file

You can insert a PDF file in LaTeX using the \includegraphics command from the graphicx package. The basic syntax is as follows:

\usepackage{graphicx}
...
\includegraphics{file.pdf}

Where “file.pdf” is the name of your PDF file. You can also specify options such as the width and height of the image, as well as its placement on the page.

\includegraphics[width=0.8\textwidth,height=0.3\textheight,keepaspectratio,center]{file.pdf}

You can also use the pdfpages package to include an entire pdf file in the document,

\usepackage{pdfpages}
...
\includepdf[pages=-]{file.pdf}

The pdfpages package

The pdfpages package allows you to include one or more pages from a PDF file in your LaTeX document. To use the package, you first need to add it to your preamble with the following command:

\usepackage{pdfpages}

Once the package is loaded, you can use the \includepdf command to include a PDF file in your document. The basic syntax is as follows:

\includepdf[options]{file.pdf}

Where “file.pdf” is the name of the PDF file you want to include and “options” are any additional options you want to specify.

The most common option is the pages option, which allows you to specify which pages of the PDF file should be included in the document. For example, to include the first and second pages of a PDF file called “file.pdf”, you would use the following command:

\includepdf[pages={1,2}]{file.pdf}

You can also use - to include all the pages in the pdf file

\includepdf[pages=-]{file.pdf}

Other options include fitpaper, fitwindow, noautoscale, angle, scale, offset, and pagecommand. You can use these options to control the size, rotation, and placement of the included PDF pages, as well as to add custom headers and footers to the included pages.

For more details and examples on how to use the pdfpages package, you can check the package documentation.

Flutter: how to sort a list of objects by one of its properties

In Flutter (Dart), you can use the sort method on a list of objects, along with a custom comparator function, to sort the list by the alphabetical order of one of its properties.

Here’s an example of how you can sort a list of objects (let’s say they’re called Person) by their name property:

List<Person> people = [
  Person(name: "Bob"),
  Person(name: "Charlie"),
  Person(name: "Alice"),
];

people.sort((a, b) => a.name.compareTo(b.name));

In this example, the sort method takes a comparator function as its argument. The comparator function compares two Person objects and returns a negative, zero, or positive value, depending on whether the first object should be sorted before, in the same position as, or after the second object. In this case, it compares the name property of each object using the compareTo method and sorts them alphabetically.

Another way to sort by one property is to use the sortBy method from the ‘dart:collection’ package:

import 'dart:collection';

people.sortBy((person) => person.name);

This will sort the list of people based on the name property.

How do I insert code into a LaTeX document?

There are several ways to insert code into a LaTeX document. One common method is to use the lstlisting environment from the listings package. The package provides options for formatting the code, such as language, font size, and background color. An example of how to use lstlisting to insert a piece of Python code is as follows:

\usepackage{listings}

% ...

\begin{lstlisting}[language=Python]
def hello_world():
    print("Hello, World!")
\end{lstlisting}

Another way is to use verbatim environment.

\begin{verbatim}
def hello_world():
    print("Hello, World!")
\end{verbatim}

Please note that verbatim does not format the code. You can also use other packages like minted, fancyvrb, listingsutf8 to insert code in LaTeX document.

How to use the minted package

The minted package is a LaTeX package that provides syntax highlighting for source code listings using the Pygments library. In order to use the package, you will need to have Pygments installed on your system.

To use the minted package in your LaTeX document, you will need to add the following lines to your preamble:

\usepackage{minted}

Then, you can use the minted environment to insert code listings in your document. The basic syntax is as follows:

\begin{minted}{language}
    [options]
    code
\end{minted}

Where language is the language of the code you are listing (e.g. Python, C++, Java), and options are any additional options you want to pass to the package.

For example, the following code will insert a listing of Python code with the default options:

\begin{minted}{python}
def hello_world():
    print("Hello, World!")
\end{minted}

You can also include options such as fontsize, linenos (line numbers), etc.

\begin{minted}[linenos, fontsize=\footnotesize,numbersep=5pt, frame=lines, framesep=2mm]{python}
def hello_world():
    print("Hello, World!")
\end{minted}

You also need to run a shell command to create a file with highlighted code.

pdflatex --shell-escape file.tex

Please note that minted package requires the use of an external program pygmentize to create the highlighted code, which is why it requires the --shell-escape option when running pdflatex.

How to use the fancyvrb package

The fancyvrb package is a LaTeX package that provides advanced verbatim capabilities, including support for typesetting source code listings with custom fonts and formatting.

To use the fancyvrb package in your LaTeX document, you will need to add the following lines to your preamble:

\usepackage{fancyvrb}

Then, you can use the Verbatim environment to insert code listings in your document. The basic syntax is as follows:

\begin{Verbatim}[options]
    code
\end{Verbatim}

Where options are any additional options you want to pass to the package.

For example, the following code will insert a listing of Python code with the default options:

\begin{Verbatim}
def hello_world():
    print("Hello, World!")
\end{Verbatim}

You can also include options such as fontsize, linenos (line numbers), etc.

\begin{Verbatim}[fontsize=\small,frame=single]
def hello_world():
    print("Hello, World!")
\end{Verbatim}

The fancyvrb package also provides other environments such as BVerbatim and LVerbatim which are useful for typesetting verbatim text with different formatting options.

Please note that the fancyvrb package is not recommended for large code listings because it can cause issues with line breaks and spacing. But it’s a good choice for small code snippets and text.

How to use listingsutf8 package

The listingsutf8 package is a LaTeX package that provides support for typesetting source code listings with UTF-8 encoded characters. It is an extension of the listings package and provides the same functionality as the listings package but with the added capability to handle UTF-8 encoded characters.

To use the listingsutf8 package in your LaTeX document, you will need to add the following lines to your preamble:

\usepackage{listingsutf8}

Then, you can use the lstlisting environment to insert code listings in your document. The basic syntax is as follows:

\begin{lstlisting}[options]
    code
\end{lstlisting}

Where options are any additional options you want to pass to the package.

For example, the following code will insert a listing of Python code with the default options:

\begin{lstlisting}[language=Python]
def hello_world():
    print("Hello, World!")
\end{lstlisting}

You can also include options such as fontsize, linenos (line numbers), etc.

\begin{lstlisting}[language=Python, fontsize=\small, numbers=left]
def hello_world():
    print("Hello, World!")
\end{lstlisting}

The listingsutf8 package provides many other options to customize the appearance of the code listing, such as background color, keywords, and more. It also allows for inputencoding to be UTF-8, so it can handle special characters and non-latin scripts.

Please note that if you are using an older version of LaTeX, you may need to install the listingsutf8 package manually and configure your TeX distribution to find it.

mysqldump: how to exclude or include tables

mysqldump is a command-line tool used for creating database backups in MySQL. By default, mysqldump includes all tables of the specified database when creating the dump. In some cases, it is useful to exclude some of the tables or even include only some of them. For me, this helped to exclude one of the biggest tables to reduce the backup execution time and file size.

Exclude a single table

To exclude a single table, the argument --ignore-table followed by the table name is used:

mysqldump my_database --ignore-table=my_table > my_backup.sql

This will create a file my_backup.sql containing the sql schema and data of all tables in the database my_database except my_table.

Exclude multiple tables

To exclude multiple tables, simply add the argument --ignore-table for all the tables you want to exclude:

mysqldump my_database --ignore-table=my_table --ignore-table=another_table > my_backup.sql

This will create a file my_backup.sql containing the sql schema and data of all tables in the database my_database except my_table and another_table.

Include a single table

To include only a single table into the dump, add the name of the table to the command:

mysqldump my_database my_table > my_backup.sql

This will create a file my_backup.sql containing the sql schema and data of the table my_table from the database my_database.

Include multiple tables

To include multiple tables into the dump, add the names of the tables to the command:

mysqldump my_database my_table another_table > my_backup.sql

This will create a file my_backup.sql containing the sql schema and data of the tables my_table and another_table from the database my_database.

A complete documentation of mysqldump is available at mysql.com.

Photo by benjamin lehman on Unsplash.

Flutter: slowing down animation for debugging

The library that is responsible for different scheduling is flutter/scheduler. This also includes animations. To use the library, simply import package:flutter/scheduler.dart – in this case, timeDilation is all that you need.

Now you can set the variable timeDilation to a custom double. The value 1.0 is the default animation speed. Setting it to 2.0 will slow down all animations by a factor of two.

import 'package:flutter/scheduler.dart' show timeDilation;

// ...

timeDilation = 2.0; // Slow down animations by factor two

As timeDilation is a global variable, you can set it anywhere in the code, e.g. in main():

import 'package:flutter/scheduler.dart' show timeDilation;

void main() {
  timeDilation = 3.0;
  runApp(new MyApp());
}

Photo by LOGAN WEAVER | @LGNWVR on Unsplash

JavaScript: simple code structure for libraries

The code of a JavaScript library might get very complex over time. This can be a problem for maintenance and expandability.

When writing a library, you should address two main points:

  • Keep the environment clean from global variables and methods to avoid conflicts between different libraries
  • Provide public and private methods and variables

The following “template” provides a simple code structure that fulfills those points:

// Unique name of the library.
MyLibrary = function() {
  MyLibrary = {};

  /*
   * Internal variables and methods
   */
  var variable = 'value';
  function doSomething() {
    // do something
  }

  /*
   * Public variables and methods
   */
  MyLibrary.myVariable = true;
  MyLibrary.myAction = function() {
    // do something
  }

  // Return the library.
  return MyLibrary;
}

You can use such a library the following way:

const lib = MyLibrary();
lib.myAction()

if (lib.myVariable) {
  alert('really?');
}

Inspiration: https://stackoverflow.com/questions/13606188/writing-a-library-what-structure

Photo by Safar Safarov on Unsplash