Consuming REST APIs In React With Fetch And Axios

Consuming REST APIs In React With Fetch And Axios

https://ift.tt/2BnRrLK

Consuming REST APIs In React With Fetch And Axios

Shedrack Akintayo



Consuming REST APIs in a React Application can be done in various ways, but in this tutorial, we will be discussing how we can consume REST APIs using two of the most popular methods known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API). I will discuss and implement each of these methods in detail and shed light on some of the cool features each of them have to offer.

APIs are what we can use to supercharge our React applications with data. There are certain operations that can’t be done on the client-side, so these operations are implemented on the server-side. We can then use the APIs to consume the data on the client-side.

APIs consist of a set of data, that is often in JSON format with specified endpoints. When we access data from an API, we want to access specific endpoints within that API framework. We can also say that an API is a contractual agreement between two services over the shape of request and response. The code is just a byproduct. It also contains the terms of this data exchange.

In React, there are various ways we can consume REST APIs in our applications, these ways include using the JavaScript inbuilt fetch() method and Axios which is a promise-based HTTP client for the browser and Node.js.

Note: A good knowledge of ReactJS, React Hooks, JavaScript and CSS will come in handy as you work your way throughout this tutorial.

Let’s get started with learning more about the REST API.

What Is A REST API

A REST API is an API that follows what is structured in accordance with the REST Structure for APIs. REST stands for “Representational State Transfer”. It consists of various rules that developers follow when creating APIs.

The Benefits Of REST APIs

  1. Very easy to learn and understand;
  2. It provides developers with the ability to organize complicated applications into simple resources;
  3. It easy for external clients to build on your REST API without any complications;
  4. It is very easy to scale;
  5. A REST API is not language or platform-specific, but can be consumed with any language or run on any platform.

An Example Of A REST API Response

The way a REST API is structured depends on the product it’s been made for — but the rules of REST must be followed.

The sample response below is from the Github Open API. We’ll be using this API to build a React app later on in this tutorial.

{
"login": "hacktivist123",
"id": 26572907,
"node_id": "MDQ6VXNlcjI2NTcyOTA3",
"avatar_url": "https://avatars3.githubusercontent.com/u/26572907?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/hacktivist123",
"html_url": "https://github.com/hacktivist123",
"followers_url": "https://api.github.com/users/hacktivist123/followers",
"following_url": "https://api.github.com/users/hacktivist123/following{/other_user}",
"gists_url": "https://api.github.com/users/hacktivist123/gists{/gist_id}",
"starred_url": "https://api.github.com/users/hacktivist123/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/hacktivist123/subscriptions",
"organizations_url": "https://api.github.com/users/hacktivist123/orgs",
"repos_url": "https://api.github.com/users/hacktivist123/repos",
"events_url": "https://api.github.com/users/hacktivist123/events{/privacy}",
"received_events_url": "https://api.github.com/users/hacktivist123/received_events",
"type": "User",
"site_admin": false,
"name": "Shedrack akintayo",
"company": null,
"blog": "https://sheddy.xyz",
"location": "Lagos, Nigeria ",
"email": null,
"hireable": true,
"bio": "☕ Software Engineer | | Developer Advocate🥑|| ❤ Everything JavaScript",
"public_repos": 68,
"public_gists": 1,
"followers": 130,
"following": 246,
"created_at": "2017-03-21T12:55:48Z",
"updated_at": "2020-05-11T13:02:57Z"
} 

The response above is from the Github REST API when I make a GET request to the following endpoint https://api.github.com/users/hacktivist123. It returns all the stored data about a user called hacktivist123. With this response, we can decide to render it whichever way we like in our React app.

Consuming APIs Using The Fetch API

The fetch() API is an inbuilt JavaScript method for getting resources from a server or an API endpoint. It’s similar to XMLHttpRequest, but the fetch API provides a more powerful and flexible feature set.

It defines concepts such as CORS and the HTTP Origin header semantics, supplanting their separate definitions elsewhere.

The fetch() API method always takes in a compulsory argument, which is the path or URL to the resource you want to fetch. It returns a promise that points to the response from the request, whether the request is successful or not. You can also optionally pass in an init options object as the second argument.

Once a response has been fetched, there are several inbuilt methods available to define what the body content is and how it should be handled.

The Difference Between The Fetch API And jQuery Ajax

The Fetch API is different from jQuery Ajax in three main ways, which are:

  1. The promise returned from a fetch() request will not reject when there’s an HTTP error, no matter the nature of the response status. Instead, it will resolve the request normally, if the response status code is a 400 or 500 type code, it’ll set the ok status. A request will only be rejected either because of network failure or if something is preventing the request from completing
  2. fetch() will not allow the use of cross-site cookies i.e you cannot carry out a cross-site session using fetch()
  3. fetch() will also not send cookies by default unless you set the credentials in the init option.

Parameters For The Fetch API

  • resource
    This is the path to the resource you want to fetch, this can either be a direct link to the resource path or a request object
  • init
    This is an object containing any custom setting or credentials you’ll like to provide for your fetch() request. The following are a few of the possible options that can be contained in the init object:

    • method
      This is for specifying the HTTP request method e.g GET, POST, etc.
    • headers
      This is for specifying any headers you would like to add to your request, usually contained in an object or an object literal.
    • body
      This is for specifying a body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object
    • mode
      This is for specifying the mode you want to use for the request, e.g., cors, no-cors, or same-origin.
    • credentials
      This for specifying the request credentials you want to use for the request, this option must be provided if you consider sending cookies automatically for the current domain.

