priyankmaniar – A Weblog of Priyank Maniar https://priyank.rocks Articles on web development & mobile app development Mon, 11 Nov 2024 07:21:05 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 MySQL Connection Troubleshooting Guide for MacOS https://priyank.rocks/mysql-connection-troubleshooting-guide-for-macos/ Mon, 11 Nov 2024 07:21:02 +0000 https://priyank.rocks/?p=9596 Initial Problem Indicators

If you see this error when trying to connect to MySQL:

bashCopy

1
2
mysql -u root -p
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Step 1: Check MySQL Installation

Check if MySQL is installed via Homebrew:

bashCopy

1
brew list | grep mysql

Step 2: Clean Up Existing Services

Stop all running MySQL services:


1
brew services stop mysql<br>brew services stop mysql@8.0

sudo pkill mysqld

Step 3: Fix Permissions

Reset ownership and permissions of MySQL directory:


1
sudo chown -R $(whoami) /opt/homebrew/var/mysql<br>sudo chmod -R 755 /opt/homebrew/var/mysql

sudo chown -R $(whoami):admin /opt/homebrew/var/mysql
sudo chown -R $(whoami):admin /opt/homebrew/Cellar/mysql@8.0

Step 4: Remove Launch Agent Files

Clean up old launch agent files:


1
rm ~/Library/LaunchAgents/homebrew.mxcl.mysql@8.0.plist<br>sudo rm /Library/LaunchDaemons/homebrew.mxcl.mysql@8.0.plist

Step 5: Reset MySQL Links

Unlink and relink MySQL:


1
brew unlink mysql<br>brew unlink mysql@8.0<br>brew link mysql@8.0 --force


# The last step will gave an export to add, add that as well => echo 'export PATH="/opt/homebrew/opt/mysql@8.0/bin:$PATH"' >> ~/.zshrc

Step 6: Start MySQL Service

Start MySQL as a regular user (not root):


1
brew services start mysql@8.0

Verification

After completing these steps, verify the connection:


1
mysql -u root -p

Note: Keep track of your MySQL root password. If you’ve just installed MySQL, the initial root password might be empty.

]]>
Resolving WordPress Cron Job Issues on WP Engine: A Step-by-Step Guide https://priyank.rocks/resolving-wordpress-cron-job-issues-on-wp-engine-a-step-by-step-guide/ Sun, 10 Nov 2024 08:59:28 +0000 https://priyank.rocks/?p=9594 Introduction

Running scheduled tasks (cron jobs) in WordPress is essential for many functions, from sending scheduled emails to updating plugins and handling automated tasks. However, if you’re using WP Engine as your hosting provider, you may encounter issues with WordPress cron jobs not running as expected. This guide outlines the steps I took to resolve these issues on WP Engine, with insights into why they occur and how to fix them effectively.


Understanding WordPress Cron Jobs and WP Engine’s Alternate Cron

In a typical WordPress setup, cron jobs are triggered by page views. When someone visits your site, WordPress checks if any scheduled tasks are due, and if so, it runs them. However, this can lead to inconsistencies in running cron jobs, especially if your site has low traffic or if there are server restrictions in place.

WP Engine, a managed hosting provider, has its own optimized way of handling cron jobs called Alternate Cron. When Alternate Cron is enabled, WP Engine takes over the job scheduling process and runs WordPress cron jobs at regular intervals, independently of page views. This is more efficient and reliable but requires specific configurations.


