Difference between || and ?? operators

 https://stackoverflow.com/questions/61480993/when-should-i-use-nullish-coalescing-vs-logical-or

The OR operator || uses the right value if left is falsy, while the nullish coalescing operator ?? uses the right value if left is null or undefined.

These operators are often used to provide a default value if the first one is missing.

But the OR operator || can be problematic if your left value might contain "" or 0 or false (because these are falsy values):

console.log(12 || "not found") // 12
console.log(0  || "not found") // "not found"

console.log("jane" || "not found") // "jane"
console.log(""     || "not found") // "not found"

console.log(true  || "not found") // true
console.log(false || "not found") // "not found"

console.log(undefined || "not found") // "not found"
console.log(null      || "not found") // "not found"

In many cases, you might only want the right value if left is null or undefined. That's what the nullish coalescing operator ?? is for:

console.log(12 ?? "not found") // 12
console.log(0  ?? "not found") // 0

console.log("jane" ?? "not found") // "jane"
console.log(""     ?? "not found") // ""

console.log(true  ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null      ?? "not found") // "not found"

While the ?? operator isn't available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:

The ?? operator was added to TypeScript 3.7 back in November 2019.

And more recently, the ?? operator was included in ES2020, which is supported by Node 14 (released in April 2020).

When the nullish coalescing operator ?? is supported, I typically use it instead of the OR operator || (unless there's a good reason not to).

Git Undo Merge: A Guide

 https://careerkarma.com/blog/git-undo-merge/

You can undo a Git merge using the git reset –merge command. This command changes all files that are different between your current repository and a particular commit. There is no “git undo merge” command but the git reset command works well to undo a merge.

How to Undo a Git Merge

Have you just merged two branches that you’re not ready to merge? Not to worry, Git has a solution for you. Developers merge branches all the time that should not be branched, so you’re definitely not alone in experiencing this issue.

In this tutorial, we’re going to talk about git merges and how to undo a git merge. We’ll walk through an example of two approaches you can use to undo a git merge. Let’s begin!

Git Merges

Git relies heavily on branches. These are used to maintain separate lines of development inside a project. Branches allow you to work on multiple different versions of a repository at once. Merging combines two branches into one.

You can merge a branch into another branch whenever you are ready. This means that you can develop a feature or a bug fix on a separate branch. Then, you can make it part of your main project later.

Git Undo Merge

To undo a git merge, you need to find the commit ID of your last commit. Then, you need to use the git reset command to reset your repository to its state in that commit. There is no “git revert merge” command.

The steps to revert a merge, in order, are:

  • git log OR git reflog (to find the last commit ID)
  • git reset –merge (to revert to the commit you specify)

Say we have accidentally merged two branches that should not be merged. We can undo these changes.

Undo Merge Git Example

Find the Commit ID

To start, we need to find out the commit ID of the commit before our merge on our remote repository. You can do this using git reflog:

git reflog

Let’s run this command on a Git repository:

ac7188c HEAD@{6}: commit: feat: Push example code for innerText and innerHTML tutorial
a9fdeb5 HEAD@{7}: commit (initial): feat: Merge dev-fix-7 into master

This command tells us that the last commit has the hash a9fdeb5.

Alternatively, you can use the git log command. But, the reflog command returns an output that is easier to read. This is why we opted to use reflog instead of the log command.

Revert to the Commit

We can use this hash to revert the merge commit with the git reset –merge command:

git reset --merge a9fdeb5

This command resets our repository to the state it was at in the a9fdeb5 commit on the master branch.

The –merge flag resets an index and updates all the files that are different between the current state of your repository and the HEAD.

This flag does not reset files with changes that have not been added to a commit. This makes it safer than using the oft-recommended git reset –hard command.

Once we have reset our repository, we can make the relevant changes to our code. Then, we can push them to a remote branch using the git push command.

A Word on the HEAD Shorthand

The Git HEAD keyword refers to the latest commit in your repository. You can use the Git HEAD shorthand to undo a merge:

git reset --merge HEAD~1

This command reverts our repository to the last commit. HEAD refers to the current state of your repository; HEAD~1 is the last commit in your repository.

This command reverts our repository to the last commit. HEAD refers to the current state of your repository; HEAD~1 is the last commit in your repository.

Conclusion

The git reset command undoes a merge. The –merge flag resets a repository but keeps files to which changes have been made that have not been added to your repository.

Are you interested in learning more about Git? Check out our How to Learn Git guide. In this guide, you’ll find advice on how to learn Git and a list of top learning resources.

What is a Wildcard DNS record?

 https://kb.porkbun.com/article/94-what-is-a-wildcard-dns-record

A wildcard DNS record is a record that answers DNS requests for any subdomain you haven't already defined. You can create wildcard A records and CNAME records by entering an asterisk (*) in the Host field when creating a DNS record.

For example, if you create the wildcard A record  *.goosehollow.design and someone visits https://abcdef.goosehollow.design, their request will resolve to the IP address you specified as the answer.

GatsbyJs - Add environment variables

 https://dev.to/kapilgorve/gatsbyjs-add-environment-variables-1io5

Development Environment

  • Create a new file named as .env.development at the root of your project.
  • Add your variable to the newly created file. Example - TEST_KEY=123
  • Change your npm run develop command to set environment.

For Windows -

    "develop": "set GATSBY_ENV=development && gatsby develop"

For Linux -

    "develop": "GATSBY_ENV=development gatsby develop"
  • Restart your dev environment. So Gatsby will load your new env file.
  • You should be able to access your env variables using process.env.TEST_KEY in any js file.

Production Environment

  • Create a new file named as .env.production at the root of your project.
  • Add your variable to the newly created file. Example - TEST_KEY=123
  • Change your npm run build command to set environment.

For Windows -

    "develop": "set GATSBY_ENV=production && gatsby develop"

For Linux -

    "build": "GATSBY_ENV=production gatsby build",

This is only if you want to build on local.

If you are using any providers like Netlify use the Linux version. You will also need to add environment variables in the service provider.

For Netlify it is in Site Settings > Build&Deploy > Environment

This post was originally published at https://www.jskap.com/blog/gatsby-add-environment-variables/

How to stretch the background image to fill a div

 https://stackoverflow.com/questions/11223585/how-to-stretch-the-background-image-to-fill-a-div

Add

background-size:100% 100%;

to your css underneath background-image.

You can also specify exact dimensions, i.e.:

background-size: 30px 40px;

Axios: chaining multiple API requests

 https://stackoverflow.com/questions/44182951/axios-chaining-multiple-api-requests


        const tokenInput = JSON.stringify({
                ...
            });
        const Agent = new https.Agent({
            rejectUnauthorized: false
        })
        // call for access token
        const [tokenResponse] = await Promise.all([axios
            .post(process.env.TOKEN_URL, tokenInput, {
                httpsAgent: Agent,
                headers: {
                  // Overwrite Axios's automatically set Content-Type
                  'Content-Type': 'application/json'
                }
            })
        ]);
        // check token
        const accessToken = tokenResponse.data.result.accessToken;
        // check access token
        if (!tokenResponse.data.result.accessToken) {
            return;
        }

        /**
         * prepare data to post
         */
        const postData = JSON.stringify({
            ....
        });

        axios
        .post(process.env.FORM_URL, postData, {
            httpsAgent: Agent,
            headers: {
              // Overwrite Axios's automatically set Content-Type
              'Content-Type': 'application/json'
            }
        })
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          console.error(error)
        })