Basic Syntax for Using the Fetch() API

A basic fetch request is really simple to write, take a look at the following code:

fetch('https://api.github.com/users/hacktivist123/repos')
  .then(response => response.json())
  .then(data => console.log(data));

In the code above, we are fetching data from a URL that returns data as JSON and then printing it to the console. The simplest form of using fetch() often takes just one argument which is the path to the resource you want to fetch and then return a promise containing the response from the fetch request. This response is an object.

The response is just a regular HTTP response and not the actual JSON. In other to get the JSON body content from the response, we’d have to change the response to actual JSON using the json() method on the response.

Using Fetch API In React Apps

Using the Fetch API in React Apps is the normal way we’d use the Fetch API in javascript, there is no change in syntax, the only issue is deciding where to make the fetch request in our React Apps. Most fetch requests or any HTTP request of any sort is usually done in a React Component.

This request can either be made inside a Lifecycle Method if your component is a Class Component or inside a useEffect() React Hook if your component is a Functional Component.

For example, In the code below, we will make a fetch request inside a class component, which means we’ll have to do it inside a lifecycle method. In this particular case, our fetch request will be made inside a componentDidMount lifecycle method because we want to make the request just after our React Component has mounted.

import React from 'react';

class myComponent extends React.Component {
  componentDidMount() {
    const apiUrl = 'https://api.github.com/users/hacktivist123/repos';
    fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => console.log('This is your data', data));
  }
  render() {
    return <h1>my Component has Mounted, Check the browser 'console' </h1>;
  }
}
o
export default myComponent;

In the code above, we are creating a very simple class component that makes a fetch request that logs the final data from the fetch request we have made to the API URL into the browser console after the React component has finished mounting.

The fetch() method takes in the path to the resource we want to fetch, which is assigned to a variable called apiUrl. After the fetch request has been completed it returns a promise that contains a response object. Then, we are extracting the JSON body content from the response using the json() method, finally we log the final data from the promise into the console.

Let’s Consume A REST API With Fetch Method

In this section, we will be building a simple react application that consumes an external API, we will be using the Fetch method to consume the API.

The simple application will display all the repositories and their description that belongs to a particular user. For this tutorial, I’ll be using my GitHub username, you can also use yours if you wish.

The first thing we need to do is to generate our React app by using create-react-app:

npx create-react-app myRepos

The command above will bootstrap a new React app for us. As soon as our new app has been created, all that’s left to do is to run the following command and begin coding:

npm start

If our React is created properly we should see this in our browser window when we navigate to localhost:3000 after running the above command.


Initial App Screen
(Large preview)

In your src folder, create a new folder called component. This folder will hold all of our React components. In the new folder, create two files titled List.js and withListLoading.js. These two files will hold the components that will be needed in our app.

The List.js file will handle the display of our Repositories in the form of a list, and the withListLoading.js file will hold a higher-order component that will be displayed when the Fetch request we will be making is still ongoing.

In the List.js file we created inside the components folder, let’s paste in the following code:

import React from 'react';
const List = (props) => {
  const { repos } = props;
  if (!repos) return null;
  if (repos.length === 0) return <p>No repos, sorry</p>;
  return (
    <ul>
      <h2 className='list-head'>Available Public Repositories</h2>
      {repos.map((repo) => {
        return (
          <li key={repo.id} className='list'>
            <span className='repo-text'>{repo.name} </span>
            <span className='repo-description'>{repo.description}</span>
          </li>
        );
      })}
    </ul>
  );
};
export default List;

The code above is a basic React list component that would display the data, in this case, the repositories name and their descriptions in a list.

Now, Let me explain the code bit by bit.

const { repos } = props;

We are initializing a prop for the component called repos.

if (!repos) return null;
  if (repos.length === 0) return 

No repos, sorry

;

Here, all we are doing is making a conditional statement that will render a message when the length of the repos we get from the request we make is equal to zero.

return (
    <ul>
      <h2 className='list-head'>Available Public Repositories</h2>
      {repos.map((repo) => {
        return (
          <li key={repo.id} className='list'>
            <span className='repo-text'>{repo.name} </span>
            <span className='repo-description'>{repo.description}</span>
          </li>
        );
      })}
    </ul>
  );

Here, we are mapping through each of the repositories that will be provided by the API request we make and extracting each of the repositories names and their descriptions then we are displaying each of them in a list.

export default List;

Here we are exporting our List component so that we can use it somewhere else.

In the withListLoading.js file we created inside the components folder, let’s paste in the following code:

import React from 'react';

function WithListLoading(Component) {
  return function WihLoadingComponent({ isLoading, ...props }) {
    if (!isLoading) return <Component {...props} />;
    return (
      <p style=>
        Hold on, fetching data may take some time :)
      </p>
    );
  };
}
export default WithListLoading;

The code above is a higher-order React component that takes in another component and then returns some logic. In our case, our higher component will wait to check if the current isLoading state of the component it takes is true or false. If the current isLoading state is true, it will display a message Hold on, fetching data may take some time 🙂. Immediately the isLoading state changes to false it’ll render the component it took in. In our case, it’ll render the List component.

In your *App.js file inside the src folder, let’s paste in the following code:

import React, { useEffect, useState } from 'react';
import './App.css';
import List from './components/List';
import withListLoading from './components/withListLoading';
function App() {
  const ListLoading = withListLoading(List);
  const [AppState, SetAppState] = useState({
    loading: false,
    repos: null,
  });

  useEffect(() => {
    SetAppState({ loading: true });
    const user = `https://api.github.com/users/hacktivist123/repos`;
    fetch(user)
      .then((res) => res.json())
      .then((repos) => {
        SetAppState({ loading: false, repos: repos });
      });
  }, [SetAppState]);
  return (
    <div className='App'>
      <div className='container'>
        <h1>My Repositories</h1>
      </div>
      <div className='repo-container'>
        <ListLoading isLoading={AppState.loading} repos={AppState.repos} />
      </div>
      <footer>
        <div className='footer'>
          Built{' '}
          <span role='img' aria-label='emoji'>
            💚
          </span>{' '}
          with by Shedrack Akintayo
        </div>
      </footer>
    </div>
  );
}
export default App;

Our App.js is a functional component that makes use of React Hooks for handling state and also side effects. If you’re not familiar with React Hooks, read my Getting Started with React Hooks Guide.

Let me explain the code above bit by bit.

import React, { useEffect, useState } from 'react';
import './App.css';
import List from './components/List';
import withListLoading from './components/withListLoading';

Here, we are importing all the external files we need and also the components we created in our components folder. We are also importing the React Hooks we need from React.

const ListLoading = withListLoading(List);
  const [AppState, SetAppState] = useState({
    loading: false,
    repos: null,
  });

Here, we are creating a new component called ListLoading and assigning our withListLoading higher-order component wrapped around our list component. We are then creating our state values loading and repos using the useState() React Hook.

useEffect(() => {
    SetAppState({ loading: true });
    const user = `https://api.github.com/users/hacktivist123/repos`;
    fetch(user)
      .then((res) => res.json())
      .then((repos) => {
        SetAppState({ loading: false, repos: repos });
      });
  }, [SetAppState]);

Here, we are initializing a useEffect() React Hook. In the useEffect() hook, we are setting our initial loading state to true, while this is true, our higher-order component will display a message.
We are then creating a constant variable called user and assigning the API URL we’ll be getting the repositories data from.

We are then making a basic fetch() request like we discussed above and then after the request is done we are setting the app loading state to false and populating the repos state with the data we got from the request.

return (
    <div className='App'>
      <div className='container'>
        <h1>My Repositories</h1>
      </div>
      <div className='repo-container'>
        <ListLoading isLoading={AppState.loading} repos={AppState.repos} />
      </div>
    </div>
  );
}
export default App;

Here we are basically just rendering the Component we assigned our higher-order component to and also filling the isLoading prop and repos prop with their state value.

Now, we should see this in our browser, when the fetch request is still being made, courtesy of our withListLoading higher-order component:


App Loading State
(Large preview)

Now, when the fetch request has completed successfully, we should see the repositories displayed in a list format as below:


Finished App
(Large preview)

Now, let’s style our project a little bit, in your App.css file, copy and paste this code.

@import url('https://fonts.googleapis.com/css2?family=Amiri&display=swap');
:root {
  --basic-color: #23cc71;
}
.App {
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-family: 'Amiri', serif;
  overflow: hidden;
}
.container {
  display: flex;
  flex-direction: row;
}
.container h1 {
  font-size: 60px;
  text-align: center;
  color: var(--basic-color);
}
.repo-container {
  width: 50%;
  height: 700px;
  margin: 50px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  overflow: scroll;
}
@media screen and (max-width: 600px) {
  .repo-container {
    width: 100%;
    margin: 0;
    box-shadow: none;
  }
}
.repo-text {
  font-weight: 600;
}
.repo-description {
  font-weight: 600;
  font-style: bold;
  color: var(--basic-color);
}
.list-head {
  text-align: center;
  font-weight: 800;
  text-transform: uppercase;
}
.footer {
  font-size: 15px;
  font-weight: 600;
}
.list {
  list-style: circle;
}

So in the code above, we are styling our app to look more pleasing to the eyes, we have assigned various class names to each element in our App.js file and thus we are using these class names to style our app.

Once we’ve applied our styling, our app should look like this:


Styled App
(Large preview)

Now our app looks much better. 😊

So that’s how we can use the Fetch API to consume a REST API. In the next section, we’ll be discussing Axios and how we can use it to consume the same API in the same App.

Consuming APIs With Axios

Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. With Axios, we get the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.

Features Of Axios

  • Request and response interception
  • Streamlined error handling
  • Protection against XSRF
  • Support for upload progress
  • Response timeout
  • The ability to cancel requests
  • Support for older browsers
  • Automatic JSON data transformation

Making Requests With Axios

Making HTTP Requests with Axios is quite easy. The code below is basically how to make an HTTP request.

// Make a GET request
axios({
  method: 'get',
  url: 'https://api.github.com/users/hacktivist123',
});

// Make a Post Request
axios({
  method: 'post',
  url: '/login',
  data: {
    firstName: 'shedrack',
    lastName: 'akintayo'
  }
});

The code above shows the basic ways we can make a GET and POST HTTP request with Axios.

Axios also provides a set of shorthand method for performing different HTTP requests. The Methods are as follows:

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

For example, if we want to make a similar request like the example code above but with the shorthand methods we can do it like so:

// Make a GET request with a shorthand method
axios.get(
  url: 'https://api.github.com/users/hacktivist123',
);

