Categories
Coding

How to detect English/ASCII string in PHP

There is not direct function for this in my knowledge. But it can be done easily like so.

if ( mb_strlen( $string, 'ASCII' ) === mb_strlen( $string, 'utf-8' ) ) {
    return true;
}
Categories
Business

The state of automobile dealerships in India

My father had a "not-so-great" experience during routine service of his two-wheeler vehicle at a Honda service-center at my hometown. And it is the same for most dealerships and service outlets of major automobile companies in Tier-2 and Tier-3 cities in India.

These dealerships are operated as local businesses and though they adhere to company standards, they do not have consistent service quality across outlets.

Usually these dealers have monopoly in their area for the given brand as it is not easy to replace a dealer due to various factors like lengthy compliance requirements, less number of eligible people and high costs involved.

That’s why even after multiple customer complaints, these dealerships keep going on even with their poor service quality without any substantial action from the automobile company. This, along with lack of competition, makes them even more complacent.

A "perfect" world would be where every business strives to give best service to its customers. But as they say, nothing is "perfect".

servicequality #automobile #dealership

Categories
Javascript

Sending JSON with data Javascript Fetch

An important reminder to include following header while sending data in Javascript fetch() call in JSON format.

Also, do not forget to use JSON.Stringify().

var data = { some_data: ABC};
headers: {
    'Content-Type': 'application/json',
},
body: JSON.stringify( data ),

This is not needed if you are creating a form data object and appending data to it.

var data = new FormData();
data.append( 'some_data', 'ABC' );
Categories
WordPress

Disable RSS Feed Pages in WordPress

To disable RSS feed pages in WordPress, hook into the action filters provided for each feed page function and then redirect to the home page.

// Disable RSS feed pages
add_action( 'do_feed', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rdf', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rss', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rss2', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_atom', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rss2_comments', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_atom_comments', 'disable_rss_feed_pages', 1);

function disable_rss_feed_pages() {
    wp_redirect( site_url() );
    exit();
}
Categories
Finance

Safety & Liquidity of Debt Mutual Funds

Yesterday I wrote an article about Debt Mutual Funds.

I got a few questions about the liquidity and safety of a particular fund. So, I am adding a few more points.

Many Debt Mutual Funds like Nippon, Axis and HDFC offer instant redemption and you get the money within 30 minutes.

Safety of money means that the fund will not run away with your money. Market risk is there but it is almost zero for short-duration funds invested for a longer term.

In the past, withdrawals have been restricted even in the case of prestigious banks when the banks were facing issues.

Obviously, you should not blindly go for any Debt Mutual Fund just like you do not go for any FD offered at much higher interest rates by various NBFCs and smaller banks.

Similarly, in the case of Debt Mutual Fund, it all depends on various factors like the fund’s category, company, fund manager, duration of investment, past record, etc.

My article is about the overall advantages of Debt Mutual Fund over FDs and of course, both have their share of pros and cons. And there may be exceptional edge cases as well.

Only after considering all the factors should you make your investment decision.

investment #mutualfund #fixeddeposit

Categories
Finance

FDs are destroying your wealth

If you are still making FDs of your monthly savings, you are destroying your wealth.

Interest on FDs is taxable. That means the current interest rate of about 5.5% effectively gives you ~3.8% return on your money (Assuming you fall in the highest income tax slab).

With more than 6% inflation, your money is losing its value.

DEBT Mutual Funds is a better alternative which is tax efficient, gives better returns and is quite safe.

Debt Mutual Funds are different than EQUITY Mutual Funds because they lend your money to government & companies rather than investing it in the stock market.

A good Debt Mutual Fund can give you better returns than FDs, depending on the fund’s category.

A few benefits are-

  • Mutual Funds in India are very tightly regulated, so your money is as safe as it was in the bank.

  • You will be taxed only if you withdraw the money. So, if you do not withdraw the money, you will have to pay ZERO taxes on the return.

  • If you withdraw money after 3 or more years, you get indexation benefit which further reduces income tax to an effective rate of 6-7%.

  • SEBI has defined different categories for Debt Mutual Funds based on the duration of loans and the type of companies to which loans are given.

That means for safer investment, you can go for the funds with shortest duration or those that give loans only to the reputed companies.

  • There is no penalty for withdrawing money early, unlike FDs where you pay penalty if you withdraw the money before completing the term.

  • Debt Mutual Funds are highly liquid & you can withdraw your money in minutes. So, you can avoid keeping large sums of money in the savings account.

So, it seems like a good time to move your money from FDs to Debt Mutual Funds.

Categories
Finance

A useful tip to save upto Rs.15k in tax: Section 80TTB for Senior Citizens

As we are just 2 days away from the last date of filing income tax return, here is a useful tip to save upto Rs.15k in tax.

