What to Do When the Code Sucks

I've written a few times about people saying, "This code sucks." Most of the time the sucky code in question was written by somebody else — another employee or a different vendor.

On occasion, it was written by the very person who is talking to me about it, usually 6 months or more in the past. That is always a fascinating conversation, but that is not what this blog is about. This blog is about the other situation: "This bad code was written by somebody else and it is bad, bad code."

What Are Spring Projects?

There are several important Spring Projects solving the needs of enterprises today. But first, it is essential to understand what are Spring Projects and how are they different from Spring Modules?

What You Will Learn

  • What are Spring Projects?
  • What are some examples of Spring Projects?
  • How are Spring Projects different from Spring Modules?

What Are Spring Projects?

Within the Spring Framework, there are a variety of different Spring modules — JDBC, AOP, Beans, and Context. All Spring Modules share the same release version as the Spring Framework. They are part of the same project.

Google Apps Script for Developers

Google Apps Script makes it is easy for you to integrate data and functionality from Gmail, Google Drive, Google Maps, YouTube, and most other Google APIs. Apps Script is JavaScript under the hood so you don’t have to learn a new language and you don’t have to manage any servers since all your code runs on the Google Cloud, not your browser.

In this video tutorial, you’ll learn how to develop Google Apps Script projects locally on your computer inside Visual Studio Code. You can write your code in modern JavaScript, neatly organized in modules, and the build environment will use Babel and Webpack to transform your code into a version of JavaScript that is compatible with Apps Script.

Modern Development with Google Apps Script

There are quite a few advantages with having a local development environment vis-a-vis writing code in the Apps Script Cloud IDE.

  1. You can write code with ES6 Classes, Arrow Functions, Modules, Destructing and use all the other modern JavaScript features.
  2. The development experience inside VS Code is unmatched and tools like ESLint and Prettier make it easier for you to catch errors early in the development.
  3. The build and deployment process can be completely automated with npm scripts and CLASP, Google’s command line utility for Apps Script.
  4. VS Code has built-in support for Git and integrates with source control providers like Github and Gitlab. It is therefore easier to track changes and restore previous versions of the code.
  5. You can quickly integrate JavaScript libraries like LoDash, Moment, Underscore and any of the NPM packages into your code.
  6. You can use modern frameworks like React, Vue.js and Angular to build the HTML frontend that connects to the backend with the Google Script Client API.

Getting Started with the Apps Script Starter

The Starter kit is a boilerplate for quickly getting started with local Apps Script development locally inside VS Code. Open your terminal and run the following commands:

1. Clone the Github repository to a local folder

git clone https://github.com/labnol/apps-script-start my-project

2. Switch to the project folder

cd my-project

3. Install all the project dependencies and utilities

npm install

4. Connect CLASP to your Google account

npx clasp login

5. Create a new Google Apps Script project in your Google Drive with CLASP

npx clasp create "My Project" --rootDir ./dist

This command will create a new .clasp.json file in your project folder that links the local folder with your Apps Script project. During build, Webpack will bundle all your code in a single JavaScript file and add it to the ./dist folder that Clasp will push to your Apps Script project.

Next, open the current project folder inside VS Code with the code . command. It includes some sample code but we will start with a blank folder so delete everything that’s inside the src folder.

Inside the src folder, create a new file – email.js – and write a simple arrow function that prints a list of all the email addresses connected to your Gmail account.

apps-script-starter (1).png

Next, create an index.js file (entry point) in the src folder, import the email function that you’ve created inside the email.js file and add it to the global object. This is a requirement of the Webpack plugin for Google Apps Script.

You can also add a function expression to the global object directly, like doGet in the example below.

htmlservice-doget.png

Now that your JavaScript code is ready, open the appsscript.json file in your project folder and modify the oAuthScopes property to only include the scopes that are required by your project.

Next, jump to the command line terminal and run the deploy command to push your code to the Apps Script project.

npm run deploy

After the deployment is complete, open the associated script in the browser with the CLASP open command.

npx clasp open