// Make a Post Request with a shorthand method
axios.post('/signup', {
    firstName: 'shedrack',
    lastName: 'akintayo'
});

In the code above, we are making the same request as what we did above but this time with the shorthand method. Axios provides flexibility and makes your HTTP requests even more readable.

Making Multiple Requests With Axios

Axios provides developers the ability to make and handle simultaneous HTTP requests using the axios.all() method. This method takes in an array of arguments and it returns a single promise object that resolves only when all arguments passed in the array have resolved.

For example, we can make multiple requests to the GitHub api using the axios.all() method like so:

axios.all([
  axios.get('https://api.github.com/users/hacktivist123'),
  axios.get('https://api.github.com/users/adenekan41')
])
.then(response => {
  console.log('Date created: ', response[0].data.created_at);
  console.log('Date created: ', response[1].data.created_at);
});

The code above makes simultaneous requests to an array of arguments in parallel and returns the response data, in our case, it will log to the console the created_at object from each of the API responses.

Let’s Consume A REST API With Axios Client

In this section, all we’ll be doing is replacing fetch() method with Axios in our existing React Application. All we need to do is to install Axios and then use it in our App.js file for making the HTTP request to the GitHub API.

Now let’s install Axios in our React app by running either of the following:

With NPM:

npm install axios

With Yarn:

yarn add axios

After installation is complete, we have to import axios into our App.js. In our App.js we’ll add the following line to the top of our App.js file:

import axios from 'axios'

After adding the line of code our App.js all we have to do inside our useEffect() is to write the following code:

useEffect(() => {
    SetAppState({ loading: true });
    const user = 'https://api.github.com/users/hacktivist123/repos';
    axios.get(user).then((repos) => {
      const allRepos = repos.data;
      SetAppState({ loading: false, repos: allRepos });
    });
  }, [SetAppState]);

If you’ve noticed, we have replaced the fetch API there with the Axios shorthand method axios.get to make a get request to the API.

axios.get(user).then((repos) => {
      const allRepos = repos.data;
      SetAppState({ loading: false, repos: allRepos });
    });

In this block of code, we are making a GET request then we are returning a promise that contains the repos data and assigning the data to a constant variable called allRepos. We are then setting the current loading state to false and also passing the data from the request to the repos state variable.

If we did everything correctly, we should see our app still render the same way without any change.


App with Axios
(Large preview)

So this is how we can use Axios client to consume a REST API.

Fetch vs Axios

In this section, I will be listing our certain features and then I’ll talk about how well Fetch and Axios support these features.

  1. Basic Syntax
    Both Fetch and Axios have very simple syntaxes for making requests. But Axios has an upper hand because Axios automatically converts a response to JSON, so when using Axios we skip the step of converting the response to JSON, unlike Fetch() where we’d still have to convert the response to JSON. Lastly, Axios shorthand methods allow us to make specific HTTP Requests easier.

  2. Browser Compatibility
    One of the many reasons why developers would prefer Axios over Fetch is because Axios is supported across major browsers and versions unlike Fetch that is only supported in Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+.

  3. Handling Response Timeout
    Setting a timeout for responses is very easy to do in Axios by making use of the timeout option inside the request object. But in Fetch, it is not that easy to do this. Fetch provides a similar feature by using the AbortController() interface but it takes more time to implement and can get confusing.

  4. Intercepting HTTP Requests
    Axios allows developers to intercept HTTP requests. HTTP interceptors are needed when we need to change HTTP requests from our application to the server. Interceptors give us the ability to do that without having to write extra code.

  5. Making Multiple Requests Simultaneously
    Axios allows us to make multiple HTTP requests with the use of the axios.all() method ( I talked about this above). fetch() provides the same feature with the use of the promise.all() method, we can make multiple fetch() requests inside it.

Conclusion

Axios and fetch() are all great ways of consuming APIs but I advise you to use fetch() when building relatively small applications and make use of Axios when building large applications for scalability reasons.
I hope you enjoyed working through this tutorial, you could always read more on Consuming REST APIs with either Fetch or Axios from the references below. If you have any questions, you can leave it in the comments section below and I’ll be happy to answer every single one.

Related Resources

Smashing Editorial
(ks, ra, il)

geeky

via Smashing Magazine https://ift.tt/2ibDzra

June 3, 2020 at 08:00AM

5 Good 9mm Luger Loads for Personal Defense

5 Good 9mm Luger Loads for Personal Defense

https://ift.tt/2U5EooR

The 9mm Luger is everyone’s caliber. The 9mm is a powerful number well-suited to personal defense. The 9mm easily jolts 115 to 124-grain bullets to well over 1100 fps. +P or higher-pressure loadings may reach 1300 fps.

The 9mm is not quite as good as some of its fans think, but it is a better cartridge than most of its detractors would have you believe. It has evolved into perhaps the ideal personal-defense caliber for most users.

The 9mm uses a .355-inch bullet. It cannot do the work of larger calibers, but it certainly outclasses smaller calibers. The 9mm offers all of the recoil most shooters are willing to master.

A number of very experienced shooters choose the 9mm based on excellent control, good practical accuracy and a good reserve of ammunition. A compact 9mm Luger handgun is easily controlled with practice.

A compact .40 S&W handgun or .38 Special small-frame revolver may be a bear to handle. Some of the finest handguns in the world are chambered for the 9mm Luger cartridge.

Many affordable handguns are chambered in 9mm as well. It is important to choose a loading with a good balance of expansion and penetration.