Step-by-Step Solution for Running Cron Jobs on WP Engine

  1. Identify the Issue with Cron Jobs First, I noticed that several cron jobs were overdue in the WordPress admin panel under Tools > Cron Events. The jobs were scheduled but hadn’t run on time. They showed an error or were marked as overdue, which could indicate a scheduling issue. Additionally, some jobs had “Unknown” intervals, which could suggest issues with custom intervals.
  2. Enable WP Engine’s Alternate Cron To improve reliability, I enabled WP Engine’s Alternate Cron setting. Here’s how:
  • Navigate to WP Engine > General Settings in the WP Engine dashboard.
  • Look for the Alternate Cron option and turn it on. Enabling Alternate Cron tells WP Engine to handle cron scheduling independently of page views. As part of this change, WP Engine automatically sets the DISABLE_WP_CRON constant to true in your wp-config.php file. This effectively disables the default WordPress cron spawning process, which is normally triggered on page loads. Note: With DISABLE_WP_CRON set to true, WordPress will no longer attempt to run cron jobs with every page load. Instead, WP Engine’s server takes care of scheduling and running these tasks at regular intervals.
  1. Verify Custom Intervals and Plugins During troubleshooting, I noticed one job with an “Unknown (cseo_custom_interval)” interval, which means WordPress didn’t recognize this custom interval. It’s important to ensure that any custom intervals used in your cron jobs are correctly registered within your theme or plugin files. You may need to check with the plugin developer or add custom code to ensure WordPress recognizes these intervals.
  2. Manually Trigger Cron Jobs to Test To confirm that the new setup was working, I triggered the cron jobs manually:
  • Visit https://yourdomain.com/wp-cron.php in your browser. This URL manually triggers the cron process, helping to clear any backlog or overdue jobs.
  • If you have the WP Crontrol plugin installed, you can use it to manually run specific cron events, which is particularly useful for testing individual tasks.
  1. Wait for WP Engine’s Cron to Sync After enabling Alternate Cron, it’s important to give WP Engine’s system time to synchronize and catch up on any overdue jobs. Typically, WP Engine checks for scheduled cron jobs every hour, so allow at least an hour to see if overdue tasks are executed. In my case, I checked the cron events at 12:03 pm and then again at 1:05 pm. By 1:05 pm, the overdue jobs had successfully run, indicating that WP Engine’s Alternate Cron was now handling the tasks correctly.

Additional Tips for Troubleshooting Cron Jobs on WP Engine

If you continue to experience issues with cron jobs on WP Engine, here are a few additional tips:

  • Use the WP Crontrol Plugin: This plugin provides detailed insights into your cron jobs, including their scheduled run times, intervals, and actions. It allows you to manually run, edit, and delete cron jobs, which can be very helpful in troubleshooting.
  • Check Plugin Conflicts: Certain plugins, especially security or caching plugins, can interfere with cron jobs. If a specific cron job isn’t running, try disabling relevant plugins temporarily to see if it resolves the issue.
  • Review Custom Intervals: If any of your cron jobs use custom intervals, make sure these are registered correctly in your code. Without a properly registered interval, WordPress won’t know when to run the job.
  • Use Manual or System-Level Cron as a Backup: If WP Engine’s Alternate Cron still doesn’t provide the desired reliability, you could consider setting up a server-level cron job or using a third-party cron service. WP Engine’s support team can assist with these setups if necessary.

Conclusion

Using WP Engine’s Alternate Cron feature can significantly improve the reliability of WordPress cron jobs by removing dependency on page views. However, as with any custom setup, it may take a bit of tweaking and testing to get it running smoothly. By following these steps and leveraging tools like WP Crontrol, you can ensure that your scheduled tasks execute as expected, providing a seamless experience for your WordPress site.

Endnote

Keeping a record of these troubleshooting steps can be a time-saver in the future. If you encounter similar issues down the road, revisiting this guide will help you quickly identify and resolve cron job issues on WP Engine. Happy debugging!

]]>
Vuetify v-expansion-panels: Understanding v-model Tracking Behavior Differences https://priyank.rocks/vuetify-v-expansion-panels-understanding-v-model-tracking-behavior-differences/ Thu, 24 Oct 2024 04:05:15 +0000 https://priyank.rocks/?p=9591 In Vuetify’s v-expansion-panels component, there’s a significant difference in how v-model tracks selected panels between versions 2 and 3. Let’s explore this behavior:

Vuetify 2 Behavior

In Vuetify 2, v-model only tracks by index regardless of what you set as the 