Inside the Apps Script Editor, go to the Run menu and choose the getEmailAddress function from the list. Open the logs and you should see your email addresses in the window.

Then go to the Publish menu, choose Deploy as web app and open the URL in a new browser tab to check the program output. That’s how easy it is to build projects with the Google Apps Script starter kit.

Using Git with Google Apps Script

Create a new repository in Github and make a note of the URL of the new repository. Next, open the terminal and run the following commands to push your Apps Script project to Github.

github-apps-script.png

Also see: Most Useful Google Apps Scripts

The same approach is used by Digital Inspiration for building popular Google add-ons including Gmail Mail MergeGoogle Forms Notifications and Document Studio.

The post Google Apps Script for Developers appeared first on Digital Inspiration.

Default WordPress Image Sizes and How to add Custom Sizes

When you upload an image, WordPress does a lot of work behind-the-scenes so you can serve the image to your visitors. You can piggyback on this process and add custom image sizes to save yourself from having to resize images manually.

In this post, I’ll explain how and why WordPress creates different image sizes. Then I’ll teach you how to add your own image sizes by modifying the functions.php file, regenerate thumbnails and add your new image sizes to the Gutenberg image block and/or the WordPress loop.

WordPress Image Sizes Explained

Every time you upload an image into the WordPress media library, these are the additional image size options WordPress creates by default:

  • Thumbnail
  • Medium
  • Medium Large
  • Large

If your theme specifies additional image sizes, WordPress creates those as well.

WordPress also preserves the original size you upload and names it Full as in full-size.

You can see all of these (with the exception of Medium_Large) in the Gutenberg image block Image Size drop down when inserting an image into a page or post.

Why does WordPress create so many images?

Images are like pants. You want to make sure you get the right size. Pants and images that are too small look silly and it’s painfully obvious to you and everyone else that they don’t fit right. Too small images on your site will look stretched out or pixellated.

By contrast, if they’re too large, that’s super wasteful. You wouldn’t put a pair of pants made for a man on a baby, right? It’s so much extra fabric that isn’t even necessary. That baby is going to get lost in a pant leg ;)

Images are the same. If your image is too large for the container, you’re wasting bandwidth and time downloading it to serve on your page. And for what? For nothing.

Ideally, the full-size images you upload should be big enough to fit the largest image container on your site, but no larger. Then when you use images on your site, you should use the exact size image you need.

Since scaling images to create the right size in Photoshop or other image editor takes valuable time, WordPress takes on this task and does it for you. Thanks, WordPress!

All you need to do is choose the appropriate size when inserting an image into your site to get the performance benefits of using an image that is just right.

If the WordPress default image sizes aren’t perfectly sized for your theme, you can adjust the defaults in the Media > Settings section or add custom sizes so you’ll have more options to choose from.

Screenshot of WordPress Media settings
The WordPress default image sizes, except for medium_large which is hidden by default

The default image sizes are as follows:

  • 150px square for thumbnails
  • 300px width for medium images
  • 768px max width for medium_large images
  • 1024px max width for large images.

Medium_large was added to take advantage of responsive image support, which is why it isn’t included in the settings page. Speaking of responsive images…

Responsive Images

All of these images in various sizes serve another purpose, so you shouldn’t set the defaults to zero to keep WordPress from creating them, as some tutorials suggest.

WordPress added responsive images to core in version 4.4. Instead of populating image src attributes with the URL for just one image, WordPress also added srcset (set of sources) which is a list of URLs of images of various sizes.

Guess what images it uses to create that list? Yup, WordPress uses the same images at different sizes it creates when you upload an image.

It offers this list to the browser so it can select an image that is appropriate for the visitor’s device. If the visitor is using a mobile device, they’ll receive a smaller image in the srcset. If they’re visiting your site on a desktop Retina device, then they’ll receive the full-size Retina-ready image file you uploaded. Again, this is why you should upload an image big enough to fill that need.

When you add a custom image size, WordPress will add it to the srcset as long as it has the same aspect ratio. If the custom image size crops the image into a different shape then it will be omitted from the set.

WordPress Thumbnails and Featured Image Size