The 9mm needs good expansion to be effective, and all calibers must exhibit adequate penetration for good effect. Non-expanding FMJ loads have proven ineffective. The search was on for five good 9mm defensive loads.

Underwood 9mm Expansion
Underwood’s 124-grain 9mm exhibits good expansion.

When I was given this assignment, I resolved to test each loading not only for reliability and accuracy, but wound potential as well. I tested the loads without regard to advertised velocities or overstated claims.

There is a lot of misinformation regarding wound potential. A lot of folks don’t understand that questioning the veracity of a source is instrumental to understanding and using sources.

Misinformation is staggering. I use water for testing penetration and expansion because it is within 10 percent of gelatin results and much, much easier to work with.

While some will say this isn’t valid compared to gelatin testing, the answer is of course it is. As I stated, water and gelatin testing are very close to one another, usually within 10 percent in penetration and expansion results.

Neither bears a close correlation to flesh and bone. The primary advantage of gelatin is that the wound channel may be observed and even preserved. Water only supplies the end result. On the other hand, my work is easily double-checked.

I tested many loads, but ended up with five that I feel fill the most important niche roles of the 9mm Luger. I think they are excellent loads. For testing, I used a GLOCK 19 9mm handgun.

A handgun with a shorter barrel may be expected to produce less velocity, while a longer-barrel handgun will exhibit greater velocity.

With modern loads, the difference in expansion and penetration may be slight in either barrel length. Reliability is 100 percent in these loads. Accuracy is consistent at 15 yards.

1. Hornady 100-Grain Critical Defense Lite

This loading fills the need for a low-recoil loading for those of small stature, particularly in a compact handgun. Older shooters may also feel a need for lower recoil.

The Hornady load functions well despite lowered bullet weight. Velocity averaged 1140 fps. Penetration was 12 inches of water and expansion averaged 0.59 inches.

This is a credible choice that will serve well for recoil-shy shooters or those using the smallest 9mm handguns.

Hornady Lite 9mm Luger Ammo
The Hornady Lite 9mm 100-grain loads exhibit good expansion.

2. Fiocchi 115-Grain Extrema

This is a good go-anywhere, do-anything load. It works fine in every 9mm I have fired, and offers good accuracy and a clean powder burn. The 115-grain Fiocchi Extrema isn’t loaded too hot or too light, it is just right! Accuracy is excellent. The load averaged 1160 fps. Penetration was 16 inches and expansion a very consistent 0.55 inches.

Fiocchi Extrema
Fiocchi 9mm has proven reliable and accurate in a variety of the author’s handguns.

3. Hornady 115-Grain Critical Defense

The Critical Defense uses a polymer plug to instigate expansion. This works well against a variety of material. The Hornady Critical Defense load is loaded to 1151 fps.

Penetration was ideal at 16 inches, and expansion was excellent at 0.58 inches. This is a good general-purpose defense load.

Hornady Critical Defense 9mm Luger
Note excellent expansion with the Critical Defense bullet.

4. Underwood 124-Grain JHP

I wanted to test at least one +P or maximum-effort loading. The Underwood loading clocks 1302 fps average. Recoil was the greatest of any load tested.

We probably would not use this one in a sub-compact pistol. Recoil would be greater, and greater slide velocity may lead to malfunctions. The load was reliable in the GLOCK 19 and accuracy was good.

Penetration was 18 inches and expansion the greatest of the test at 0.82 inches. That is a lot of wound potential.

Underwood 9mm Luger Ammunition
The Underwood load is high velocity and high energy, but did not exhibit excessive pressure signs.

5. Buffalo Bore 147-Grain JHP

Buffalo Bore also offers fast-stepping 9mm loads in 115 and 124-grain weight. I wanted to test a heavyweight 9mm. The industry standard for the 147-grain JHP seems to be 960 to 1000 fps.

This loading breaks 1047 fps average in the GLOCK 19. This is excellent velocity for a 147-grain bullet, yet recoil isn’t excessive. Reliability is good.

If you have the need for deep penetration against heavily-clothed attackers or feel that light cover is part of the likely scenario, this is a good choice. Penetration was 20 inches and expansion was a reliable 0.56 inches.

Buffalo Bore 9mm Luger Ammo
The Buffalo Bore 147-grain heavyweight is an interesting number.

When you choose personal safety gear, choose what is optimum for your use, not what is popular. Obtain training and build skills, or else resign yourself to defense at arm’s length.

Decide that defending yourself is possible, not impossible. It fails the power of my pen to describe the fear of a fight fought to the finish. Avoid it at all cost, but by the same token, be prepared with the best gear and supplies possible.

What is your favorite 9mm Luger defensive load? Why? Let us know in the comments section below!

Get the Best Deals on Guns, Ammo & Gear sent 3 days a week.


guns

via The Shooter’s Log https://ift.tt/2VbyLGM

June 3, 2020 at 08:43AM

SQL Query Formatting Tools Used At Percona

SQL Query Formatting Tools Used At Percona

https://ift.tt/305WbQy

SQL Query Formatting Tools

SQL Query Formatting Tools Used At PerconaPercona engineers often need to analyze and review complex SQL database queries. Good formatting can make these SQL queries much easier to understand and work with. Without clear formatting, queries can become confusing and hard to debug.

Online query formatting services provide one set of solutions. Examples are Code Beautify, FreeFormatter, and sqlformat.org. However, many users are not comfortable sharing their queries with third-party services, especially if your SQL code contains confidential information.