If you are helping out a senior citizen in filing their Income Tax Return, do not forget section 80TTB which allows Rs.50k deduction on their interest income from both bank FDs and savings.

This can save them upto Rs.15k if they fall in the highest income tax slab.

On the contrary, section 80TTA which is applicable to individuals less than 60 years old, allows deduction upto Rs.10k that too only on the savings interest income.

itr #tax #incometaxreturn

Categories
WordPress

WordPress adding slashes in POST requests

WordPress adds slashes before quotes even if we do not want to use magic quotes.

To solve this problem, you can use either of the following two functions on the values returned from POST requests-

  • wp_unslash
  • stripslashes_deep

References:

Categories
Coding

How to disable translation pop-up on website in Google Chrome

Google Chrome on Android tries to show pages in user’s preferred language by continuously showing translation pop-up on each page load. This happens when website content is in a different language than user’s preferred language.

But this creates issues in user experience by hiding bottom content on website. My site had fixed bottom navigation bar which was getting hidden by the translation pop-up and was badly ruining user experience by making it unusable at times.

So, to disable these translation features, there are some meta tags that you can add to the head section of all your webpages.

<!-- Disable translation in Google search -->
<meta name="googlebot" content="notranslate" />
<!-- Disable translation widget on Chrome -->
<meta name="google" content="notranslate" />

The first meta tag disables translation in Google Search results, and the second one disables translation pop-up in Chrome.

Problem solved.

References:

Categories
WordPress

How to Modify Title Tag in WordPress

I always missed a function to directly change the title tag in WordPress template. But here is a function which can do that for you.

function modify_title( $new_title ) {
    add_action( 'pre_get_document_title', function( $current_title ) use( $new_title ) {
        return $new_title;
    }, 9999 );
}

Please note that this function uses use keyword to bind variables into anonymous function’s scope. Learn more

Categories
Coding

Restrict number of selected checkboxes in html

This code will restrict html multi select input to given number.

document.addEventListener( "click", function( event ) {
    if ( event.target.matches( '.input-checkbox' ) ) {
        var inputCheckboxes = document.querySelectorAll( '.input-checkbox[type="checkbox"]:checked' );
        if( inputCheckboxes.length > 3 ) {
            event.preventDefault();
            alert( 'You cannot select more than 3 categories for a post.' );
        }
    }
} );
Categories
WordPress

WP_Query by URL for Infinite Scroll in WordPress

I was trying to create an infinite scroll in WordPress. All I wanted was to parse the next page url without making any changes to the code so that the code becomes interoperable with the pagination templates.

To achieve that, instead of passing custom query parameters to the API, I decided to parse the next page url to run WP_Query without mentioning any additional parameters.

Steps were:

  1. Get the next page url
  2. Parse it to get query parameters of next page
  3. Run WP_Query on that and get the posts of next page

Though I spent hours on this, it turned out to be rather simple.

// Get the url of the next page
$next_page_url = $args[ 'next_page_url' ] ?? $_SERVER['REQUEST_URI'];

// Save the next page url in the current global server variable array
$_SERVER['REQUEST_URI'] = $current_page_url;

// Rebuild the global $_GET variable to include the new query string parameters
parse_str( parse_url( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ?? '', PHP_URL_QUERY ), $_GET );

// Run the wp_query to get the posts of next page
$wp->parse_request();
$wp->query_posts();
$all_posts = $wp_query->posts;

Just replace your pagination links with an element which passes the next page url to the API when it becomes visible. And you can get the posts HTML from the API.

And that’s it. Your infinite scroll is ready.

References:

  1. https://medium.com/@harryhorton/query-wp-rest-api-using-any-permalink-url-f5e4e4dd36b7
Categories
Coding

MySQL Disk Size Issue

I was facing a strange issue on one of my servers. Storage was getting full even when I did not upload any extra files.

Turned out it was a MySQL logging issue and got resolved only when I disabled logging.

References:

  1. https://www.christophe-casalegno.com/mysql-how-to-purge-binary-logs-when-you-have-no-space-left-on-device/

  2. https://www.alittleofboth.com/2020/04/droplet-out-of-disk-space/

  3. https://www.digitalocean.com/community/questions/where-did-my-disc-space-go

Categories
Productivity

JPG Image Compression

When you upload images to Facebook or Whatsapp, you must have noticed a reduction in size and quality of the image. Though the image looks fine on most devices, its size get reduced by over 95%. The reason is compression.

It is recommended to compress the images before uploading them to your blog or website. This helps in reducing the bandwidth usage and increase in site speed.

For JPG, my recommended compression settings are 60%.

I noticed that it is best for images being hosted on websites and there is no visible image degradation.

There is a good JPG compression website- https://compressjpeg.com/.