We’ve now reached the part of our tutorial where we will unravel the whole thumbnail/featured image mess. Basically, the problem boils down to this; because WordPress maintains backward compatibility as it evolves, the names of things change, but the functions still refer to things by their old names.

The WordPress Thumbnails image size was introduced in version 2.9 but was quickly changed to Featured Images in version 3.0, but alas, the name stuck. So you’ll often hear featured images referred to as thumbnails in tutorials and even in the function names.

Screenshot of Featured Image Metabox
If you don’t have the featured image meta box, paste add_theme_support( ‘post-thumbnails’ ); into your functions.php file

Here are some examples:

  • If your theme doesn’t have featured images and you want to enable that feature, you’ll add add_theme_support( 'post-thumbnails' ); to your functions file.
  • To display the WordPress featured image size in a theme, you’ll use the_post_thumbnail() function.

Thumbnails and featured images share a default size of 150px by 150px. If you use the_post_thumbnail() function without an argument to specify the size, it will use the default 150px square size.

To make this less confusing for yourself so you can actually use the right size, I suggest creating a custom image size and naming it featured-large or something similar. Then, when you want to use that image in you’re the loop, you’ll use the_post_thumbnail('featured-large').

Before You Start Creating Custom Image Sizes in WordPress

As you start creating custom image sizes, avoid going overboard and creating images for every conceivable purpose. Otherwise, you’ll burn through space on your hosting and if you’re using an image optimization service that charges you per image, you’re going to go through your image allowance a whole lot faster.

If your plan allows you to optimize 100 images but every upload generates 9 additional sizes that also need to be optimized, you’ll hit your limit once you upload 10 images. Keep this in mind when adding custom sizes and choosing image optimization plans.

Smush Pro doesn’t have image optimization limits and comes with a CDN so you can keep your server storage space clear. You’ll be able to add more custom image sizes than you normally would. Think of it as the equivalent of putting flowy MC Hammer pants instead of little skinny jeans on those babies because the fabric is cheap :)

Try Smush Pro free for 30 days.

How to Add Custom Image Sizes in WordPress

Here is the code we’re going to be adding to our functions file to add image sizes:

add_image_size( 'the-name-for-custom-image-size', 600, 400, true );

This function accepts 4 parameters in this order:

  1. The name you give your custom image size
  2. The image width in pixels
  3. The image height in pixels
  4. Should the image be cropped to fit the width and height you specified above

Cropping

The cropping parameter is a boolean, so you’ll use true or false. If you leave it out entirely, then it will default to false.

If you set the cropping parameter to true, then WordPress will crop your image to fit the dimensions you specify when it creates the custom image.

For example, if your custom image size is a 600px by 600px square and you set cropping to true, then if you upload a 600px by 800px rectangular image, 200px will get chopped off to make the image square.

add_image_size( 'custom-image-square', 600, 600, true );

Setting the cropping parameter to true is helpful for image sizes that have to be exact, like featured images or post archive images that have to fit a certain dimension perfectly.

For images that can have more wiggle room, such as the WordPress post image size and images on pages that tend to have variable heights and widths, then you can set cropping to false. This will resize the images, but it won’t change the shape of the image or cut off any pixels.

Take a look at our image SEO guide if you’re trying to drive traffic to your sites with your images.

Regenerating Thumbnails

One of the most important steps when either:

  1. modifying the WordPress default image sizes
  2. adding custom image sizes or
  3. switching over to a new theme that has different custom sizes

is regenerating thumbnails.

In this context, thumbnails refers to all the additional images WordPress creates, including the custom image sizes that are included in your theme and the ones that you create via your functions file.

When you make a change to the way that WordPress creates additional images, then it will only affect the images you upload going forward. It doesn’t update the images that are already in your media library.

To change the images you’ve already uploaded, you’ll have to use the popular Regenerate Thumbnails plugin.

After you install it, you’ll find it in the Tools section.

Screenshot regenerate thumbnails settings
Just push the button to create new image sizes

When you regenerate your thumbnails in your new sizes, you’ll have the option to delete old unused image sizes to free up server space.