This article examines alternatives to online tools for SQL query formatting tools that have been successfully used by Percona engineers. These solutions come in different types:

  1. Plug-ins to your code editor or IDEs.
  2. Database Management tools
  3. Terminal Tools

Let’s examine these options.

Code editor or IDE

Most modern code editors have functionality or plug-ins for formatting queries. We checked Visual Studio Code and Sublime because these popular code editors are available for Linux, Mac, and Windows.

Visual Studio Code knows how to format SQL queries, as well as available Extensions for working with databases, for example, “SQLTools – Database tools”. Sublime does not have SQL formatting as standard functionality, but it is easy to add it through Package Control. Several packages are available for Query formatting, and we used Sql​Beautifier.

In this case, you need to copy the request to the code editor and save it to a file. It turned out that most of the Percona team use console tools.

SQL query formatting

Sublime

 

DBA tools

Special database management and monitoring software also have functionality for query formatting.

MySQL Workbench

MySQL Workbench enables a DBA or developer to visually, generate, and manage databases.

The Workbench allows you to format an SQL query into a new SQL tab and click the “Beautify/reformat the SQL script” button.

SQL query formatting

 

Percona Monitoring and Management (PMM)

Percona Monitoring and Management (PMM) is a free, best-of-breed, open-source database monitoring and management solution. PMM has the useful functionality of PMM Query Analytics, which allows you to immediately view requests in formatted form.

percona monitoring and management

 

Terminal tools

The most popular console tool for formatting queries in our team is sqlparse (sqlformat). The developers of the popular online service SQLFormat were very kind and provided the source code of their excellent tool (sqlparse). This simple and useful tool you can use on different platforms.

Docker

If you love Docker and do not want to install the tool on your system. Percona Support Engineer Agustín Gallego has packed the data script into a docker. Here is a simple instruction on how you can use it.

shell> docker pull guriandoro/sqlparse:0.3.1
shell> docker run --rm \
>   --network=none \
>   guriandoro/sqlparse:0.3.1 "SELECT several, columns from a_table as a join another_table as b where a.id = 1;"
SELECT several,
       columns
FROM a_table AS a
JOIN another_table AS b
WHERE a.id = 1;

Cool, right? 🙂

Ubuntu

It’s very simple, install the sqlformat package.

# apt install sqlformat

$ echo "SELECT several, columns from a_table as a join another_table as b where a.id = 1;" | sqlformat - -r -k upper
SELECT several,
       columns
FROM a_table AS a
JOIN another_table AS b
WHERE a.id = 1;

Mac

Install sqlparse using brew or another way to use the command sqlformat.

# brew install sqlparse

# echo "SELECT several, columns from a_table as a join another_table as b where a.id = 1;" |  sqlformat - -r -k upper

SELECT several,
       columns
FROM a_table AS a
JOIN another_table AS b
WHERE a.id = 1;

VIM

And if you love and use VIM, you can also install sqlformat and use it.

vmap <leader>sql :%!sqlformat - -r -k upper<CR>

Sqlformat in VIM

Conclusion

We looked at Sqlparse and Sqlformat tools and their use on Linux, Mac, or Windows. We would like to note that it is very convenient for developers to use the Code Editor or IDE, especially if you become a regular user. Additionally, specialized database software such as MySQL Workbench or PMM can help with query formatting. These are SQL query formatting tools that the Percona team has utilized successfully. Share your experience with these or other tools here in the blog comments.

technology

via MySQL Performance Blog https://ift.tt/1znEN8i

June 3, 2020 at 10:03AM

How Bathtubs Are Made

How Bathtubs Are Made

https://ift.tt/3dmVWVa

How Bathtubs Are Made

Link

South African bathroom fixture company Ceramic Industries takes us inside of their Betta Baths factory for a look at the production process for its bathtubs. Each one starts out as a flat sheet of acrylic, which is then heated and formed using vacuum molds, covered with a fiberglass and resin spray, then baked.

fun

via The Awesomer https://theawesomer.com

June 1, 2020 at 06:01PM

Killhouse Rules.

Killhouse Rules.

https://ift.tt/3dqzEBL

Today I was introduced to a set of rules that are too damned true. We all know them in one way or another or at least have the concepts, but it is good to see them formatted.

Enjoy!

guns

via https://gunfreezone.net

June 1, 2020 at 03:27PM

Perfectly Preserved 1,700-Year-Old Roman Mosaic Floor Found Under Vineyard in Italy

Perfectly Preserved 1,700-Year-Old Roman Mosaic Floor Found Under Vineyard in Italy

https://ift.tt/3eCmzWg

Officials in Negrar di Valpolicella, an Italian village midway between Milan and Venice, have made a startling discovery several meters below a vineyard: A perfectly preserved mosaic floor dating back to the 3rd Century A.D.

In 1922, hints of a Roman villa had been discovered on the site, but no successful excavations had been performed until now. "After countless decades of failed attempts," the municipality writes on their Facebook page, "part of the flooring and foundations of the Roman Villa have been located."

Uncovering the floor completely "will not come soon," the municipality writes, pointing out that "significant resources will be needed." They are also working "to identify the most suitable ways to make this archaeological treasure available and open and visible under our feet."

fun

via Core77 https://ift.tt/1KCdCI5

June 1, 2020 at 10:11AM

Learn How to Make Pretzels from Auntie Anne Herself on Facebook Live