Though this site is good and easy to use, by default it compresses images at different compression ratios for every image. Though you can customize it by clicking the thumbnail of each image, it is not so convenient.

My recommended image compression website is https://bulkresizephotos.com

You can compress images in bulk with the same settings.

Here is the url with predefined setting of 60% compression ratio- https://bulkresizephotos.com/en?preset=true&quality=0.6&value=100

Categories
Coding

Why click event not working on SVG

I created a simple menu with SVG icons and to my surprise, clicking on the icon was not taking me to the linked url.

It turned out that as SVGs are independent HTML objects, the target element is actually nested path. So, it does not match with the clicked element and thus click event listeners does not work on it.

Similarly, if you add others event listeners to the parent element of the SVG’s, it does not work.

There are multiple ways to fix this-

  1. Disable click on SVG elements by adding the CSS- pointer-events: none;

  2. Add event listener to the path element of SVG.

Problem solved.

References:

  1. https://gomakethings.com/detecting-click-events-on-svgs-with-vanilla-js-event-delegation/
Categories
Coding

Add event listener on SVG element

I was facing problem while adding event listener to an svg element.

Then I added event listeners to both svg and path tags, and it worked.

Categories
Work Culture

When my boss told me not to prepare for CAT

"Don’t prepare for CAT if you want to succeed here."

Those were the words of the manager of my first project.

I was a fresher B. Tech graduate in my first job and had joined my first project along with a few others. Our manager called us into his cabin for a casual introduction session.

His first words were, "Do not prepare for CAT or any government job exam if you want to succeed here. Stay here for a long time, and only then you will grow in your career." He also individually asked everyone if we were preparing for some exam and made sure we all said no.

That was his way of imposing employee retention by forcing people not to pursue better career opportunities. It was clear that if I shared my MBA plans with him, I was not getting any promotion no matter how well I did my job.

But did it stop me from pursuing my dream of getting into an IIM? No. But it did stop me from sharing about my CAT preparation with him.

I was committed to my work and did the best I could. At the same time, I spent my weekends preparing for CAT. It was very hectic, but somehow I managed.

After a year and a half, I got a promotion in my job and, at the same time, secured admission offers from multiple IIMs and other top MBA colleges in India.

I did not want to hide my preparation, but If I had told him, I could not get that promotion, even though I deserved that. That promotion was crucial for my career, in case, I could not pursue MBA.

You cannot retain employees by forcing them. Why not give them such a great environment that leaving becomes impossible.

And even if they leave, they would be willing to come back whenever possible. Wouldn’t it be great!

#work #career #mba #iim
Categories
Technology

Will electric cars ever succeed?

Many people think that electric cars cannot replace petrol cars due to high charging time and low battery capacity. Range anxiety is a big issue with electric cars today.

This reminds me of the range anxiety of smartphone batteries we had just a few years ago. While traveling, we were always worried about whether our smartphone battery would discharge before we reached home or if we would find a charging slot on the way.

Even the highest-priced smartphones did not have the battery capacity offered by the lowest-priced smartphones of today. But everything changed as it became a differentiating factor for the mobile phone manufacturers.

Suddenly the technology started to evolve. High-capacity batteries became financially viable. And the massive scale achieved due to high demand reinforced the innovation.

It started with the emergence of power banks which proved very useful for some time. But they were a part of the evolution soon replaced by even better technology.

As a result of that demand-led innovation, today, in just a few years, we have 120-watt mobile chargers compared to 5-watt chargers just a few years back. This has drastically reduced the charging time.

And the battery capacity has increased enough to ensure that our mobile phones work for days on a single charge, even with heavy usage.

We do not worry about battery capacity of mobile phones anymore. The range anxiety is gone as if it was never an issue.

I know it is not exactly an apples-to-apples comparison, but it does give us a good perspective on the possible future of electric cars. It may seem far-fetched and improbable today, but we never know if it is just the beginning of another era of demand-led innovation.

#innovation #electriccars #technology
Categories
Startup

Startups going back to the old models

Life comes full circle!

Big EdTech startups who created so much hype about online education are returning to the offline coaching center model.

Similarly, we are returning to the auto-rickshaws from the golden days of on-demand app-based cab services.

Raising and spending investors’ money may be necessary for fast-paced growth, but it is equally important to focus on the quality and feasibility of the actual product.

#startups
Categories
Life

Beauty of randomness in life

I do not mean to offend anyone but lately I have observed a peculiar trend in my LinkedIn feed.

A lot of people are posting random stories about small instances from their daily life and trying to create analogies with something meaningful to bring out great learnings out of that.

To be honest, sometimes these analogies make sense, but most of the time they seem too much forced trying to find meaning out of everything.

Somethings in life are random and randomness has its own beauty.