How to Add Custom Image Sizes to the drop-down in the Gutenberg image block

You only need to add the code below to your functions file if you want your custom image sizes to appear in the drop-down in the Gutenberg image block. If you created a custom image size to use behind-the-scenes for your theme, you can skip this step.

Screenshot Gutenberg Image Block Sizes Dropdown
Here’s the custom image size I’m adding with the code below

We’re going to be hooking onto the image_size_names_choose filter.

In the array, I’ll add the name of the custom size that I specified in the add_image_size function and the name that I want to appear in the drop-down within the parentheses.

As I learned when doing this tutorial, you’ll have to regenerate thumbnails before the image appears in the drop down.

WordPress Add Image Size Full Code Snippet

Next, we’ll combine everything we learned into one code block with a real-world example.

Let’s say you want to add custom image sizes to your blog.

Here are the image sizes you want to add:

  • A 1600px by 400px featured image
  • An 800px size that spans the width of your blog’s content section

Since our theme doesn’t currently support featured images, we’ll start with that.

You’ll then see my custom sizes. Notice that I didn’t crop the images that are going to span the width of the blog content. I will hard crop my featured images since I want them to line up just right.

The only image I want to add to the Gutenberg drop down is the blog image since I’ll be using the WordPress featured image size in my theme.

After I add this code to my functions.php file, the next step is to regenerate thumbnails.

To use my custom featured image for my posts in the loop, I’ll add the following to single.php or index.php

See how I added 'featured-large' in the_post_thumbnail() function? That will display my featured image below my blog posts titles, above my content.

Custom Image Sizes Best Practices

Here are a few more tips so you don’t run into trouble creating custom images in WordPress.

  1. Always upload the largest file you can. If your image size is too small, WordPress won’t be able to create all the sizes it needs to serve your images properly on a variety of devices.
  2. If you need to resize the medium_large default size, use the update_option() function. You can use this same function to update any other WordPress default image size.
  3. If you’re outside the WordPress loop, you can use the function get_the_post_thumbnail() to use one of your custom images.
  4. Here’s more on soft cropping and hard cropping when creating custom images sizes in case you run into trouble.

That’s All There is to Adding Custom Image Sizes

Once you understand how custom image sizes in WordPress work, you can modify them to fit your needs and save a lot of time. Getting your image sizes right also helps you improve your site performance and search engine rankings, so it is an important thing to get right.

If you really want to take your image optimization to another level, check out Smush. We’ve added an amazing CDN to Smush Pro that has automatic image resizing, which will help you avoid dealing with modifying your functions file to add custom image sizes.

There are also other great image optimization features that come built-in, like lazy loading and converting images to next-gen formats. Try Smush Pro free for 30 days and see how the image optimization features can improve your site.

Immutable Data Structures in Java

As part of some of the coding interviews I’ve been conducting recently, the topic of immutability sometimes comes up. I’m not overly dogmatic in it myself, but whenever there’s no need for mutable state, I try to get rid of code which makes code mutable, which is often most visible in data structures. However, there seems to be a bit of a misunderstanding on the concept of immutability, where developers often believe that having a final reference, or val in Kotlin or Scala, is enough to make an object immutable. This blogpost dives a bit deeper in immutable references and immutable data structures.

Benefits of Immutable Data Structures

Immutable data structures have significant benefits, such as:

How to Completely Customize the WordPress Login Page

The WordPress login page provides a generic looking one-size-fits-all solution for logging into WordPress. The only problem is customizing it can get a little awkward. In this comprehensive tutorial we show you how to modify the login screen to look exactly how you want.

Creating a Calculator With wxPython

A lot of beginner tutorials start with “Hello World” examples. There are plenty of websites that use a calculator application as a kind of “Hello World” for GUI beginners. Calculators are a good way to learn because they have a set of widgets that you need to lay out in an orderly fashion. They also require a certain amount of logic to make them work correctly. For this calculator, let’s focus on being able to do the following:

  • Addition
  • Subtraction
  • Multiplication
  • Division