Learn How to Make Pretzels from Auntie Anne Herself on Facebook Live

https://ift.tt/3gDawK3

Whether you got your Auntie Anne’s pretzel fix at the mall or the airport (do they exist anywhere else?), you may be missing those salty, buttery treats now that we’re not spending much time in either place. If this is the case, mark your calendar for Sunday, May 31 at 4 p.m. EST, when THE Auntie Anne herself (the chain’s founder Anne Beiler) will be doing a Facebook Live pretzel-making tutorial. The virtual class will take place at the home of the company’s current president, Heather Neary, but don’t worry: Auntie Anne herself will be there and doing the rolling.

The Auntie Anne’s pretzel recipe

Technically, they want you to order their DIY At-Home Pretzel Kit for the event, which, for $20, comes with most of what you need to make 10 pretzels, either in their original or cinnamon sugar flavor. Butter—a key component of these pretzels—is not included in the kit.

But if you don’t have time to order a kit, or want to save some money, there are several Auntie Anne pretzel copycat recipes out there, including these from Food.com, The Spruce Eats and Once Upon a Chef. The main thing you’ll be learning from Auntie Anne during the tutorial is how to actually form the pretzels, so making your own dough shouldn’t be an issue.

Back by popular demand

The DIY At-Home Pretzel Kits were initially a limited-time special for National Pretzel Day, but ended up being so popular, the company brought them back. “We heard from our guests loud and clear that they are missing our hand-rolled, golden brown pretzel snacks, and quite frankly, we’re missing our guests, too!” Neary said in a statement. “The DIY At-Home Pretzel Kit is not only a great way to satisfy those pretzel cravings, but also creates a fun activity for families to enjoy together while remaining at home.”

Even if you aren’t able to join the Facebook Live demonstration, the video will remain up on the Auntie Anne’s page after that for a quick tutorial whenever you have the time. Now every day can be Pretzel Day!

geeky,Tech,Database

via Lifehacker https://lifehacker.com

May 30, 2020 at 02:08PM

Laravel Packages I never wanna miss again

Laravel Packages I never wanna miss again

https://ift.tt/3eAWcQG

Let’s talk about my favorite topic: Laravel.

In Laravel, I often had the situation that I started building something where a package is already there out in the wild. Since I recognized that also for not so common topics packages are existing but also for niche problems, I check google out first before I start programming things. Best example:

I started building my own tax list for my first Product smartdb.io, where I have Stripe implemented for the billing. While researching for the way of writing the reverse charge on the receipt, I found the package from Marcel Pociot which is solving my problems totally: Vat Calculator

But now my list of Packages which I never wanna lose again:

Livewire

Writing reactive UIs is not so intuitive with vue. Ok, you can get it on your plate fast what you have to do, and packages like Interia.js are adorable, but this is nothing compared to livewire. With vue and laravel, you have to create a REST API first and then fire queries and requests to it. Or use Inertia.js, of course, this is making your life easier. With livewire, you can write everything directly in PHP, no need for big JS things. If you want to create something minimal but reactive like the burger-menu on your page, you can use alpine.js. Alpine.js is minimal and functional like tailwind, just check it out.

Horizon

Horizon is a package for managing your queues. It’s so lovely how easy it is to manage multiple, autoscaling queues with it. You can define what queues should run, how much throughput they can have and also what for timeouts etc. they have. Also, the failed jobs are visible in the UI, that’s so good!

Nova

If you didn’t buy Laravel Nova yet, go for it! It’s such a good admin-tool for all your apps, and you can just pay for it if you go live with your app because the license is not limited at your local machine, only for production apps. I also build whole management apps with nova. For example, our Community “Bitkom”: We made a management System for online orders with it, and just with it and mailgun.

Laravel Gravatar

No need for explanation: Never build an upload for an avatar in your MVP again. Here is the package: thomaswelton/laravel-gravatar

Telescope

Debugging your laravel web-application never was more comfortable than with telescope. It’s so pleasant for development purposes. GitHub

socialite

With Laravel socialite, the Social authentification is so secure and comfortable. You want your users to login with GitHub, Facebook, Google, or others? With socialite, it’s done in under 5 minutes. Get it

Cashier

If you start your own SaaS or Shop with laravel, you’ll have the moment to collect money from your users. With cashier and Stripe, it’s easy. Cashier link

Sushi

Sushi was a sponsor package from Caleb Porzio, which is creating Eloquent Models from an array instead of a database connection. Now it’s free to get here: GitHub. I can describe my use-case of this package at best with “better ENUM”. I use it for long lists of countries, specs, or others that are more or less static, for example, taxes, AWS region mappings to AMIs, and such things.

Laravel Debugbar

You all should know it. I use it for years, and I love it. I’ll not explain it too much, but you can debug your MySQL queries, Gates, views, and all other things you need to debug with it. You see how many Queries are executed, you see which views got rendered and all these goodies. Get it

To be honest, I think this list is not complete. Maybe I’ll add a second list and a third and so on. But for now, these are the packages I don’t want to miss.

programming

via Laravel News Links https://ift.tt/2dvygAJ

May 29, 2020 at 10:06AM

Fisher Space Pen Short Video & Pen Review

Fisher Space Pen Short Video & Pen Review

https://ift.tt/2XeVwu5

Fisher Space Pen — the only pen that writes frozen, under water, and in zero gravity — will be heading back to space with NASA astronauts tomorrow, if all goes according to plan. And that’s what didn’t happen a couple days ago, when the SpaceX launch was delayed.