1
:key
:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
&lt;!-- v-model ONLY tracks by index regardless of :key -->
&lt;v-expansion-panels v-model="selectedIndex">
    &lt;v-expansion-panel
        v-for="(item, index) in items"
        :key="item.value"  &lt;!-- This doesn't affect v-model behavior -->
    >
        &lt;v-expansion-panel-header>
            &lt;div :class="{ 'active': selectedIndex === index }">
                {{ item.text }}
            &lt;/div>
        &lt;/v-expansion-panel-header>
    &lt;/v-expansion-panel>
&lt;/v-expansion-panels>

&lt;script>
export default {
    data: () => ({
        selectedIndex: null  // Will be 0, 1, 2, etc.
    }),
    computed: {
        selectedValue() {
            return this.items&#91;selectedIndex]?.value;
        }
    }
}
&lt;/script>

The Gotcha

  • The v-model tracks by index (0, 1, 2, etc.)
  • The 
    1
    :key
     binding has no effect on tracking
  • Need a computed property to get the actual value

Vuetify 3 Behavior

Vuetify 3 introduces value tracking through the 

1
:value
 prop:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
&lt;!-- Can track by actual value using :value prop -->
&lt;v-expansion-panels v-model="selected">
    &lt;v-expansion-panel
        v-for="item in items"
        :key="item.id"
        :value="item.id"  &lt;!-- v-model will track this value -->
    >
        &lt;v-expansion-panel-header>
            {{ item.text }}
        &lt;/v-expansion-panel-header>
    &lt;/v-expansion-panel>
&lt;/v-expansion-panels>

&lt;script>
export default {
    data: () => ({
        selected: null  // Will be actual item.id value
    })
}
&lt;/script>

Improvements

  • Can track by custom values using 
    1
    :value
     prop
  • Directly stores the selected value in v-model
  • No need for computed properties to get actual values
  • More intuitive value tracking

Best Practices

Vuetify 2

  • Name variables to clearly indicate index tracking (e.g., selectedIndex)
  • Use computed properties to get actual values
  • Be explicit about index-based tracking in code comments

Vuetify 3

  • Can use semantic names for v-model variables
  • Utilize the 
    1
    :value
     prop for direct value tracking
  • More straightforward implementation

This change in Vuetify 3 represents a significant improvement in the developer experience, making the component behavior more intuitive and requiring less boilerplate code.

]]>
The Silent Bug: When forEach Meets filter in JavaScript https://priyank.rocks/the-silent-bug-when-foreach-meets-filter-in-javascript/ Tue, 22 Oct 2024 15:40:47 +0000 https://priyank.rocks/?p=9589 Have you ever written code that seemed perfectly logical but just didn’t work? Today, let’s dive into a subtle but common JavaScript bug that can trip up even experienced developers: using
1
forEach
inside a
1
filter
method.

The Problem

Consider this seemingly reasonable code for filtering items based on a specific condition:


1
2
3
4
5
6
7
8
9
10
filterItems(searchTerm) {
    let self = this;
    return self.items.filter((category) =&gt; {
        category.children.forEach((item) =&gt; {
            if (item.name === searchTerm) {
                return true;
            }
        });
    });
}

This code looks fine at first glance. It:

  1. Takes a search term as a parameter
  2. Filters through categories
  3. Checks each item in the category for a match
  4. Should return categories containing matching items

But it doesn’t work. At all. In fact, it will always return an empty array. Why?

Understanding the Issue

There are two key problems here:

1. forEach Doesn’t Return Anything

The

1
forEach
method is designed for executing code for each element – it always returns
1
undefined
. This means our
1
filter
callback receives
1
undefined
as its return value, causing
1
filter
to exclude every item.

2. Return Statement Scope

Even if

1
forEach
did return values, the
1
return true
statement inside the
1
forEach
callback only returns from that inner function, not from the
1
filter
callback. It’s equivalent to this:


1
2
3
4
5
6
7
8
filter((category) =&gt; {
    forEach((item) =&gt; {
        if (condition) {
            return true; // Only exits this inner function!
        }
    });
    // Implicitly returns undefined here
});

The Solution

Here’s the correct way to write this function:


1
2
3
4
5
6
7
filterItems(searchTerm) {
    return this.items.filter((category) =&gt; {
        return category.children.some((item) =&gt; {
            return item.name === searchTerm;
        });
    });
}

This version:

  1. Uses
    1
    some()
    instead of
    1
    forEach()
    1
    some()
    returns
    1
    true
    if any element matches the condition
  2. Properly chains return values through the callbacks
  3. Removes the unnecessary
    1
    self
    variable (arrow functions maintain the proper
    1
    this
    context)

Why This Works Better

The

1
some()
method is perfect for this use case because it:

  • Returns a boolean value (true/false)
  • Stops iterating once it finds a match (better performance)
  • Clearly communicates the intent: “does this category have some item matching our criteria?”

Lessons Learned

  1. Choose the Right Tool: Array methods have different purposes:
  • 1
    forEach
    : Execute code for each element
  • 1
    some
    : Check if any element matches a condition
  • 1
    filter
    : Create a new array with matching elements
  • 1
    map
    : Transform each element into something new
  1. Watch Your Return Scopes: Be careful with nested callbacks – make sure you’re returning from the right function.
  2. Consider Performance: Methods like
    1
    some()
    can be more efficient as they stop processing once they find a match.

Conclusion

This is a classic example of how using the wrong array method can lead to subtle bugs. When working with arrays in JavaScript, always consider:

  • What value do you need to return?
  • What is the scope of your return statements?
  • Is there a more appropriate array method for your use case?

Remember: Just because code looks correct doesn’t mean it will work as intended. Understanding these nuances is key to writing reliable JavaScript code.

Happy coding! 🚀

]]>
Resolving npm Installation Issues Related to Python and distutils https://priyank.rocks/resolving-npm-installation-issues-related-to-python-and-distutils/ Fri, 18 Oct 2024 05:37:40 +0000 https://priyank.rocks/?p=9587 Problem

While trying to install npm packages for a Vue.js project, I encountered errors related to the 

1
deasync
 package and Python’s 
1
distutils
 module. The error message indicated that 
1
distutils
 was not found, despite having Python installed on my system.

Diagnosis

  1. The project was using an older version of Node.js (v16.17.1).
  2. The system Python (version 3.13) did not include the distutils module.
  3. npm was not correctly configured to use a Python version with distutils available.

Solution

The issue was resolved by following these steps:

  1. Update Node.js to the latest LTS version:bashCopy
    1
    nvm use v20.11.1
  2. Verify Python 3.11 installation (which includes 
    1
    distutils
    ):bashCopy
    1
    /opt/homebrew/opt/python@3.11/bin/python3.11 --version
  3. Confirm 
    1
    distutils
     availability in Python 3.11:bashCopy
    1
    /opt/homebrew/opt/python@3.11/bin/python3.11 -c "import distutils; print('distutils is available')"
  4. Set npm to use Python 3.11:bashCopy
    1
    export npm_config_python=/opt/homebrew/opt/python@3.11/bin/python3.11
  5. Clear npm cache and reinstall dependencies:bashCopy
    1
    npm cache clean --force rm -rf node_modules package-lock.json npm install

Key Takeaways

  1. Python Version Matters: Newer versions of Python (3.12+) have removed 
    1
    distutils
    , which some npm packages rely on for compilation.
  2. Node.js and npm Compatibility: Ensure you’re using a compatible Node.js version for your project and npm version.
  3. npm Configuration: Properly configuring npm to use the correct Python version can resolve many installation issues.

Additional Notes

  • Consider using a Python version manager like 
    1
    pyenv
     for easier management of multiple Python versions.
  • For projects requiring specific Python versions, consider creating a virtual environment.
  • Regularly update your development tools and be aware of major changes in new versions that might affect your projects.

Remember, while this solution worked for my specific setup, your mileage may vary depending on your system configuration and project requirements.

]]>
Vuetify 2 v-treeview https://priyank.rocks/vuetify-2-v-treeview/ Tue, 03 Sep 2024 17:01:17 +0000 https://priyank.rocks/?p=9583 v-model works with selectable (checkbox)