I think that supporting these four functions is a great starting place and also give you plenty of room for enhancing the application on your own.

In a Software-Driven World, Who Is Responsible for the Risks?

The power of software to improve our lives and our world is almost limitless. Consequently, those creating software are wielding a power that demands a new level of responsibility.

When I think about how fast the world is changing, I wonder how our ancestors must have felt at the dawn of past industrial revolutions. Everything changed — the way we made, shipped, and sold goods evolved, and daily schedules and lives changed as people moved to cities to escape subsistence farming and find work in factories and mills. All of this change was fueled by new technologies and innovations. While many of these changes were positive, there were risks and costs, such as increased injuries, rising wealth inequality, and, as urbanization took hold, an increased spread of disease. It became the responsibility of factory workers, and in some cases the government, to address these concerns in order for our economy and society to flourish and grow.

The Essential Tools for Programmers

This is a list of essential tools and services from my coding workflow that I think should be part of every web programmer’s toolkit. Whether you a building a simple “Hello World” app or a complex web application, these tools should make your coding easier and increase productivity.

programmers-toolkit.jpg

The Web Developer’s Toolkit

1. devdocs.io — API documentation for all popular programming languages and frameworks. Includes instant search and works offline too.

2. glitch.com — create your own web apps in the browser, import GitHub repos, use any NPM package or build on any popular frameworks and directly deploy to Firebase.

3. bundlephobia.com — quickly find the import cost (download size) of any package in the NPM registry. Or upload your package.json file to scan all dependencies in your project.

4. babeljs.io/repl — Write your code in modern JavaScript and let Babel transform your code into JavaScript that is compatible with even older browsers.

5. codeply.com — quickly build frontend responsive layouts with frameworks like Bootstrap, Materialize CSS and SemanticUI.

6. httpie.org — a command-line tool that is useful for making HTTP requests to web servers and RESTful APIs. Almost as powerful as CURL and Wget but simpler.

7. regexr.com — A good tool for testing your regular expressions in the browser.

8. jex.im/regulex — Write any regular expression into the editor and get a visual representation of how the pieces work.

9. buildregex.com — Construct regular expressions visually.

Also see: The Most Useful Websites on the Internet

10. explainshell.com — Type any Unix command and get a visual explanation of each flag and argument in the command.

11. tldr.ostera.io — Unix man pages are long and complex. This site offers practical examples for all popular Unix command without you having to dive into the man pages.

12. mockaroo.com — quickly generate dummy test data in the browser in CSV, JSON, SQL and other export formats.

13. jsdelivr.com — Serve any GitHub file or WordPress plugin through a CDN. Combine multiple files in a single URL, add “.min” to any JS/CSS file to get a minified version automatically. Also see unpkg.com.

14. carbon.now.sh — create beautiful screenshots of your source code. Offers syntax highlighting for all popular languages.

15. wakatime.com — know exactly how long you spend coding with detailed metrics per file and even language. Integrates with VS Code, Sublime text, and all popular code editors.

16. astexplorer.net — paste your JavaScript code into the editor and generate the Abstract Syntax Tree that will help you understand how the JavaScript parser works.

17. hyper.is — A better alternative to the command line terminal and also iTerm. Use with the Oh My Zsh shell and add superpowers to your terminal.

18. curlbuilder.com — make your own CURL requests in the browser.

19. htaccess.madewithlove.be — easily test the redirect and rewrite rules in the .htaccess file of your Apache server. See useful .htaccess snippets.

Also see: The Best Places to Download HTML Templates

20. trackjs.com — monitor errors in your JavaScript based web projects and get instant email notifications when a new error is detected.

21. ngrok.com — Start a local web server, fire up ngrok, point to the port where the localhost is running and get a public URL of your tunnel.

22. codeshare.io — An online code editor for pair programming, live interviews with video conferences or for teaching code to students remotely.

23. webhooks.site — Easily inspect the payloads and debug HTTP webhooks in the browser. All HTTP requests are logged in real-time. Another good alternative is RequestBin.