Here’s a short video about that and about the company’s past & current contributions to the writing industry; the only ballpoint pen that’s been on every manned American space mission since Apollo 7, and a newer all-brass pen with antimicrobial properties (popular lately due to the COVID-19 coronavirus scare).

At the 2020 SHOT Show Range Day this past January, I was the happy recipient of a Tradesman Yellow Cap-O-Matic Space Pen, which I immediately put to work.

Two views of my Tradesman Yellow Space Pen (Photo © Russ Chastain)
Two views of my Tradesman Yellow Space Pen
(Photo © Russ Chastain)

The SHOT Show is a busy time, with dozens of meetings and new products each day. While I keep extensive notes electronically on my phone, there’s no substitute for jotting down a quick handwritten note on a business card or pamphlet to remind you of that moment in time once you get back to your room — and eventually back home. After a whirlwind like the SHOT Show, that stack of business cards you amassed won’t mean much without those scribbles telling to to send email, write up a new product, or contact the company for a review sample.

My usual drill is to pick up free pens here & there on the Show floor, and find out which ones are useful via “trial by fire.” Different pens “like” different surfaces, and not every one will write on every business card or slick printed brochure.

This time, I used my Space Pen almost exclusively for all of that work, with no letdowns. My only “iffy” note was on a very shiny business card, on which most pens won’t write well. The Fisher pen wrote well, but the slick surface didn’t allow the ink to soak in at all, and some of the ink was wiped off with handling before it dried.

In other words: the Fisher Space Pen is the best pen I’ve ever owned.

The two parts of the pen body are threaded together, with the pressurized ink cartridge inside. (Photo © Russ Chastain)
The two parts of the pen body are threaded together, with the pressurized ink cartridge inside.
(Photo © Russ Chastain)

It’s the Cap-O-Matic model, which is a click-to-retract style of pen… but instead of a button at the back end of the pen, you “click” the entire rear cap portion (the part with the clip). The entire mechanism is contained in that cap; the lower part is a painted brass tube containing the ink cartridge.

I do a lot of workshop work, which is tough on my things… things like clothes, phone cases, and pens. After 4 months of tough service, my Tradesman pen is doing just fine, with the only casualty being a little lost paint & exposed brass.

My pen has lost a little paint during 4 months of hard use. (Photo © Russ Chastain)
My pen has lost a little paint during 4 months of hard use.
(Photo © Russ Chastain)

Perhaps best of all, it’s easy to spot and easy to identify; there’s very little chance anyone can pick it up and walk away with your pen, thinking it’s theirs — and if you leave it lying on a workbench or desk, it’s easy to spot among the clutter. The Tradesman bright yellow finish is glossy and covers every exterior surface of the pen, including the inside of the clip.

All Fisher Space Pens are lifetime guaranteed for quality against all manufacturing defects.

Company longevity is always a concern when you read the words “lifetime guarantee,” but when a company has been making good on their Space Pen products for more than helf a century, you can have confidence in their staying power.

After the Show, I ordered two more Cap-O-Matics; one in TrueTimber Strata Camouflage and one in the Firefighter motif.

Cap-O-Matic Space Pens in Firefighter (top), TrueTimber, and Tradesman Yellow (bottom). (Photo © Russ Chastain)
Cap-O-Matic Space Pens in Firefighter (top), TrueTimber, and Tradesman Yellow (bottom).
(Photo © Russ Chastain)

The TrueTimber version is a wrap, which means there’s no camo below the clip. It has a slightly-textured finish, which is nice for gripping the pen. This is the pen I can see hunters carrying to fill out their hunting licenses or tags, often with shaking (and possibly bloody) hands. There’s no doubt it’ll do this job better than most, and should have no problem writing on your tags.

Firefighter version of Fisher Cap-O-Matic Space Pen. (Photo © Russ Chastain)
Firefighter version of Fisher Cap-O-Matic Space Pen.
(Photo © Russ Chastain)

The Firefighter model has an all-over matte black finish enhanced by red lines on the pen clip and the lower body of the pen. It writes like a champ, and for every one sold, Fisher will make a donation to help injured firefighters and their families.

Each Cap-O-Matic Space Pen comes in this attractive "shuttle gift box." (Photo © Russ Chastain)
Each Cap-O-Matic Space Pen comes in this attractive “shuttle gift box.”
(Photo © Russ Chastain)

Engraving is available on some models, including the Red Line Firefighter and Blue Line Police models, with the first line free (up to 30 characters/spaces per line). Up to two more lines can be added at $4 per additional line, for a maximum of 3 30-character lines.

Some people don’t carry a pen. That’s cool; no worries. But I have long been one to carry a pen most of the time. Need to fill out a form or sign a receipt? Use your own pen, not some grubby cheapo that’s been handled by every snot-wiping nose-picker who came before you. Need to endorse a check or fill out a deposit form at the bank? Same thing.

Although I don’t worry about my current Fishers wearing out, I can’t help but drool a little over the original AG7 Astronaut Pen or maybe even the black Titanium Nitride version. Decisions, decisions…

And if you’re going to carry a pen, you might as well make it a good one with a lifetime guarantee. That’d be Fisher Space Pen of Boulder City, Nevada, USA.

The post Fisher Space Pen Short Video & Pen Review appeared first on AllOutdoor.com.

guns

via All Outdoor https://ift.tt/2yaNKUu

May 29, 2020 at 01:40PM