The v-model updates but it only updates when the checkbox is used, which shows when selectable is added as an attribute.

I desired that, it should not work based on the checkbox but upon normal row-like selection. Not the checkbox.

@update:active="(a) => { updateActive(a) }" // selected ones
@update:open="(a) => { updateOpen(a) }" // the folders that are open
]]>
fatal: detected dubious ownership in repository at… https://priyank.rocks/fatal-detected-dubious-ownership-in-repository-at/ Wed, 21 Feb 2024 14:54:51 +0000 https://priyank.rocks/?p=9553 For me this was an error because I had the folder ownership given to www-data:ww-data. However, for my current aws ec2 user ubuntu was not able to do a git pull.

The easiest solution for me was to login as www-data:

sudo su -s /bin/bash www-data

]]>
Learning about V-list, V-list-item-group https://priyank.rocks/learning-about-v-list-v-list-item-group/ Fri, 30 Jun 2023 09:00:33 +0000 https://priyank.rocks/?p=9493 So, as we know we can set a value at v-list-item and a model at v-list-item-group. This works great for most cases.

I once had a bit different setup where, inside the v-list-item, I had several elements, and in that order viz. v-list-item-title, v-hover, v-row, v-col, v-menu, v-list, and v-list-item.

Now, the problem was, the value of the main v-list-item-group model was set to a random value when the v-list item was clicked (inside the v-menu). The solution then I found was, I set the value to the v-list-item (inside the v-menu) to the expected value. That resolved the value issue.

The second issue that appeared was since the v-list-item of the v-menu now has a value, and it’s also a current/active value of the model, it was solved then by the following:

I put flat to v-list, so that the background styling disappears, next the icon color was a bit heavy, which was then manually set to grey, the expected colour, via primary attribute. Last was the font-weight which was set to the v-list-item and that solved it.

In the ui we had a listing of some items, which had options of edit and delete.

]]>
WooCommerce custom code to hide some theme elements https://priyank.rocks/woocommerce-custom-code-to-hide-some-theme-elements/ Fri, 23 Jun 2023 07:16:51 +0000 https://priyank.rocks/?p=9489
1
2
3
4
5
6
7
8
9
10
11
12
13
// Woocommerce, hide the customer reviews ui

jQuery(document).ready(function(){

    jQuery('.woocommerce .woocommerce-product-rating').hide();
    jQuery('.woocommerce .edgtf-social-share-holder').hide();
    jQuery('.woocommerce-tabs .edgtf-tabs-nav').find('li').eq(1).hide();
    jQuery('.woocommerce-tabs .edgtf-tabs-nav').find('li').eq(2).hide();

    // hide related products
    jQuery('.woocommerce .related.products').hide();

});

]]>
Validating image existence on the client side with JavaScript, Vue & Vuetify https://priyank.rocks/validating-image-existence-on-client-side-with-javascript-vue-vuetify/ Tue, 13 Jun 2023 05:28:37 +0000 https://priyank.rocks/?p=9484 Validating an image path on a client-side is slightly tricky. It is easy with
1
&lt;v-img @error
for simple usage but for a more real-world or complex setup, where we want to programmatically check whether the image path is valid or not is slightly tricky. 

1
2
3
<v-img v-if="!showIconFromCommon && !showInitials"
                       :src="getIconPath()" :title="appName" @error="setShowIconFromCommon"
                />

However, with the following function, life is easy. One thing to note though: it throws a browser error, if the image is found missing. I’m yet to look into if the error can be suppressed by wrapping a try/catch block.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// CHECK IF IMAGE EXISTS
        checkIfImageExists (url, callback) {
            const img = new Image()
            img.src = url

            if (img.complete) {
                callback(true)
            } else {
                img.onload = () => {
                    callback(true)
                }

                img.onerror = () => {
                    callback(false)
                }
            }
        },

Usage:

1
2
3
4
5
6
7
                self.checkIfImageExists(self.getIconPath(), (exists) => {
                    if (exists) {
                        self.showIconFromCommon = false
                        self.showInitials = false
                    } else {
}
                })
]]>