24. surge.sh — the easiest way to deploy web pages and other static content from the command line. Supports custom domains and SSL. Also see Zeit Now.

25. visbug — A must-have add-on for web developers that brings useful web design tools right in your browser. Available for Google Chrome and Firefox.

26. puppeteersandbox.com — Puppeteer is a Node.js framework for automating Google Chrome. Use the sandbox to quickly test your scripts in the browser. Also see try-puppeteer.com.

27. prettier.io/playground — Beautify your JavaScript and TypeScript code using Prettier, the favorite code formatter of programmers.

28. json.parser.online.fr — The only JSON parser you’ll ever need to analyze and beautify your complex JSON strings.

29. scrimba.com — Create your own programming screencasts in the browser or watch other developers code.code.

30. katacoda.com — A training platform for software developers where anyone can create their own dedicated and interactive training environments.

31. codesandbox.io — A full-featured online IDE where you can create web applications in all popular languages including vanilla JavaScript, React, TypeScript, Vue and Angular. Also see StackBlitz.com and Repl.it.

32. apify.com — Write your own web scrapers using JavaScript and schedule your scrapers to run at specific intervals automatically.

33. vim-adventures.com — The Vim text editor is hugely popular among programmers. The site will help you master the various key commands through a game.

34. insomnia.rest — A desktop based REST client that lets you create HTTP requests and view response details all in a easy-to-use interface. Advanced users may consider Postman.

Also see: The Most Awesome Teachers for Learning Web Development

The post The Essential Tools for Programmers appeared first on Digital Inspiration.

Magic With the Spring Boot Actuator

Spring Boot provides the Spring Boot actuator module for monitoring and managing your application when it is moved into production. Some of the production-ready features it provides are health monitoring of the application, auditing of the events, and gathering of metrics from the production environments.

For enabling the Spring Boot actuator, we need to add the following Spring Boot starter Maven dependency in pom.xml.

Spring Boot and Working With MBeans [Snippet]

The following example demonstrates how one can manage object operation remotely via the JMX Console. Once you declare your object as MBeans, one can extend the example to apply remote logging without changing log4j, which is very useful in production environments, evicting cache or any other operation that needs to be handled remotely via MBean/JMX.

 @ManagedResource: This Spring annotation applies on the Class Level, and this will declare it as an MBean.

Enhancing a Kotlin Chart With Advanced Charting Kit (Part 2)

In part 1 of this blog series, I demonstrated how the Advanced Charting Kit can be used to enhance a shinobichart using Kotlin. In this blog post, I’d like to show you how you can improve your chart a little further. Again, I’ll demonstrate this using the heart rate chart that I used in part 1. At the end of part 1, we had a chart that looked as below:

While the chart now shows pace as well as heart rate, I feel it looks a little crowded. The relationships between the data series are not immediately obvious and I feel — to some degree — adding the pace data clutters the chart when it is viewed fully zoomed out. Rather than display all of the pace data upon the initial loading of the chart, I think this could be a great fit for ACK’s drill down animation feature. Why don’t we have the pace data appear as the user zooms in on the x or time axis?

Enhancing a Kotlin Chart With Advanced Charting Kit (Part 1)

Ever since Google announced support for Kotlin on Android back in 2017, its popularity amongst developers has continued. Having initially experimented with Kotlin, I was keen to see how it would get along with the shinobicharts and Advanced Charting Kit libraries. Being the owner of a wearable fitness tracking device, I decided to write a simple app that would display a chart showing my heart rate over a typical working day.

I began by taking a day’s worth of data and placing into a simple file. The data is presented as a timestamp value and an integer showing the beats per minute at that time. A typical data row looks like this:

Design Patterns in Java: Singleton

A design pattern is defined as the re-usable form of a solution to a design problem. With a design pattern, you can document a solution to a design problem. Design patterns were introduced by the architect Christopher Alexander and have been adapted for various other disciplines and are very popular among developers, as they provide solutions to general problems that software developers face. It provides a template to solve common problems while designing a system or an application.

Design patterns act as a common language between developers so that each developer easily understands the concept while working with common problems.