First off, not sure you want to do this in your componentWillMount, it's better to have it in componentDidMount and have some default states that will update once done with these requests. Second, you want to limit the number of setStates you write because they might cause additional re-renders, here is a solution using async/await:

async componentDidMount() {

  // Make first two requests
  const [firstResponse, secondResponse] = await Promise.all([
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p1}`),
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p2}`)
  ]);

  // Make third request using responses from the first two
  const thirdResponse = await axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + firstResponse.data.results.place_id + '&destination=place_id:' + secondResponse.data.results.place_id + '&key=' + 'API-KEY-HIDDEN');

  // Update state once with all 3 responses
  this.setState({
    p1Location: firstResponse.data,
    p2Location: secondResponse.data,
    route: thirdResponse.data,
  });

}

WordPress GraphQL vs Gatsby GraphQL

 https://www.gatsbyjs.com/blog/getting-started-with-gatsby-source-wordpress-choose-your-own-adventure/

The query names you see here aren’t the same as the query names you’ll be using in Gatsby, so by all means peruse it at your leisure. However, we won’t be using quite the same query names in the following steps. (This is because with Gatsby, in order to avoid query-clash between different platforms, any WordPress-specific query usually contains the letters “Wp” to identify it as WordPress related. Plural queries are prefixed with “all”. Don’t worry, I’ll show you the diff).

Here’s a side by side equivalent GraphQL query to show an example of one of the main differences: 

 

WordPress GraphQL

Gatsby GraphQL

{
  pages {
    nodes {
      title
    }
  }
}
{
  allWpPage {
    nodes {
      title
    }
  }
}

 

Back on the GraphQL page, below the GraphQL Endpoint item and input field at the very top, you’ll see a url for the new GraphQL endpoint. Make a note of this, since we will be using it in the next step ➡️.

wpgraphql: Node & Global ID

https://www.wpgraphql.com/docs/wpgraphql-concepts/ 

Every object in WordPress is treated as an individual "node" in GraphQL. Posts are nodes. Pages are nodes. Categories, tags, users, comments, menu items, etc are all considered "nodes".

And each "node" in the Graph can be identified by a unique ID.

In WordPress, IDs are not truly unique. There can be a Post with ID 1, a User with ID 1, a Category with ID 1 and a Comment with ID 1. WPGraphQL generates opaque global IDs for entities by hashing the underlying loader type and the database id. So, objects loaded by the Post loader get a global ID of base_64_encode( 'post:' . $database_id );. So, a Post with the database ID of 1 would have a global ID of cG9zdDox.

jquery-tabs

 https://gist.github.com/chrisguitarguy/1237619


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery('ul.tab-nav li').click(function(e){
		var tab_id = jQuery(this).attr('id');
		jQuery('ul.tab-nav li').removeClass('active');
		$(this).addClass('active');
		jQuery('.tab-container div.tab').hide();
		jQuery('.tab-container div#' + tab_id + '-tab').show();
	});
	jQuery('ul.tab-nav li:first-child').trigger('click');
});
</script>


<div class="tab-container">
	<ul class="tab-nav">
		<li id="one">One Tab</li>
		<li id="two">Two Tabs</li>
		<li id="three">Three Tabs</li>
	</ul>
	<div class="tab" id="one-tab">
		test
	</div>
	<div class="tab" id="two-tab">
	        test 1
	</div>
	<div class="tab" id="three-tab">
	        test 2
	</div>
</div>

anti-pattern là gì

  Trong công nghệ và lập trình, Anti-pattern (mẫu phản diện) là những giải pháp bề ngoài có vẻ hiệu quả để giải quyết một vấn đề phổ biến, ...