1678207748
При разработке легковесных приложений мы можем захотеть сохранить некоторые данные. Если база данных избыточна - есть отличная альтернатива: localStorage!
Хотя он не заменяет базу данных для целей базы данных, он служит простой файловой системой хранения, которую вы можете использовать для хранения легкодоступных точек данных.
В этой статье мы узнаем, как localStorageлегко хранить данные в нашем браузере. Эти данные сохраняются в виде пар ключ-значение, которые пользователь может легко получить.
Сохранить данные в localStorageReact очень просто:
const [data, setData] = useState([]);
useEffect(() => {
localStorage.setItem('dataKey', JSON.stringify(data));
}, [data]);
Если вы никуда не торопитесь и хотите узнать больше о том, как это работает, продолжайте читать!
localStorage— это объект веб-хранилища, который позволяет разработчикам хранить пары «ключ-значение» в веб-браузере и гарантирует, что эти данные сохраняются при всех обновлениях страницы, даже когда пользователь закрывает или перезапускает браузер, и не имеет срока действия. Сохраненные пары ключ-значение могут включать в себя данные любого типа — массивы, объекты, строки, числа и многие другие.
Однако это не может заменить роль баз данных на ваших веб-сайтах и веб-приложениях, поскольку данные теряются, когда пользователь очищает кеш браузера и локальное хранилище — в конечном счете, это локальное хранилище , и его следует использовать как таковое. Тем не менее, есть ситуации, в которых пользователь может использовать localStorage, например, реализация функции темного режима , сохранение входного значения пользовательской формы и многие другие.
localStorageимеет встроенные методы, которые позволяют нам получить доступ к объекту хранилища браузера. Одним из примеров является setItem()метод, который позволяет нам добавить ключ и значение к localStorage, что позволяет нам хранить данные. Другие методы используются для извлечения данных - getItem(), удаления данных - removeItem(), очистки всех localStorageэкземпляров - clear()и так далее.
Метод setItem()позволяет нам сохранять значения любого типа данных, localStorageприсваивая значения ключам, в результате чего получается пара ключ-значение . Этот ключ будет использоваться для получения соответствующего значения всякий раз, когда мы хотим получить его из localStorage.
Примечание. Чтобы сохранить данные в localStorage, мы должны сначала преобразовать их в строку JSON с помощью JSON.stringify()функции. И когда мы захотим получить его, мы проанализируем данные с помощью JSON.parse(), преобразуя строку JSON обратно в объект JSON .
При работе с данными в React мы часто используем хуки , которые помогают нам хранить/удерживать их. Хуки также могут помочь нам найти, куда загружать эти данные. Это также относится и к localStorageпотому, что мы будем использовать хуки useState()и useEffect(). Эти хуки имеют решающее значение, потому что useState()хук используется для хранения и установки данных, тогда как useEffect()хук срабатывает по умолчанию после первого рендеринга и всякий раз, когда изменяется состояние, передаваемое вторым параметром.
После объяснения основы, вот код, который мы будем использовать для хранения данных localStorage:
const [data, setData] = useState([]);
useEffect(() => {
localStorage.setItem('dataKey', JSON.stringify(data));
}, [data]);
Сначала мы создали состояние для хранения данных, которые мы хотим сохранить в нашем localStorage, а затем мы создали useEffect()ловушку, передав состояние в качестве второго параметра. Таким образом, всякий раз, когда состояние изменяется, данные в файле localStorageобновляются до текущего значения.
Мы обработали основную функциональность, которая помогает нам в хранении данных, в useEffect()хуке:
localStorage.setItem('dataKey', JSON.stringify(data));
В этой статье мы узнали, как использовать хуки React для хранения данных в React с использованием localStorage. Как указывалось ранее, это никогда не заменит роль базы данных, а скорее поможет нам хранить некоторые пользовательские данные, которые могут улучшить пользовательский интерфейс, но не предназначены для сохранения независимо от браузера.
Оригинальный источник статьи по адресу: https://stackabuse.com/
1678200120
When developing lightweight applications - we may want to store some data. If a database is overkill - there's a great alternative: localStorage
!
While it doesn't replace a database for, well, database purposes, it does serve as a simple file-based storage system that you can leverage to store easily-accessible data points.
In this article, we will learn how to use
localStorage
to easily store data in our browser. This data is saved as key-value pairs that the user can easily retrieve.
Saving data to localStorage
in React is super easy:
const [data, setData] = useState([]);
useEffect(() => {
localStorage.setItem('dataKey', JSON.stringify(data));
}, [data]);
If you're not in a hurry and want to learn more about how this works, keep reading!
localStorage
is a web storage object that enables developers to store key-value pairs in a web browser and ensures that this data survives all page refreshes, even when a user closes or restarts a browser - and it has no expiration date. Stored key-value pairs can include any type of data - arrays, objects, strings, numbers, and many others.
However, this cannot replace the role of databases in your websites and web apps because data is lost when a user clears the browser's cache and local storage - ultimately, it's local storage and should be used as such. Nonetheless, there are situations in which a user can use localStorage
, such as implementing the dark mode feature, persisting a user's form input value, and many others.
localStorage
has built-in methods that allow us to access the browser's storage object. One example is the setItem()
method, which allows us to add a key and a value to localStorage
, therefore enabling us to store data. Other methods are used to retrieve data - getItem()
, delete data - removeItem()
, clear all localStorage
instances - clear()
, and so on.
The setItem()
method allows us to save values of any data type to localStorage
by assigning values to keys, resulting in a key-value pair. This key would be used to retrieve the corresponding value whenever we want to retrieve it from localStorage
.
Note: In order to store data in localStorage
, we must first convert it to JSON string using the JSON.stringify()
function. And when we want to retrieve it, we will parse the data using JSON.parse()
, converting the JSON string back to a JSON object.
When working with data in React, we frequently use hooks to help us store/hold it. Hooks can also help us find where to upload that data. This also applies to localStorage
because we will use the useState()
and useEffect()
hooks. These hooks are critical because the useState()
hook is used to hold and set data, whereas the useEffect()
hook is triggered by default after the first render and whenever the state passed as the second parameter changes.
After explaining the foundation, here is the code we would use to store data in localStorage
:
const [data, setData] = useState([]);
useEffect(() => {
localStorage.setItem('dataKey', JSON.stringify(data));
}, [data]);
We've first created a state to hold the data we want to store in our localStorage
, and then we've created a useEffect()
hook, passing the state as the second parameter. That way, whenever the state changes, the data in the localStorage
is updated to the current value.
We handled the core functionality, which is used to assist us in data storage, within the useEffect()
hook:
localStorage.setItem('dataKey', JSON.stringify(data));
In this article, we learned how to use React hooks to store data in React using localStorage
. As previously stated, this will never replace the role of a database, but rather will assist us in storing some user-related data that can improve the UI but isn't meant to be persisted independenly of the browser.
Original article source at: https://stackabuse.com/
1678196760
在开发轻量级应用程序时——我们可能希望存储一些数据。如果一个数据库是矫枉过正 - 有一个很好的选择:localStorage!
虽然它不会取代数据库,嗯,数据库目的,但它确实充当了一个简单的基于文件的存储系统,您可以利用它来存储易于访问的数据点。
在本文中,我们将学习如何使用localStorage浏览器轻松存储数据。此数据保存为用户可以轻松检索的键值对。
在 React中保存数据localStorage非常简单:
const [data, setData] = useState([]);
useEffect(() => {
localStorage.setItem('dataKey', JSON.stringify(data));
}, [data]);
如果您不着急并想了解更多有关其工作原理的信息,请继续阅读!
localStorage是一个 Web 存储对象,它使开发人员能够在 Web 浏览器中存储键值对,并确保此数据在所有页面刷新后仍然存在,即使在用户关闭或重新启动浏览器时也是如此 - 而且它没有过期日期。存储的键值对可以包括任何类型的数据——数组、对象、字符串、数字等等。
但是,这不能取代数据库在您的网站和 Web 应用程序中的作用,因为当用户清除浏览器的缓存和本地存储时,数据会丢失 - 最终,它是本地存储,应该这样使用。尽管如此,在某些情况下用户还是可以使用 的localStorage,例如实现深色模式功能、保留用户的表单输入值等等。
localStorage具有允许我们访问浏览器存储对象的内置方法。一个例子是setItem()方法,它允许我们向 中添加一个键和一个值localStorage,从而使我们能够存储数据。其他方法用于检索数据 - getItem()、删除数据 - removeItem()、清除所有localStorage实例 -clear()等等。
该setItem()方法允许我们通过将值分配给键来保存任何数据类型的值localStorage,从而产生键值对。每当我们想从中检索它时,该键将用于检索相应的值localStorage。
注意:为了将数据存储在 中localStorage,我们必须先使用函数将其转换为JSON 字符串JSON.stringify()。当我们想要检索它时,我们将使用 解析数据JSON.parse(),将 JSON 字符串转换回JSON 对象。
在 React 中处理数据时,我们经常使用钩子来帮助我们存储/持有它。Hooks 还可以帮助我们找到上传数据的位置。这也适用于localStorage因为我们将使用useState()和useEffect()钩子。这些钩子很关键,因为useState()钩子用于保存和设置数据,而useEffect()钩子默认情况下在第一次渲染后以及当第二个参数更改时状态传递时触发。
在解释了基础之后,这是我们用来存储数据的代码localStorage:
const [data, setData] = useState([]);
useEffect(() => {
localStorage.setItem('dataKey', JSON.stringify(data));
}, [data]);
我们首先创建了一个状态来保存我们想要存储在我们的 中的数据localStorage,然后我们创建了一个useEffect()钩子,将状态作为第二个参数传递。这样,每当状态发生变化时, 中的数据localStorage就会更新为当前值。
我们在钩子中处理了核心功能,用于帮助我们进行数据存储useEffect():
localStorage.setItem('dataKey', JSON.stringify(data));
在本文中,我们学习了如何使用 React hooks 在 React 中使用localStorage. 如前所述,这永远不会取代数据库的作用,而是帮助我们存储一些与用户相关的数据,这些数据可以改进 UI,但并不意味着独立于浏览器而持久化。
原始文章来源:https: //stackabuse.com/
1676410020
In this tutorial, we learn about how to Build compelling app preview videos for the App Store. Creating a compelling app preview video for the App Store is a crucial aspect of promoting your app and driving downloads.
A well-made app preview video can provide potential users with a comprehensive understanding of the features and benefits of your app, and can also showcase its unique selling points.
To create a compelling app preview video, you must consider various elements such as storytelling, graphics, sound, and video length.
Additionally, you need to make sure that your video showcases the app’s key features, and provides a clear message about the value your app provides to its users.
App Preview Videos are short promotional videos that showcase the features and functionality of a mobile app. These videos are designed to give potential users a quick overview of the app and to demonstrate what the app can do.
App preview videos are typically 30-60 seconds long and are displayed on the app store listing of the app, usually in the app’s description section. They can be used to give potential users a visual representation of how the app works, highlight its unique features and explain its benefits.
These videos are an effective marketing tool for app developers as they provide a visual representation of the app, making it easier for potential users to understand what the app does and how it works.
They also give developers an opportunity to showcase the app’s design and overall user experience. When creating app preview videos, it is important to keep them short, concise, and visually appealing. The videos should clearly highlight the key features of the app and demonstrate its value proposition.
Overall, App Preview Videos are an essential component of any app marketing strategy, as they help potential users make informed decisions about downloading and using an app.
Uploading videos to the App Store or Google Play Store is a simple process. Here are the steps:
App Store (iOS): To upload an app preview video to the App Store, you need to sign in to iTunes Connect, select your app, and click on the “App Preview” section. From there, you can upload the video file and set the order in which it will be displayed in the App Store.
Google Play Store (Android): To upload an app preview video to the Google Play Store, you need to sign in to the Google Play Console, select your app, and click on the “Store Listing” section. From there, you can upload the video file and set the order in which it will be displayed in the Google Play Store.
[Note: It is essential to follow the guidelines set by each platform for app preview videos, such as video length, file format, and resolution. Additionally, make sure that the video is optimized for mobile devices and is of high quality.]
In conclusion, app preview videos can significantly boost the number of downloads for your app.
By showcasing the app’s features and benefits in an engaging and compelling way, app preview videos can help potential users make informed decisions about downloading and using an app.
Additionally, they can help increase app visibility and drive user engagement, making them an essential component of any app marketing strategy.
With the right planning, storytelling, and execution, you can create an effective and compelling app preview video that will help you reach your target audience and achieve your marketing goals.
So, start planning and creating your app preview video today, and see the impact it has on your app’s succes
Original article sourced at: https://www.techwebspace.com
1675517421
Speed is money for an ecommerce site. The faster your site loads, the better the shopping experience. A better user experience translates to improved SEO, increased ROI, and happier customers. This ultimately leads to greater revenue and profits.
Shoppers today expect high-resolution images and videos, live chat, user reviews, real-time inventory, personalization, and a host of other dynamic tools.
Online shoppers have a short attention span. Hence, all the features they expect to have a faster and smoother buying experience are the same ones that slow down your ecommerce site if you don’t execute them properly.
WooCommerce is the most popular ecommerce platform in the world and is free to use and tweak as per your requirements. Kinsta Can with POPs highlighted” width=”800″ height=”500″ /> Kinsta Can with PoPs
WooCommerce leads the ecommerce pack (Image source: BuiltWith)\
WooCommerce has been downloaded over 88 million times to date. As of now, it’s in use on over 5 million websites.
WooCommerce plugin downloads and usage stats
Unlike other popular shopping platforms, you don’t have to pay a percentage of your revenue to WooCommerce if you use it. There are some overhead costs associated with running a WooCommerce-powered store though.
But there’s a catch! Since WooCommerce is free with limited support, you’re responsible for maintaining it in tip-top shape. The good news is that it’s easy to take care of it if you know what you’re doing!
Want to learn how to speed up your WooCommerce site reliably?
This guide is for you!
And remember, your ultimate goal is to increase your store’s revenue. So be sure to download our free ebook, 10 Ways to Boost Your WooCommerce Product Page Conversions.
First impressions matter and speed is the first thing a user will notice about your site. In a study by Google, 53% of mobile users left a site if it took longer than 3 seconds to load.
3 seconds is best practice (Image source: Think with Google)
“2 seconds is the threshold for ecommerce website acceptability. At Google, we aim for under a half second.”
– Maile Ohye, Tech Lead, Google
In another global study, 80% of users said that they find a slow loading website more frustrating than a temporarily down one. The same study also found that 73% of users would switch to a competitor site if a website is too slow to load.
Even a 100-millisecond delay in page response time can hurt the user experience and online revenue. As per Akamai, a 100-millisecond delay impacts conversion rates by 7%, while a 2-second delay increases bounce rates by a whopping 103%.
If your site is generating $1000 in revenue daily, 100-millisecond delays in page load times might cost you $25,550 in lost sales annually.
The bigger the business, the greater the fall. For instance, Amazon projected a revenue loss of $1.6 billion annually if its page load time slowed by just one second.
Page load time is vital (Image source: Think with Google)
The above data suggests that if your website takes 6 seconds or more to load, you’re losing twice as many users as you would if your site loaded in less than 3 seconds.
Apart from user experience, your site’s speed also impacts SEO. Website speed and performance play a major factor in Google’s site ranking algorithm.
Google has shifted to mobile-first indexing for over 50% of the pages shown in their search results. Despite this, data from HTTPArchive.org suggests that the average load time for mobile sites running WordPress has worsened in the last year.
How top WordPress sites perform (Image source: HTTPArchive.org)
During peak traffic times such as Cyber Monday and Black Friday, it’s even more crucial to keep your site running as fast as possible. With the outburst of offers going around, ensuring that shoppers don’t abandon your site is critical to close sales.
Given these statistics, speeding up your WooCommerce Store can give you a significant edge over your competition.
What you cannot measure, you cannot improve!
Now that you’ve understood why speed is important for your WooCommerce store, it’s time to learn how to measure it. It’s essential to know how to gauge the improvements when you’re trying to speed up your WordPress site.
A website speed test is a perfect tool to test the responsiveness of your WooCommerce store. But if you don’t do this properly, your site may seem slower to you after making a change, when it’s faster.
A website speed test report (Image source: Pingdom)
We recommend you get started with one of these website speed testing tools: WebPagetest, Pingdom, Google PageSpeed Insights or GTMetrix.
You can also use the free WordPress plugin Query Monitor to pinpoint the themes, plugins, and functions that are performing poorly. It helps you debug inefficient database queries, bloated functions, PHP errors, HTTP API calls, etc.
No speed testing tool is perfect, but pick one and stick with it. You can work your way towards other options later.
Gary Illyes, Webmaster Trends Analyst, Google
There’s a difference between actual performance and perceived performance. The user experience matters more than the technical wizardry powering the site.
Therefore, use the techniques mentioned below to enhance your site’s overall user experience, rather than just getting a high-speed score.
A speed test report will give you an actionable plan to optimize your slow WooCommerce site. Excited? Let’s get started!
Let’s start with the basics by optimizing WooCommerce plugin settings.
First, change your login page URL. By default, every WordPress site’s login URL is domain.com/wp-admin/. While this is easy to remember, it poses a major problem: everyone knows about it too, including bots and hackers.
Changing your login URL to something unique will protect you against brute force attacks from nefarious actors. It’ll also help you combat rate-limiting HTTP errors like 429 Too Many Requests.
Free plugins such as WPS Hide Login and Rename wp-login.php make this task super easy.
If your ecommerce site hosts a blog too, you can limit the number of posts on your blog feed. WordPress sets this limit to 10 posts by default, but you can set a lower limit.
While this may seem trivial, performance savings add up if you run a high-traffic blog (here’s how to drive traffic to your website). You can find this option under WordPress Dashboard → Settings → Reading.
Limit the number of posts in your blog feed
Next, disable pingbacks on your website. They usually generate worthless spam. The fewer queries your site generates, the better.
Optimize the discussion settings
If you have a lot of user comments on your posts or pages, then WordPress also gives you an option to break them into smaller chunks. The same setting holds true for breaking down reviews on your product pages.
Keep this number between 10 and 20 to optimize your product page load time.
You can disable product reviews under WooCommerce → Settings if you don’t like having them on your store. This will help speed up your site as it eliminates loading a few scripts and widgets.
Disable product reviews if you don’t need them
Finally, remove any unnecessary/outdated themes and plugins from your site. The fewer themes and plugins you’ve installed, the easier it is to maintain them and troubleshoot performance issues.
Using the right WooCommerce theme matters. There are hundreds of thousands of themes out there, so deciding on the one that’s perfect for you is always a challenge.
Featured themes on WordPress.org
A beautiful theme with amazing built-in features can sound great on paper, but it may flop in actual usage. For an ecommerce site, you need to ensure that it’s fully compatible with WooCommerce.
Filter down your ecommerce theme search
WP Rocket tested a bunch of popular WooCommerce themes for speed and came up with the following results.
Opt for a fast WooCommerce theme (Image source: WP Rocket)
Astra, OceanWP, and GeneratePress are also Kinsta’s favorites as suggested in the WordPress speed up article. They’re ultra-fast, lightweight WordPress themes. You will find 10+ additional very fast themes in this tutorial.
When paired with a page builder such as Elementor or Beaver Builder, they can help you create almost any site.
Storefront is WooCommerce’s official theme
Storefront is a free theme offered by WooCommerce, whereas Shoptimizer, Divi, and WoondrShop are premium themes. Since these themes are built for running an ecommerce site, there’s no need to install third-party plugins to get all the features you want.
If you’re short on budget, it’s perfectly fine to start with a free theme and upgrade later to a premium solution.
We recommend leaving page builders behind to reduce bloat. Instead, go for a theme that supports WordPress’ block editor Gutenberg.
To decide on a theme, we suggest you list down all the features you need in your online store. Then go for a theme that covers most of your feature requirements. This will help you cut down dependency on bloated multi-purpose themes and third-party plugins.
This brings us to the next suggestion.
WordPress has 54,000+ free plugins in its repository. There are even more premium plugins out in the wild. Thus, it’s easy to get carried away and install dozens of them.
There’s a plugin for almost anything
Many popular plugins, especially performance and security related ones, don’t work well in certain hosting environments.
If you find it hard to decide which plugin to install, go through Kinsta’s hand-picked list of the best WordPress plugins for various uses. From SEO to image compression, you’re bound to find some gems in there.
WooCommerce functionality can be expanded with its wide range of free and premium WooCommerce extensions. They work the same way as plugins.
WooCommerce extensions enhance your store’s functionality
Contrary to popular perception, the number of plugins you install doesn’t always cause performance issues. But this holds true only as long as the plugins are built with the best coding practices.
Vetting every plugin you install for quality becomes a hassle when there are too many of them. And that’s considering you have the skills and expertise to vet them thoroughly.
A few plugins even create conflicts with other plugins. When you have dozens of plugins on your site, the probability of a plugin conflict occurring shoots up exponentially.
Hence, be smart about the type of plugins and WooCommerce extensions you install.
WordPress allocates 32 MB memory for PHP by default. If it runs into any crunches, it’ll automatically try to increase this limit to 40 MB (for a single site) or 64 MB (for a multisite).
In most cases, this memory limit won’t be enough for a WooCommerce site. You may even receive an error message on your dashboard such as:
“Allowed memory size of xxxxxx bytes exhausted”
It’s recommended to increase this limit to 256 MB. Always do a backup of any file before you edit it. In case something goes wrong, you can replace the edited file with the original one.
Images make up the bulk of any website’s page size, more so for an ecommerce site. WooCommerce sites are loaded with product images and banners.
If you don’t optimize images for size and delivery, they can bring your website to a crawl 🐌
HTTPArchive tracks the size and quantity of many popular web pages. Here’s a visual representation of their state of WordPress sites in 2021:
Images are a heavy resource
While videos are a heavier resource than images, they’re loaded on demand in most cases. Hence, they don’t affect the perceived page load speed as much as images do.
According to HTTP Archive’s State of the Images report, you can save 545 KB per page by lazy-loading hidden and offscreen images.
By setting your JPEG compression levels to 85 or lower, you can further save 40.3 KB per page. This metric comes straight from Lighthouse, Google’s speed test tool for mobile websites.
Follow these 5 rules to optimize images for your WooCommerce store (and the web in general):
WooCommerce 3.3 introduced image size improvements such as on-the-fly thumbnail resizing, blurry image fix, and background thumbnail resizing. All these features make using a plugin such as Regenerate Thumbnails for WooCommerce-related images redundant.
Customizing WooCommerce’s Product Images (Image source: WooCommerce)
If you’re starting with a fresh install, you can compress your images before you upload them to your site. Here are some of the top online image compression recommendations:
Compress images with minimal loss in quality (Image source: Compressor.io)
Do you have many images already up on your site? Then you can use a WordPress plugin to automate image optimization. Here are the ones that consistently performed the best in our experience:
Most of these plugins also enable lazy-loading for images. The WordPress core team is planning to add lazy-loading images as an inbuilt feature. This will utilize the new loading HTML attribute for <img> tags.
One last thing on image optimization, though. Avoid using image compression plugins as much as possible, particularly the ones that use your server’s resources to compress the images.
Instead, use a service that offloads the image compression task to an external server. Or better yet, resize and compress your images before uploading them to your website.
For an in-depth tutorial, Kinsta’s article on image optimization for web and performance is a great resource to get started.
A Content Delivery Network (CDN) is a group of servers located strategically around the world. These server locations are known as Points of Presence (PoPs).
A CDN’s primary function is to cache and deliver static resources such as images, JavaScript, CSS, etc. More powerful CDNs can also host and deliver dynamic content such as audio and video.
Even if your site runs on the fastest server on the planet, it’s still limited by its geographical location. A WordPress CDN will decrease the distance between the individual user and the site’s resources, reducing both network latency and time to first byte (TTFB).
Kinsta CDN with PoPs highlighted
Depending on where the request is coming from, it automatically assigns the nearest CDN PoP to deliver the cached resources. The result is a faster website and a better user experience.
If you are a Kinsta customer, at no extra cost to you, we provide only locations offering Google’s best C2 machines. You can select the region that works best for you and your users and choose from 26 data centers on five continents.
Your WooCommerce store can run a maximum speed with our 275+ CDN POPs.
For instance, if your WooCommerce store is hosted at a server in the USA, and a user from India tries to open your website, the CDN will serve the website’s assets from the nearest PoP. Here it would be from Bengaluru (India).
CDNs are perfect for delivering static content (Image source: Seobility)
As a general rule, the higher the number of PoPs and the wider their global spread, the faster your website will be for your users.
Kinsta put its CDN to the test and the results speak for themselves. For users in geographical locations that are considerably farther from the hosting server, using a CDN decreased site load time by over 50%.
Apart from caching, many CDNs include other performance-enhancing features such as superior on-the-fly image compression, HTTP/2 support, hotlink protection, and additional security.
For a faster WooCommerce store, we recommend that you get a fast CDN. Some popular CDNs you can check out are:
Most WordPress themes and plugins load scripts and stylesheets on all your site’s pages. They load these assets even when they’re not used on the page.
As an example, Contact Form 7 loads its scripts and stylesheets on every page. Its forms may only be used on the contact page, but the assets load on all the pages. Quite unnecessary!
Stripping these unused assets from pages will help you reduce bloat and speed up page load times. WooCommerce and its extensions (e.g., Smart Coupons and Follow-Ups) are susceptible to this issue.
For instance, it’s unnecessary to load scripts related to payment gateways on your store’s homepage or shop page. You can restrict such scripts to load only on the checkout and order confirmation pages. Likewise, eliminate scripts and styles for sliders and carousels from your checkout page.
If you want to know which assets to eliminate, look at the waterfall chart in your website speed test report. It’ll give you an idea about the unnecessary assets that are being loaded.
GTMetrix’s Waterfall Chart
The Network tab under Chrome browser’s DevTools is also a good place to get started. It’ll give you a comprehensive view of how and what a web page loads.
Use the Network tab in Google Chrome DevTools
Strip the scripts and styles that aren’t necessary for the functioning of the page. Start by optimizing your homepage and landing pages, since these are the first points of entry for most of your users.
You can use wp_dequeue_script and wp_dequeue_style functions to remove scripts and styles you don’t need. An easy way to achieve the same is through a plugin called Asset CleanUp: Page Speed Booster.
Clean up your WordPress assets
Asset CleanUp scans for all scripts and stylesheets that will be loaded onto a page. You can disable the ones that aren’t used on the page. Test the page for proper design and functionality once you finish making the changes.
Unloading Stripe payment gateway script with Asset Cleanup
The pro version of the plugin allows you to set async or defer attributes to the assets. Applying this setting removes JavaScript from the page’s critical rendering path. It should help with improving your site’s perceived page load time.
Another advantage of eliminating unnecessary CSS and JS assets is that your website will make fewer HTTP requests.
For a free alternative, you can use the combination of Autoptimize and Async JavaScript plugins to get the same results. If you go with Autoptimize plugin here is our full step by step guide on the best settings.
If we were writing this article a few years ago, we would’ve titled this section “Reduce the Number of HTTP Requests.” Thanks to substantial improvements in how browsers communicate with websites (and vice-versa), the need for this optimization is now obsolete.
HTTP 1.1 was the first major update to the HTTP protocol, and it was finalized way back in 1997. That’s before social media, streaming services, smartphone apps, and even WordPress. The web has grown exponentially since then.
HTTP/2 improved upon the HTTP 1.1 protocol and made its entry in 2015 to keep up with the growing demands of the internet. It brought with it amazing improvements in speed, efficiency, and security.
HTTP 1.1 vs HTTP/2 (Image source: Cloudflare)
The performance increase with HTTP/2 is due to multiple reasons:
All that jazz amounts to one crucial advantage: making websites load faster, even when they host various types of resources.
Typically, WooCommerce stores serve a lot of resource-heavy assets such as images, stylesheets, and scripts. Sites like these will benefit greatly by switching to HTTP/2.
You can use the HTTP/2 test tool by KeyCDN to check whether your site is configured to work with HTTP/2. As of now, every major browser supports HTTP/2. There’s no reason you shouldn’t be taking advantage of its massive performance benefits.
If your hosting provider doesn’t support HTTP/2 yet, start looking for a new one. Kinsta supports HTTP/2 and TLS 1.3 on all of its servers and CDN.
Furthermore, HTTP/3 is just around the corner and is set to make websites load even faster.
Caching is temporarily storing resources (cache) from one request so that subsequent requests can be executed quickly. The cache can be stored either on the server or on the user’s device.
It’s one of the easiest ways to speed up your WooCommerce store. And it’s also the most important one.
How web caching works
If everything works smoothly, all the above steps should take a few seconds at max to execute.
But that’s just one request from a single user. What if there are multiple requests from thousands of users at the same time? That will put an enormous load on the server, eventually leading to a slower website.
This is where caching comes to the rescue. It reduces the amount of work required to generate a pageview, thus reducing WordPress’ dependency on PHP and a database. Caching makes WordPress perform almost as fast as static websites, if not the same.
There are 2 major types of web caching, each with their own subsets:
Server-Side Caching
Client-Side Caching
Caching not only makes the website load faster, but it also reduces load on the server. Kinsta’s in-depth article on WordPress cache is a great resource for a detailed explanation.
If your WooCommerce store is hosted with Kinsta, caching is taken care of at the server-level. Hence, you need not use a caching plugin.
Kinsta configures cache rules to work seamlessly with WooCommerce. This ensures that your users have a smooth checkout experience with no hiccups.
WordPress load times after migrating to Kinsta’s new servers
If your hosting provider doesn’t handle caching at the server-level, then you need to depend on third-party caching plugins to do the work for you. While they aren’t an ideal solution, something is always better than nothing.
Here are our top WordPress caching plugin recommendations:
For more options, check out Kinsta’s post on WordPress caching plugins.
A database is an organized collection of all your website’s data. In a WooCommerce store, it includes:
Every time a user visits your store, they’re requesting your site content, which is mostly static and doesn’t change much. But when they’re placing an order, they’re making a dynamic request.
If you don’t optimize your store’s database, it may take too long to process these requests. Ultimately, a slow server response time leads to a slow website. Hence, you must clean up and optimize the database by removing unnecessary junk.
Here are 6 ways to speed up and fine-tune your WooCommerce database.
If your WooCommerce store has been up for quite a while, its pages, posts, and products will be filled with old revisions. It’s time to clean these up.
The easiest way to do it is through plugins such as WP-Sweep or WP Rocket.
Deleting old revisions with WP Rocket
If you’re handy with WP-CLI, then you can also connect to your server via SSH and run a few simple commands to do the same. Here’s how you can do it.
You can avoid having numerous old revisions by limiting the number of revisions for posts and pages. If you’re prone to updating your site content often, this will help you keep revisions from going out of hand.
An easy way to set the limit is by adding the below code snippet below to your wp-config.php file. Make sure to add it before the line where ABSPATH is defined.
define('WP_POST_REVISIONS', 15);
I’ve set the limit as 15 in the code above. You can change it to any number of revisions you want, but try to keep it below 15.
Alternatively, you can use a free plugin such as WP Revisions Control to do the same.
Set the number of revisions with WP Revisions Control
You can disable revisions from your site altogether. All you need to do is add the following code to your wp-config.php file. As before, ensure that you add this snippet above the line where ABSPATH is defined.
define('WP_POST_REVISIONS', false);
Or you can use a free plugin such as Disable Post Revision to do the same with a single click.
Before disabling revisions, we suggest you delete all the old revisions that are still present. This way, your site’s database will be completely free of revisions going forward.
Transients are cached data stored with a custom name and an expiration period. They’re usually stored in the WordPress database under the wp_options table.
Transients are similar to Options, except they have an added property of expiration time. They are useful to store temporary data such as responses from a remote API or large queries.
The WordPress Transients API defines how to handle transients and delete expired transients automatically. However, things don’t always go as planned.
Sometimes, a corrupt transient cache can create almost a million junk entries with no end in sight. Customer sessions can rack up over time, creating thousands of unnecessary rows in your database tables. In such cases, a bloated database can bring your site to its knees.
The free Delete Expired Transients plugin is an easy way to get rid of all expired transients.
Deleted all your expired transients easily
Your WooCommerce database stores everything that’s needed to run your ecommerce store. As data gets added, removed, and moved around the tables in your database, it becomes inefficient and ends up storing many things that aren’t important to run your store.
You need to clear out this unnecessary data by cleaning up your database tables. The wp_options table, in particular, is prone to getting bloated and hurting database performance.
The wp_options table in WordPress database
Database housekeeping is key to keeping your WordPress site running as swiftly as possible.
Optimizing your database manually is a time-consuming process. You can use the free WP-Optimize plugin to check which database tables have unnecessary data and delete those wasted spaces. It can also retrieve storage space lost to data fragmentation.
You can schedule WP-Optimize to clean up and optimize your database regularly.
WooCommerce themes and plugins come with a lot of cool features that seem great from the outset but end up crumbling the database.
One such example is using “Popular Products” and “Related Products” plugins. These features can cause enormous sitewide queries, especially if you have many products. If you need these features, try to insert them manually into your pages. Plugins such as Advanced Custom Fields can help here immensely.
Kinsta inserts its ‘Related Content’ posts manually
Another example is image optimization plugins that compress images on the same server where the site is hosted, rather than do it externally. This ends up using a lot of your server’s resources.
Social Warfare plugin can tax the server resources
Also, stay away from plugins that add counters to your site. For example, adding the number of views/posts/comments beside a username. A lengthy discussion with multiple users involved will stress your database to crunch these numbers.
This advice holds true for using social counters too. Minimize the use of auto-generated counters to maximize database performance.
Need a blazing-fast, reliable, and fully secure hosting for your ecommerce website? Kinsta provides all of this and 24/7 world-class support from WooCommerce experts. Check out our plans
Like housekeeping, fine-tuning your WordPress database is an ongoing process.
Keeping this in mind, Kinsta has implemented an automated system to combat database performance issues. Based on your site’s needs, the automated system scans and fine-tunes your MySQL database once per week to ensure peak database performance. If the system detects something out of the ordinary that can’t be fixed automatically, it notifies the sysadmin team to take immediate action.
If your site is hosted somewhere else, here are a few database optimization plugins to make your job easier:
Reminder: Always take a backup before editing your database or WordPress core files.
As of January 2020, there are over 4 billion internet users in the world. There are almost as many mobile internet users. It’s expected to grow to 5+ billion by 2024.
There are billions of us (Image source: Statista)
Mobile devices overtook desktops in global website traffic in 2019, generating 52.6% of the total pageviews. In some countries such as India and Nigeria, mobile phones account for 70%+ of web page views.
Mobile traffic from Google Analytics
According to a study involving 500+ million online shoppers across 37 countries, smartphones accounted for 65% of site visits and 46% of ecommerce orders.
Mobile shopping has massive growth potential (Image source: Statista)
Surprisingly, the conversion rate for mobile phones is less than half that of desktops. There’s phenomenal room for growth here.
Speed counts a lot for mobile shoppers (Image source: Think with Google)
You can start by making your WooCommerce store mobile-friendly. You can use Google’s Mobile Friendly Test tool to check whether your site passes the minimum mobile usability standards.
Google’s Mobile Friendly Test
The test will show you a snapshot of how your website looks on a mobile device. It’ll also list any mobile usability issues if it finds any.
The easiest way to make your WordPress website mobile-friendly is to use a responsive theme. All the themes mentioned earlier in this post are responsive out of the box and look great on mobile devices.
Mobile shoppers don’t enjoy scrolling endlessly. Hence, keep your store pages as lean as possible. Don’t overcrowd them with too much content.
If you have loads of products listed on your store, make it easier for your mobile shoppers to find them through search. You can install the WooCommerce Product Search plugin to help your customers find products swiftly with live product filters.
Simplify product search with filters (Image source: WooCommerce)
Finally, streamline the checkout experience for your online shoppers. The fewer the steps to place an order, the better the shopping experience. Here are a few WooCommerce extensions that can help you with this:
Easy mobile checkouts with Bolt
Ultimately, mobile shopping is more than just about making a purchase. Many users use it primarily to look up product information and check/compare prices. Make your online store experience great for your users on their mobile devices.
When a user makes any changes to their shopping cart, WooCommerce uses the Get Refreshed Fragments AJAX request to update the shopping cart contents dynamically. Refreshing the cart page without reloading it seems great from a user experience perspective.
But most times it slows down websites, mainly those hosted on shared servers. Plus, a lot of sites don’t end up using this feature.
Just to verify, we tested an up-to-date WooCommerce store on Pingdom Tools and here are the results:
That’s a lot of wait time for one request
Despite being just 1.1 KB in size, the wc-ajax=get_refreshed_fragments request takes 0.76 seconds to execute. If your site takes 3 seconds or less to load, that’s over 25% of the page load time. This test site is hosted on a cloud VPS, so you can imagine the load times on a cheaper hosting plan.
This post by WebNots covers the issue in greater detail. You can use the free Disable Cart Fragments or Disable Cart Fragments by Optimocha plugins to disable this taxing request.
If you disable this request, then it’s recommended enabling the option ‘Redirect to the cart page after successful addition’ in your WooCommerce → Products settings panel.
Remember to enable this setting afterward
Enabling this behavior will ensure that the user is redirected to the Cart page after adding a product to their cart.
Speed isn’t an important factor for only your store’s frontend. A snappy backend is just as crucial to manage your store with ease and make quick changes whenever needed.
Working efficiently on your WooCommerce admin panel is the key to being productive. It also frees up your time to do more essential stuff for your WooCommerce store’s success, like online marketing.
Below are a few ways to fix a slow WooCommerce dashboard.
Does the problem only occur with the WordPress admin dashboard and not the whole website? If it’s the latter, then apply all the optimizations listed earlier first.
Why? Because in most cases, making your WooCommerce store load faster on the frontend will optimize the backend too. We can attribute this to freeing up resources on your server.
If your admin dashboard lags even after optimizing the frontend, then carry on to the following suggestions.
Make sure to update WordPress, WooCommerce, plugins, extensions, and the theme frequently. If a theme or plugin is no longer supported by its developers, then it’s time to consider ditching them.
Likewise, if a theme/plugin adds unnecessary bloat to your dashboard, start looking for better alternatives. For instance, you might want to consider alternatives to plugins that serve aggressive ads in your dashboard.
Example of banner in WordPress admin
This issue is so prevalent that there are plugins solely dedicated to removing bloat from some of the most popular WordPress plugins.
Caching plugins are a great way to speed up your WordPress site. However, if not configured properly, they can lead to unexpected results. That includes slowing down your backend.
For instance, W3 Total Cache is one of the most popular caching plugins for WordPress. It’s free, supports plenty of caching options, does JS and CSS minification, integrates with a CDN, and is used by 1+ million websites.
Cache options in W3 Total Cache
W3 Total Cache features the following cache options:
Having a lot of options is confusing, especially to beginners who don’t understand what each type of caching does.
Object and database caching speed up the website by reducing the number of database queries, but they do so at the cost of offloading the work to the server’s memory.
Ideally, this shouldn’t pose a problem if your hosting server is smart or powerful enough. For instance, if your WordPress site is hosted with Kinsta, you don’t need to worry about caching as it’s already implemented at the server level.
Unfortunately, that’s not the case with every hosting provider.
In that scenario, you need to depend on a third-party caching plugin such as W3 Total Cache. Its simple settings make it super easy to enable all types of cache with just a single click.
In the W3 Total Cache → General Settings panel, disable object cache and/or database cache. Then check whether you see any improvements in your admin panel’s responsiveness.
Disable Database and Object Cache
Experimenting with the cache isn’t as simple as ticking or unpicking options in your plugin settings. You should also check whether your site works properly after making the changes and flushing your old cache.
Kinsta customers can boost their overall optimization by taking advantage of the code minification feature that is built right into the MyKinsta dashboard. This feature allows customers to enable automatic CSS and JavaScript minification with a simple click, effectively speeding up their sites with zero manual effort.
Some WordPress plugins are a great resource hog on your web server. They end up using most of your server’s CPU and RAM.
You can use the free Query Monitor plugin to find the troublesome plugins. It’ll show you all the scripts, styles, and HTTP API calls that are being loaded by your website, along with their size and loading time. Look out for the ones that have the most number of requests and the slowest load times.
On the test site below, the Classic Editor plugin loads the slowest on the admin side. Other plugins like Loginizer, All-in-One WP Migration, and WP Bakery (formerly Visual Composer) also show up as potential bloat.
Query Monitor helps you troubleshoot performance issues
We found that the migration and Classic Editor plugins are unnecessary. Removing these two plugins fixed the admin speed considerably.
WooCommerce stores with an international audience use translation plugins like WPML to serve the site dynamically in multiple languages. It’s a great plugin with a lot of features, but it can also slow down your admin backend considerably.
You can gain some performance advantage by switching to a lean translation plugin such as Polylang. It doesn’t have as many features but works great for most use cases.
Plugins that have a lot of ongoing processes/scans will slow your WordPress backend. Some examples include sitemap generators, analytics graphs and charts, page builders, and chat plugins.
If you install Query Monitor, remember to uninstall it when done as it uses a lot of server resources to perform the scans.
CDN helps to serve your WooCommerce store at lightning speed to users all around the world. It does this by saving a snapshot of your site’s resources and delivering them from the nearest server to the user.
Most CDNs disable caching on the WordPress backend by default. But some CDNs don’t, and this can slow down your store’s admin panel drastically. In such a case, you need to exclude your admin dashboard from the CDN’s cache to improve its performance.
If you’re using Cloudflare, you can set up a Page Rule to disable Cloudflare features on WordPress admin pages. Here’s how to do that:
Cloudflare Page Rules to bypass WordPress admin
It should take around 3 minutes for the settings to take effect.
If you’re using KeyCDN, then you can use their WordPress Cache Enabler Plugin to do the same. For other CDNs, please reach out to their support to sort this out.
The WordPress Heartbeat API enables near-real-time updates by maintaining a regular connection between your browser and your server. The API sends requests to the server every 15-60 seconds and then triggers events (or callbacks) upon receiving data.
It allows some amazing features such as autosaving posts, locking posts, and login expiration warnings. However, when you’re logged in as an admin, sending a few requests to the server every minute can slow down your admin panel.
WP Rocket’s free Heartbeat Control plugin allows you to manage the frequency of these API requests on the dashboard, frontend, and post editor. It even gives you the option to disable the API altogether.
Modify or disable WordPress Heartbeat API
Start by increasing the frequency of time. If that doesn’t fix your WooCommerce backend’s speed issues, consider disabling the heartbeat API.
If applying all the above optimizations still doesn’t fix your WooCommerce store’s speed issues, then…
Just like running a car with flat tires, no matter how many optimizations you make, your site won’t get any faster if it’s hosted on a lousy server. A significant portion of your site’s performance depends on the quality of your hosting.
There are different types of hosting for WordPress sites which fall under two main category: Managed and Unmanaged. The first is perfect for most users, as the hosting provider handles all the server optimizations for WordPress. The latter is better suited for technically proficient users who can tweak and manage the server on their own.
For a WooCommerce website, go for Managed WordPress Hosting. Keep in mind that managed hosting tends to be more expensive than unmanaged hosting.
You can choose from 4 major types of Managed WordPress Hosting. Each comes with its own pros and cons, so select the one that aligns with your budget and goals. I’ve compared them in the infographic below for various features.
4 main types of Managed WordPress Hosting
Each type of hosting can be offered under multiple plans at different price points. So, when scouting for a hosting within your budget, look at the features offered to decide whether it fulfills your requirements.
WooCommerce sites are incredibly dynamic by nature. They generate a lot of data and requests that cannot be cached.
For instance, the checkout page is unique for each user and cannot be served from a cache. As a result, the server needs to be robust enough to run your site smoothly, even if your site attracts low traffic.
The recommended features you should look out for when deciding on a WooCommerce hosting plan are:
With these requirements in mind, you can safely eliminate Shared Hosting.
A Virtual Private Server (VPS) is like shared hosting, except you have a virtual space in a shared server dedicated solely to you. If you’re on a strict budget, you can get started with a mid-range VPS plan. However, if your site attracts more traffic, then you’ll have to upgrade soon.
This leaves us with Cloud Hosting and Dedicated Server options. Both are great for WooCommerce sites if they fulfill your requirements.
The prices for dedicated server plans are towards the higher side as compared to cloud hosting plans, which can range from ~$50/month to thousands of dollars per month.
Kinsta’s business cloud hosting plans check off all the recommended WooCommerce requirements. Its container-based hosting is perfect for WooCommerce as it scales automatically to handle sudden traffic and load surges.
If you want to extend the features further, Kinsta offers add-ons such as Redis, extra backups, Nginx reverse proxy, and more.
Below is an example of performance gains after Kinsta migrated an ecommerce site to Google Cloud Platform’s new Compute-Optimized VMs (C2).
Massive performance benefits after migration
From ~665 ms to ~500 ms, that’s a whopping ~25% increase in performance!
If you’re spending a considerable amount of money on marketing, you’re pushing away all your leads if your site is slow, so it’s well worth opting for the fastest WordPress hosting solutions.
Ultimately, you’re better off spending a few extra dollars every month on quality hosting, rather than spending hours pulling out your hair and wondering why your site still has a high bounce rate.
Time is literally money for an ecommerce site. A fast WooCommerce store boosts user experience, SEO, revenue, and ROI.
While you don’t have to follow all the speed optimization tips listed in this post, we recommend you to go through all of them. This will help you identify any bottlenecks in your site. No one likes to wait for a site to load. Let’s speed up WooCommerce!
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
Original article source at: https://kinsta.com/
1674808949
Hello Readers!! In this blog, we will see how to create, get and delete secrets in the AWS parameter store using CLI. In my previous blog, we have seen what is AWS Parameter store and how we can create parameters using the AWS console. Follow the below blog for more information:
https://blog.knoldus.com/getting-started-with-aws-parameter-store/
Install AWS CLI on your system. Follow the following blog for steps for installation:
https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
Configure AWS CLI.
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html
Now, let’s get started with AWS CLI!!
Use put-parameter to create and store a parameter in the AWS Parameter store. Below is the format for reference:
$ aws ssm put-parameter --name <name_of_parameter> --value <parameter_value> --type <type_of_parameter>
$ aws ssm put-parameter --name LINUX-AMI --value abcd12345 --type String
For verifying that everything is stored in the file use get-parameter. So, for pulling the parameter use the following format:
$ aws ssm get-parameter --name <name_of_parameter>
$ aws ssm get-parameter --name LINUX-AMI
We can now see the value. As this parameter is of type string. So, it is not encrypted.
What if we want to store a password or an API key which I do not want to reveal. So, for this use type as SecureString.
$ aws ssm put-parameter --name <name_of_parameter> --value <parameter_value> --type SecureString
$ aws ssm put-parameter --name Password --value mySecretPasswordhere --type SecureString
Now, if I want to get this parameter then it will not give me the actual value. It will provide parameter store value in encrypted format because it is of type SecureString. Use the following command for getting the value:
$ aws ssm get-parameter --name <name_of_parameter>
$ aws ssm get-parameter --name Password
If we want to get this value in decrypted format. Use the following command:
$ aws ssm get-parameter --name <name_of_parameter> –with-decryption
$ aws ssm get-parameter --name Password –with-decryption
Now, we will see how we can create a hierarchical parameter store or we can say nested parameter store. For this use the below command:
$ aws ssm put-parameter --name <nested_path_for_parameter> --value <parameter_value> --type SecureString
$ aws ssm put-parameter --name /myDb/MySQL/Db_password --value myDBSecretPasswordhere --type SecureString
We can see in the AWS console also:
It is created.
For getting parameters use the command:
$ aws ssm get-parameter --name /myDb/MySQL/Db_password
As its type is SecureString it is in an encrypted format.
If I want to update the existing parameter value use –overwrite flag. It will create a new version of that parameter store. Use the below command for updating the value:
$ aws ssm put-parameter --name <name_of_parameter> --overwrite --value <parameter_new_value> --type String
$ aws ssm put-parameter --name LINUX-AMI --overwrite --value new_password --type String
By default, any parameter is created in the standard tier. But If you want to create in the Advanced tier use:
$ aws ssm put-parameter --name <name_of_parameter> --value <parameter_value> --type <type> --tier Advanced
$ aws ssm put-parameter --name my_Password --value mySecretPasswordhere --type SecureString --tier Advanced
As you can see below advanced tier parameter in the AWS console:
For deleting a parameter from the parameter store use the following command:
$ aws ssm delete-parameter --name my_Password
$ aws ssm delete-parameter --name my_Password
If I will try to get this parameter it will show ParameterNotFound.
We are all done now!!
Thank you for sticking to the end. In this blog, we have learned how to create, get and delete secrets in the AWS parameter stores using CLI. This is really very quick and simple. I hope this blog helped you somewhere. If you like this blog, please share my blog and show your appreciation by giving thumbs-ups, and don’t forget to give me suggestions on how I can improve my future blogs that can suit your needs.
Original article source at: https://blog.knoldus.com/
1673607720
simpleStore is a clean, responsive storefront boilerplate with no database you can setup in minutes. simpleStore is built on simpleCart.js and Skeleton CSS Framework for a lightweight, fast, simple to use, and completely customizable experience.
Features
Plugins
Demo
You can see a working demo here
Installation
Install with Bower
bower install
or manually install using the latest release
Setup
1.Make sure simpleStore is on a web server (any type will do as long as it can serve static web pages).
2.Configure your payment options in js/config.js
.
checkout: {
type: "PayPal" ,
email: "you@yours.com"
},
3.Edit the js/config.js
to your liking.
4.Add additional products in the products.json
file.
Using Plugins
To use a plugin, add a reference just before your config.js
file
<script src="plugins/google-sheets.js"></script>
<script src="js/config.js"></script>
If you are looking for something more basic, check out the HTML version on this branch. The HTML version uses plain HTML to build the store instead of a JSON file.
Add additional products using the <div class="simpleCart_shelfItem"></div>
tags.
For further documentation on expanding/tweaking simpleStore, check out the framework/plugin pages.
ALL JavaScript shopping carts are NOT fullproof. Because simpleStore is fully client-side, some users may attempt to alter prices before checkout. SimpleStore does the best it can to minimize this kind of activity. Make sure to monitor your sales. Just like in real life, if someone walks into your store and changes the price tag, you will certainly not honor those changes.
Contributing
All forms of contribution are welcome: bug reports, bug fixes, pull requests and simple suggestions. If you do wish to contribute, please follow the Airbnb Javascript Style Guide Thanks!
You can find the list of contributors here.
UPDATES COMING SOON! Get notified
Sign up to get updates on new features and releases
Author: Chrisdiana
Source Code: https://github.com/chrisdiana/simplestore
License: MIT license
1670507104
Figuring out authentication is part of a secure data storage strategy. Find out how to store auth data safely in your database.
Almost every application requires user authentication; that is why authentication data storage is a common feature of database and application design. Special attention is needed to ensure data is kept secure and to avoid breaches that can compromise sensitive information.
Although both words are frequently used in a similar way, they do not mean the same thing. Most systems require both authentication and authorization, so let’s first explain what each one means.
Authentication is a process that verifies that a person (in software application terms, the user) is whoever they say they are. It uses different mechanisms (password, security questions, fingerprint recognition, etc.) to confirm that the user is the person they are claiming to be. Modern systems combine many of these mechanisms and add additional methods (like one-time codes sent to email or phone) to authenticate users.
Authorization verifies that the user has permission to perform a specific task or access specific data. A set of policies or rules may be established to define the actions a user can perform. Authorization is usually processed AFTER authentication.
The article APPLYING SIMPLE ACCESS CONTROL TO A SMALL DATA MODEL explains more about the difference between authentication and authorization. For now, we’ll review some authentication methods and explain how to securely store authentication data in a database.
There are many authentication methods applications employ to verify a user’s identity:
Not all of these methods require data to be stored on your own databases, so we’ll concentrate on those authentication methods that require storing sensitive information on your database.
Now we are going to review some of the best practices to store passwords in a database.
It should be quite obvious that storing passwords as plain text in our database is not a good idea, since it would mean that anyone with access to the database would be able to see all user passwords. Once we discard the option to store passwords in plain text, should we choose encryption or hashing?
Encryption is a two-way process that "scrambles'' readable text and converts it into something that is "illegible" until it is decrypted (using a "decryption key") and converted back to readable text. There are many encryption algorithms (like AES, DES, Twofish, and Blowfish).
Hashing is a one-way process that converts a string (usually a legible one) into another (illegible) string. No matter the size of the input string, a hashing mechanism returns a fixed length string output. As with encryption, there are several hashing algorithms (like MD5, SHA-1, SHA-2) that can be used to hash user passwords; we will see some of them later in the article.
You may initially be tempted to use encryption to store your passwords, but that is not the right approach! If you store encrypted passwords, the application will have to decrypt the stored password (using a decryption key) and compare it – every single time the user logs in. But if someone gets to know the decryption key, that person would be able to decrypt and access all stored passwords. That is a security concern.
If you store hashed rather than encrypted passwords, the application can simply hash the entered password and compare it with the stored hash. This way, nobody can decrypt the stored values.
Don’t worry – you’re still reading an article about login data and not a cooking recipe! Salting and peppering in this context refer to additional security measures taken to ensure passwords stored in a database are kept secure. Let’s discuss them.
Salting consists of generating a long and random string for each user and adding it to each typed-in password before hashing. That "salt" value must be stored together with the hashed password. This mechanism offers some notable benefits:
To generate the salt for each user, use a reliable random generator like SECURERANDOM, which is recommended by OWASP. The formula to calculate the hashed value would be:
Hashed Password = HASH(INDIVIDUAL SALT + PASSWORD)
Peppering is simply adding an additional string to the “password + salt” combination before hashing it. (This extra string is often called “Secret” or “Pepper”; it’s not as frequently implemented as salting.) We are not going to dig into all the details of peppering; you can find them on WIKIPEDIA. The main differences between peppering and salting are:
Hashed Password = HASH(INDIVIDUAL SALT + PASSWORD + COMMON PEPPER)
Some cryptographic algorithms are older; their usage should be avoided for password hashing, since they present some vulnerabilities. MD5 and SHA-1 have been reported as vulnerable due to collisions; the SHA-2 family of algorithms is currently the standard for hashing passwords. Having said that, newer options like SHA-3 offer more secure options. Longer hashes require more computation time to calculate and generate dictionary-based, brute force, or rainbow table attacks.
Now that we have explained the best way to store login data in a database, let’s take a quick look to a simple data model that stores user information:
In this diagram, we have a UserAccount
entity with the following attributes:
UserAccountID
: An auto generated ID.LoginName
: The name used by the user to login in the system. Some systems may use an email address as a login name, but I would recommend keeping this as a separate attribute and allowing several options like a username, an email, or even a phone number.FirstName
: The user’s first name.LastName
: The user’s last name.Email
: The user’s email address. This is used to confirm account creation or send password reset confirmations.PasswordHash
: A hash string for the user’s password plus the salt and pepper combination.PasswordSalt
: A unique, randomly-generated string that is concatenated with the user’s password before it is hashed and stored in the PasswordHash
column.PasswordDate
: The date when the user last updated or created their password; this is useful when the password needs to be renewed.After you have designed your data structure to store passwords in your database, you should consider reading the article EMAIL CONFIRMATION AND RECOVERING PASSWORDS to enhance your application with the features described in the article.
We have just reviewed some considerations and recommendations for safely storing passwords in our databases. But a secure platform is not easy to design and implement, so you may also need to think about relying on experts for authentication.
There are open standards that can be used to delegate authentication to a reliable third party, like Google, Facebook or Twitter. Let’s do a quick overview of them.
This standard allows authentication against an IDENTITY PROVIDER. As shown in the image below, the user logs in to the identity provider and it sends a certificate or key that confirms the user’s identity to the application making the request.
This standard is an extension (you can see it as a special defined use case) of the OAuth 2.0 Framework explained below. When you log in into Google to access your YouTube account, you are using OpenID. Open ID allows only the ID, profile, email, address and/or phone number to be shared to the calling application.
OAuth is an authorization standard, not an authentication standard, but it can be used for “pseudo-authentication”. Rather than asking a third party to certify that a user is who they claim to be, this authorization API provides a key to access some part of the user’s account with the provider (usually containing basic information like name and email address) and/or to perform actions like sending messages, posting tweets, etc.
Although the provider does not certify an identity, the fact that it provides a key to access a specific account can be considered as proof that the user sending the key is actually the person they say they are.
If you use your Google or Facebook account to access a third-party application and you receive a message that you’re sharing your basic information with the third party, then you are using the more generic OAuth protocol rather than OpenID. The third-party application is accessing some information or tasks on the authorization provided rather than just validating your identity.
Although each method was designed for a different purpose, they can both be used to allow access to an application by delegating the authentication process to a well-known provider. This allows you to avoid designing and implementing a proprietary authentication feature – and the security risks that may exist if this feature is not well designed and implemented.
If you want to review more on storing authentication data in a database, see the article HOW TO STORE AUTHENTICATION DATA IN A DATABASE PART 4. It includes a sample data model used to store delegated authentication information (like authentication or authorization tokens and additional data) in your database.
Original article source at: https://www.vertabelo.com/
1670215980
Database is used to store and maintain data. Based on stored data generate report, perform actions, etc.
You can also use it to manage the collection of related files. For this, you can either create a new table or update the existing table to store file information.
In this post, I will show you how to upload file and store to PostgreSQL database with PHP.
I am using files
the table in the example –
CREATE TABLE files (
id serial PRIMARY KEY,
file_name varchar(100) NOT NULL,
file_path varchar(100) NOT NULL
)
Fields –
Create config.php
file for database configuration.
Completed Code
<?php
$host = "localhost";
$user = "postgres";
$password = "root";
$dbname = "tutorial";
$con = pg_connect("host=$host dbname=$dbname user=$user password=$password");
if (!$con) {
die('Connection failed.');
}
Create <form method="post" action="upload.php" enctype="multipart/form-data">
. In the <form >
create a file element and a submit button.
Completed Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Upload And Store File To PostgreSQL with PHP</title>
</head>
<body>
<?php
// Status message
if(isset($_GET['status'])){
$status = $_GET['status'];
if($status == 'success')
echo "Upload successfully.";
else if($status == 'failed')
echo "File is not uploaded.";
else if($status == 'required')
echo "Please select a file.";
}
?>
<div style="margin-top: 20px; ">
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file" > <br><br>
<input type="submit" name="submit" value="Upload">
</form>
</div>
</body>
</html>
Create upload.php
file that calls on <form >
submit.
Also, create an upload
folder to store files.
Read file name and assign it to the variable, assign upload
to $target_folder
variable.
Assign file extensions to $extensions_arr
Array. If file extension exists in $extensions_arr
Array then upload the file.
If uploaded successfully then insert a record in the files
table.
Completed Code
<?php
include "config.php";
if(isset($_POST['submit'])){
$uploadstatus = "";
if(isset($_FILES['file'])){
$file_name = $_FILES['file']['name'];
$target_folder = "upload/";
$target_file = $target_folder . basename($file_name);
// Select file type
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","pdf","txt");
// Check extension
if( in_array($fileType,$extensions_arr) ){
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){
// Insert record
$query = "INSERT INTO files(file_name,file_path) VALUES ($1,$2)";
pg_query_params($con, $query, array($file_name,$target_file));
$uploadstatus = "success";
}else{
$uploadstatus = "failed";
}
}else{
$uploadstatus = "failed";
}
}else{
$uploadstatus = "required";
}
header('Location: index.php?status='.$uploadstatus);
}
Read all records from the files
table.
Loop on the fetched records. Check the file extension if it is image type then display file using <img >
tag. Pass $file_path
in src
attribute.
If file is not image type then display using <a >
tag. Pass $file_path
in href
attribute.
Completed Code
<?php
include "config.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Upload And Store File To PostgreSQL with PHP</title>
<!-- CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
<div class="container mt-5">
<div class="row">
<?php
// Fetch all records
$sql = "select * from files";
$records = pg_query($con, $sql);
$html = "";
$imageExtensions_arr = array("jpg","jpeg","png");
while ($row = pg_fetch_assoc($records) ){
$file_name = $row['file_name'];
$file_path = $row['file_path'];
$extension = strtolower(pathinfo($file_path,PATHINFO_EXTENSION));
$html .= "<div class='col-md-3' >";
if(in_array($extension,$imageExtensions_arr)){
$html .= "<img src='".$file_path."' width='200px' height='200px' >";
$html .= "<br>".$file_name;
}else{
$html .= "<a href='".$file_path."' >".$file_name."</a>";
}
$html .= "</div>";
}
echo $html;
?>
</div>
</div>
</body>
</html>
In the example, I stored the file path in the database but you can also use bytea
datatype to store a file in binary form. To display it on the page you need to first write binary data in a file and then use the created file path.
If you found this tutorial helpful then don't forget to share.
Original article source at: https://makitweb.com/
1668503169
In this Algorithm article, let's learn about What Is A* Search Algorithm?. Intelligence is the strength of the human species; we have used it to improve our lives. Then, we created the concept of artificial intelligence to amplify human intelligence and to develop and flourish civilizations like never before. A* Search Algorithm is one such algorithm that has been developed to help us. In this blog, we will learn more about what the A* algorithm in artificial intelligence means, the steps involved in the A* search algorithm in artificial intelligence, its implementation in Python, and more.
AI helps us solve problems of various complexities. Computational problems like path search problems can be solved using AI. Search problems where you need to find a path from one point to another, say, point A to point B. Sometimes you need to solve it by mapping those problems to graphs, where nodes represent all the possible outcomes. A* algorithm comes up as an answer to these problems.
Created as part of the Shakey project aimed to build a mobile robot that has artificial intelligence to plan its actions, A* was initially designed as a general graph traversal algorithm. It is widely used in solving pathfinding problems in video games. Because of its flexibility and versatility, it can be used in a wide range of contexts. A* is formulated with weighted graphs, which means it can find the best path involving the smallest cost in terms of distance and time. This makes A* algorithm in artificial intelligence an informed search algorithm for best-first search. Let us have a detailed look into the various aspects of A*.
A* search algorithm is an algorithm that separates it from other traversal techniques. This makes A* smart and pushes it much ahead of conventional algorithms.
Let’s try to understand Basic AI Concepts and comprehend how does A* algorithm work. Imagine a huge maze that is too big that it takes hours to reach the endpoint manually. Once you complete it on foot, you need to go for another one. This implies that you would end up investing a lot of time and effort to find the possible paths in this maze. Now, you want to make it less time-consuming. To make it easier, we will consider this maze as a search problem and will try to apply it to other possible mazes we might encounter in due course, provided they follow the same structure and rules.
As the first step to converting this maze into a search problem, we need to define these six things.
To solve the problem, we need to map the intersections to the nodes (denoted by the red dots) and all the possible ways we can make movements towards the edges (denoted by the blue lines).
A denotes the starting point, and B denotes the endpoint. We define the starting and endpoints at nodes A and B, respectively.
If we use an uninformed search algorithm, it would be like finding a path that is blind, while an informed algorithm for a search problem would take the path that brings you closer to your destination. For instance, consider Rubik’s cube; it has many prospective states that you can be in, making the solution very difficult. This calls for the use of a guided search algorithm to find a solution. This explains the importance of A*.
Unlike other algorithms, A* decides to take up a step only if it is convincingly sensible and reasonable as per its functions. This means it never considers any non-optimal steps. This is why A* is a popular choice for AI systems that replicate the real world – like video games and machine learning.
Step 1: Add the beginning node to the open list
Step 2: Repeat the following step
In the open list, find the square with the lowest F cost, which denotes the current square. Now we move to the closed square.
Consider 8 squares adjacent to the current square and Ignore it if it is on the closed list or if it is not workable. Do the following if it is workable.
Check if it is on the open list; if not, add it. You need to make the current square as this square’s a parent. You will now record the different costs of the square, like the F, G, and H costs.
If it is on the open list, use G cost to measure the better path. The lower the G cost, the better the path. If this path is better, make the current square as the parent square. Now you need to recalculate the other scores – the G and F scores of this square.
– You’ll stop:
If you find the path, you need to check the closed list and add the target square to it.
There is no path if the open list is empty and you cannot find the target square.
Step 3. Now you can save the path and work backward, starting from the target square, going to the parent square from each square you go, till it takes you to the starting square. You’ve found your path now.
It’s easy to give movement to objects. But pathfinding is not simple. It is a complex exercise. The following situation explains it.
The task is to take the unit you see at the bottom of the diagram to the top of it. You can see that nothing indicates that the object should not take the path denoted with pink lines. So it chooses to move that way. As and when it reaches the top, it has to change its direction because of the ‘U’ shaped obstacle. Then it changes direction and goes around the obstacle to reach the top. In contrast to this, A* would have scanned the area above the object and found a short path (denoted with blue lines). Thus, pathfinder algorithms like A* help you plan things rather than waiting until you discover the problem. They act proactively rather than reacting to a situation. The disadvantage is that it is a bit slower than the other algorithms. You can use a combination of both to achieve better results – pathfinding algorithms give a bigger picture and long paths with obstacles that change slowly, and movement algorithms for a local picture and short paths with obstacles that change faster.
Read how artificial intelligence will create more jobs by 2025.
A* algorithm works based on heuristic methods, and this helps achieve optimality. A* is a different form of the best-first algorithm. Optimality empowers an algorithm to find the best possible solution to a problem. Such algorithms also offer completeness; if there is any solution possible to an existing problem, the algorithm will definitely find it.
When A* enters into a problem, firstly, it calculates the cost to travel to the neighboring nodes and chooses the node with the lowest cost. If The f(n) denotes the cost, A* chooses the node with the lowest f(n) value. Here ‘n’ denotes the neighboring nodes. The calculation of the value can be done as shown below:
f(n)=g(n)+h(n)f(n)=g(n)+h(n)
g(n) = shows the shortest path’s value from the starting node to node n
h(n) = The heuristic approximation of the value of the node
The heuristic value has an important role in the efficiency of the A* algorithm. To find the best solution, you might have to use different heuristic functions according to the type of the problem. However, the creation of these functions is a difficult task, and this is the basic problem we face in AI.
A heuristic is simply called a heuristic function that helps rank the alternatives given in a search algorithm at each of its steps. It can either produce a result on its own or work in conjugation with a given algorithm to create a result. Essentially, a heuristic function helps algorithms to make the best decision faster and more efficiently. This ranking is based on the best available information and helps the algorithm decide the best possible branch to follow. Admissibility and consistency are the two fundamental properties of a heuristic function.
A heuristic function is admissible if it can effectively estimate the real distance between a node ‘n’ and the end node. It never overestimates; if it ever does, it will be denoted by ‘d’, which also denotes the accuracy of the solution.
A heuristic function is consistent if the estimate of a given heuristic function turns out to be equal to or less than the distance between the goal (n) and a neighbor and the cost calculated to reach that neighbor.
A* is indeed a very powerful algorithm used to increase the performance of artificial intelligence. It is one of the most popular search algorithms in AI. The sky is the limit when it comes to the potential of this algorithm. However, the efficiency of an A* algorithm highly depends on the quality of its heuristic function. Wonder why this algorithm is preferred and used in many software systems? There is no single facet of AI where the A*algorithm has not found its application. From search optimization to games, robotics, and machine learning, the A* algorithm is an inevitable part of a smart program.
In this section, we are going to find out how the A* search algorithm can be used to find the most cost-effective path in a graph. Consider the following graph below.
The numbers written on edges represent the distance between the nodes, while the numbers written on nodes represent the heuristic values. Let us find the most cost-effective path to reach from start state A to final state G using the A* Algorithm.
Let’s start with node A. Since A is a starting node, therefore, the value of g(x) for A is zero, and from the graph, we get the heuristic value of A is 11, therefore
g(x) + h(x) = f(x)
0+ 11 =11
Thus for A, we can write
A=11
Now from A, we can go to point B or point E, so we compute f(x) for each of them
A → B = 2 + 6 = 8
A → E = 3 + 6 = 9Since the cost for A → B is less, we move forward with this path and compute the f(x) for the children nodes of B
Since there is no path between C and G, the heuristic cost is set to infinity or a very high value
A → B → C = (2 + 1) + 99= 102
A → B → G = (2 + 9 ) + 0 = 11
Here the path A → B → G has the least cost but it is still more than the cost of A → E, thus we explore this path further
A → E → D = (3 + 6) + 1 = 10
Comparing the cost of A → E → D with all the paths we got so far and as this cost is least of all we move forward with this path. And compute the f(x) for the children of D
A → E → D → G = (3 + 6 + 1) +0 =10
Now comparing all the paths that lead us to the goal, we conclude that A → E → D → G is the most cost-effective path to get from A to G.
Next, we write a program in Python that can find the most cost-effective path by using the a-star algorithm.
First, we create two sets, viz- open and close. The open contains the nodes that have been visited, but their neighbors are yet to be explored. On the other hand, close contains nodes that, along with their neighbors, have been visited.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
|
Output:
Path Found: [ 'A','E','D','G']
How does the A * algorithm work?
A* Algorithm works by vertices in the graph, which start with the object’s starting point and then repeatedly examines the next unexamined vertex, adding its vertices to the set of vertices that will be examined.
What is the difference between the A* and AO* algorithm?
An A* is an OR graph algorithm used to find a single solution, while AO* Algorithm is an AND-OR graph algorithm used to find many solutions by ANDing over more than one branch.
Why is the A* algorithm popular?
A* Algorithm is popular because it is a technique that is used for finding path and graph traversals. Many web-based maps and games use this algorithm.
Is A* better than Dijkstra?
A* is usually considered better than Dijkstra as it performs informed and not uninformed searches. It expands more promising vertices.
Does Google Maps use the A* algorithm?
No. Google Maps uses the Dijkstra algorithm.
Why is A* optimal?
A* Algorithms are optimal. It relies on an open and closed list to find a path that is optimal and complete towards the goal.
How overestimation is handled in the A* algorithm?
Overestimation happens when the estimate of the heuristic is more than the actual cost of the final path.
Original article source at: https://www.mygreatlearning.com
1668502434
In this Python article, let's learn about What is Palindrome in Python? Codes, Algorithms, and more. A palindrome is a word, phrase, number, or another sequence of units that can be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers. When its digits are reversed, they turn out to be the same number as the original number. Palindromes can be numeric as well. For example, madam, 1234321. This blog will teach us how to create a Palindrome in Python.
If you want to dive further, check out this free course on Palindrome in Python and PG Programs on Software Engineering. It covers the fundamentals of python programming, such as its syntax, variables, data types, operators, tokens, and strings. This course also offers you a certificate on completion to help you stay ahead of the competition.
A palindrome is a word, phrase, number, or another sequence of units that may be read the same way in either direction, generally if used comma-separated.
Happy belated multi-cultural palindrome day! 02/02/2020 was a unique day in February. It works whether your preferred date format is MM/DD/YYYY or DD/MM/YYYY or YYYY/MM/DD.
These patterns are called palindromes. Reading them from the first character or backward doesn’t make any difference. This is an interesting introductory problem to solve with the use of programming. In this blog, we will understand the thought process, go step by step, and come up with various solutions to check whether the string is a palindrome.
A palindrome is a word, phrase, number, or another sequence of characters that reads the same backward as forward.
They are classified into 3 types, which are Palindrome numbers,
Palindrome strings, Palindrome phrase: A collection of words and special characters.
A Palindrome Number is a collection of numbers that remains the same when read backward. These numbers are also said to be symmetrical. When its digits are reversed, they turn out to be the same number as the original number. E.g., 1234321 is a Palindrome. If its digits are reversed, it again becomes 1234321, our original number. 1234232 is not a Palindrome. When reversed, the new number becomes 2324321, which is different from the original.
A Palindrome String is a collection of alphabets that remains the same when read backward. They are also called Symmetrical Alphabets. When its alphabets are written in reverse order, they turn out to be the same combination of alphabets as the original string. E.g., “madam” is a Palindrome. If its alphabets are reversed, it again becomes “madam,” which was our original string. “napkin” is not a Palindrome. When reversed, the new number becomes “nikpan” which is different from the original string.
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Below are a few examples of Palindromes:
Trivia: Is 02/02/2020 a palindrome string when considered a palindrome phrase?
You can enroll in these Python-related courses to get comfortable in Python Programming Language and get your free certificate on Great Learning Academy before practicing Palindromes algorithm and code in Python.
Data Science with Python |
Python for Machine Learning |
Data Visualization using Python |
Artificial Intelligence with Python |
Now how to create Palindromes in Python?
Consider the algorithm for the Problem Statement: Find if a string is a Palindrome or not.
Now let us consider an algorithm for the Problem Statement: Find if a number is a Palindrome or not.
Now that we have the algorithm, let us convert it into code by following a similar logic.
number=int(input("Enter any number :"))
#store a copy of this number
temp=number
#calculate reverse of this number
reverse_num=0
while(number>0):
#extract last digit of this number
digit=number%10
#append this digit in reveresed number
reverse_num=reverse_num*10+digit
#floor divide the number leave out the last digit from number
number=number//10
#compare reverse to original number
if(temp==reverse_num):
print("The number is palindrome!")
else:
print("Not a palindrome!")
def check_palindrome(string):
length = len(string)
first = 0
last = length -1
status = 1
while(first<last):
if(string[first]==string[last]):
first=first+1
last=last-1
else:
status = 0
break
return int(status)
string = input("Enter the string: ")
print("Method 1")
status= check_palindrome(string)
if(status):
print("It is a palindrome ")
else:
print("Sorry! Try again")
Input – Madam
Output – It is a palindrome
This is a good approach, but Python enables us to use the reverse function. We know that a word read forwards and backward if the same is a palindrome. Hence, let us generate the forward and backward strings for the same and check if the two strings are the same.
def check_palindrome_1(string):
reversed_string = string[::-1]
status=1
if(string!=reversed_string):
status=0
return status
string = input("Enter the string: ")
status= check_palindrome_1(string)
if(status):
print("It is a palindrome ")
else:
print("Sorry! Try again")
Input: Enter the string: malayalam
Output: It is a palindrome
This is a good approach, but Python enables us to use the reverse function. We know that a word reads forwards and backward if the same is a palindrome. Hence, let us generate the forward and backward strings for the same and check if the two strings are the same.
def check_palindrome_1(string):
reversed_string = string[::-1]
status=1
if(string!=reversed_string):
status=0
return status
string = input("Enter the string: ")
status= check_palindrome_1(string)
if(status):
print("It is a palindrome ")
else:
print("Sorry! Try again")
Input: Enter the string: malayalam
Output: It is a palindrome
In this article, we will see different ways of implementing the palindrome program in Python
Method 1:
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "kayak"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
Steps:
Method 2:
def isPalindrome(str):
for i in range(O, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "kayak"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
Steps:
Method 3:
def isPalindrome(s):
rev = ‘'.join(reversed(s))
if (s == rev):
return True
return False
# main function
s = "kayak"
ans = isPalindrome(s)
if(ans):
print("Yes")
else:
print("No")
Steps:
In this method, we are using a predefined function ‘.join’
Method 4:
def isPalindrome(s):
s = s.lower()
1 = len(s)
if 1 <2:
return True
elif s(0) == s{l - 1):
return isPalindrome(s[1: l - 1])
else:
return False
s = "Kayak"
ans = isPalindrome(s)
if ans:
print("Yes")
y else:
print("No")
Steps:
This method compares the first and last element of the string and gives the rest of the substring a recursive call to itself.
Let’s step this up and consider another data structure. What if the data is stored in a linked list? To tackle this, we need to understand linked lists. A linked list is a data structure with a non-contiguous allocation of memory.
We will begin by defining a linked list in python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def __init__(self,seq):
"""prepends item of lists into linked list"""
self.head = None
for item in seq:
node = ListNode(item)
node.next = self.head
self.head = node
def palindrome(self):
""" Check if linked list is palindrome and return True/False."""
node = self.head
var = node #var is initialized to head
prev = None #initially, prev is None
# prev approaches to middle of list till var reaches end or None
while var and var.next:
var = var.next.next
temp = node.next #reverse elements of first half of list
node.next = prev
prev = node
node = temp
if var: # in case of odd num elements
tail = node.next
else: # in case of even num elements
tail = node
while prev:
# compare reverse element and next half elements
if prev.val == tail.val:
tail = tail.next
prev = prev.next
else:
return False
return True
# Test Cases
list_1 = Solution([7, 8, 6 , 3 , 7 ,3 , 6, 8, 7])
print([7, 8, 6 , 3 , 7 ,3 , 6, 8, 7],end='->')
print(list_1.palindrome())
list_2 = Solution([6 , 3 , 4, 6])
print([6 , 3 , 4, 6],end='->')
print(list_2.palindrome())
list_3 = Solution([3, 7 ,3 ])
print([ 3 , 7, 3],end='->')
print(list_3.palindrome())
list_4 = Solution([1])
print([1],end='->')
print( list_4.palindrome())
Output –
3, 7, 3 – True
1 – True
The logic for checking if a linked list is a palindrome or not is the modified version of the one we implemented on strings and arrays. We check if the reverse of the linked list is the same as the original sequence. Instead of reversing the entire linked list and storing it in a temporary location, we reverse the first half of the linked list and check if the first half and second half match after reversal.
Check out a* Algorithm in Artificial Intelligence.
Therefore, we define a function called palindrome, which has parameters node, var( stands for variable), previous, and temp. We jump to the end of the list using the variable var in line 29, and meanwhile, we store the last node data in variable prev. Therefore, comparing the prev.val and tail.val in line 41 gives us the answer.
# Test Cases
list_1 = Solution([7, 8, 6 , 3 , 7 ,3 , 6, 8, 7])
print(list_1.palindrome())
list_2 = Solution([6 , 3 , 4, 6])
print(list_2.palindrome())
list_3 = Solution([3, 7 ,3 ])
print(list_3.palindrome())
listl_4 = Solution([1])
Print( list_4.palindrome())
In this article, we looked at palindromes inside and out and understood them thoroughly. Try developing better implementation techniques using different data structures to improve your command over coding. We shall keep posting many more articles on implementing data structures and algorithms using Python Stay tuned and Read the Top Ten Python Books.
Original article source at: https://www.mygreatlearning.com
1667140337
galaxy_store_in_app_review
This is a library that wraps the Galaxy Store Review Broadcast provided by the Samsung Galaxy Store for easy use in Flutter. Much inspired by britannio/in_app_review.
Usage
requestReview()
import 'package:galaxy_store_in_app_review/galaxy_store_in_app_review.dart';
if (await GalaxyStoreInAppReview.isAvailable()) {
GalaxyStoreInAppReview.requestReview();
}
openStoreListing()
import 'package:galaxy_store_in_app_review/galaxy_store_in_app_review.dart';
GalaxyStoreInAppReview.openStoreListing();
Disclaimer
This is an early project. Please let me know if there is a problem.
Run this command:
With Flutter:
$ flutter pub add galaxy_store_in_app_review
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
galaxy_store_in_app_review: ^0.0.3
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:galaxy_store_in_app_review/galaxy_store_in_app_review.dart';
import 'package:flutter/material.dart';
import 'package:galaxy_store_in_app_review/galaxy_store_in_app_review.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _packageNameController = TextEditingController();
bool _isAvailable = false;
String _debugMessage = "";
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('GalaxyStore Inapp Review Sample'),
),
body: Padding(
padding: const EdgeInsets.all(15),
child: Column(
children: [
Row(
children: [
Expanded(
child: TextField(
controller: _packageNameController,
decoration: const InputDecoration(
labelText: "Input your package name",
),
),
),
ElevatedButton(
onPressed: () async {
var targetPackage = _packageNameController.text.isEmpty
? null
: _packageNameController.text;
await GalaxyStoreInAppReview.openStoreListing(
targetPackage: targetPackage);
},
child: const Text("OPEN STORE"),
)
],
),
ElevatedButton(
onPressed: () async {
var targetPackage = _packageNameController.text.isEmpty
? null
: _packageNameController.text;
setState(() {
_debugMessage =
"Checking availability - ${targetPackage ?? "(Current app)"}";
});
var isAvailable = await GalaxyStoreInAppReview.isAvailable(
targetPackage: targetPackage);
setState(() {
_debugMessage =
"${targetPackage ?? "(Current app)"} is ${isAvailable ? "" : "not "}available for review.";
_isAvailable = isAvailable;
});
},
child: const Text("CHECK REVIEW AUTHORITY"),
),
ElevatedButton(
onPressed: _isAvailable
? () async {
await GalaxyStoreInAppReview.requestReview();
}
: null,
child: const Text("OPEN GALAXYSTORE REVIEW POPUP"),
),
Text(_debugMessage)
],
),
),
),
);
}
}
Download Details:
Author: youngminz
Source Code: https://github.com/youngminz/galaxy_store_in_app_review
1665176640
Simple package that allows you to store, retrieve and listen to your data anywhere across your project.
First, add the following dependency to your pubspec.yaml.
dependencies:
data_storeholder: ^1.0.5
After that, run the flutter packages get
or dart pub get
command.
Next, add the following import to places where you need it.
import 'package:data_storeholder/store.dart';
Store class
Store class is wrapper for your data. It can hold any type or object and adds useful functionality to it.
Store<String> stringStore = Store.empty();
Store<String> stringStore = Store('Some default value');
Store provides getter and setter for the data
variable
stringStore.data = 'New data!';
print(stringStore.data);
This example should print 'New data!' in console. Let's create listener for the variable so we don't have to call print method each time the data changes. We can call addOnDataChangedListener
method that accepts void Function as parameter. The function will provide the data variable as parameter.
stringStore.addOnDataChangedListener((data) => print(data));
Now each time we call the setter for the data variable inside of our stringStore, all listeners will be notified.
stringStore.data = 'Data has changed!';
This example should print 'Data has changed!' in console. In case we don't want to change the data but we want to notify the listeners, we can call notifyListeners
method.
stringStore.notifyListeners();
This should again print 'Data has changed!' because that is the current value stored in data variable.
If we wish to remove the listener, we can call removeOnDataChangedListener
method which accepts void Function as parameter.
void printFunction(dynamic data) => print(data);
stringStore.addOnDataChangedListener(printFunction);
stringStore.data = '1';
stringStore.removeOnDataChangedListener(printFunction);
stringStore.data = '2';
The example above should only print 1
because at the point when data was set to 2
, the listener was already removed.
StoreHolder class
StoreHolder class is single instance object that can hold instances of your Store. It uses HashMap to store the instances so retrieval of the instance is almost instant. This means that you can share your data anywhere in your project
StoreHolder storeHolder = StoreHolder();
We already created our Store instance. Now let's store it in StoreHolder so we can access it anywhere in our project. To store it, we use addStoreInstance
method that accepts String key and Store instance as parameter.
storeHolder.addStoreInstance('stringStore1', stringStore);
Method safeAddStoreInstance
is used when we are not sure if there is any Store instance at given key. The method return true is the supplied Store instance was added to the map. If there already exists some entry at given key, the entry is preserved and the method returns false.
storeHolder.safeAddStoreInstance('stringStore1', stringStore);
We recommend to name your key such that it contains the type of your Store instance as to avoid type mismatch.
Now the stringStore is stored in StoreHolder. We can access it anywhere else in project by calling getStoreInstance
which accepts String key as parameter and returns our Store instance. In case there is no Store instance for given key, it returns new Store.empty()
instance.
Store<String> stringStore1 = storeHolder.getStoreInstance('stringStore1');
As you can see, naming the key such that we know that we are accessing Store of type String is very useful.
There are situations where we might want to work with nullable instances. For that case we can call getNullableStoreInstance
which also accepts String key as parameter but returns nullable Store instance. This means that when the Store instance for given key was not found, it returns null
instead of Store.empty()
.
Store<String>? nullableStringStore = storeHolder.getNullableStoreInstance('stringStore1');
If we no longer need the Store instance to be stored in StoreHolder, we can call removeStoreInstance
method that accepts String key as parameter.
storeHolder.removeStoreInstance('stringStore1');
The instance of our stringStore should still exist in place where it was created but it's no longer accessable from StoreHolder. In case we need to see all the keys stored in StoreHolder, we can call getAllStoreInstanceKeys
which returns a list of Strings.
List<String> storeInstanceKeys = storeHolder.getAllStoreInstanceKeys();
This method can be useful when we want to check that the instance exists or no longer exists in StoreHolder. It can also be used to reconstruct the Store instance HashMap.
Run this command:
With Dart:
$ dart pub add data_storeholder
With Flutter:
$ flutter pub add data_storeholder
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get
):
dependencies:
data_storeholder: ^1.0.5
Alternatively, your editor might support dart pub get
or flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:data_storeholder/store.dart';
example/example.dart
import 'package:data_storeholder/store.dart';
void main() {
Store<String> hiStore = Store('Hi!');
print(hiStore.data);
hiStore.addOnDataChangedListener((data) => print(data));
StoreHolder storeHolder = StoreHolder();
storeHolder.addStoreInstance('stringGreetingStore', hiStore);
StoreHolder sameStoreHolder = StoreHolder();
Store<String>? helloStore =
sameStoreHolder.getNullableStoreInstance('stringGreetingStore');
helloStore!.data = 'Hello!';
Store<String> nonNullHelloStore =
sameStoreHolder.getStoreInstance('stringGreetingStore');
print(nonNullHelloStore.data);
if (storeHolder == sameStoreHolder) {
print('These StoreHolders are the same!');
}
if (hiStore == helloStore) {
print('These Stores are the same!');
}
}
Author: Kulishnik22
Source Code: https://github.com/kulishnik22/Store
License: MIT license
1662005340
ffcache(Flutter File Cache) is a file based key value store. It stores cache in iOS/Android app's temporary folder. Cache automatically expires after expiration time. Web platform is also supported (uses idb_shim package).
Most methods are asynchronous. So you should use await from an async function.
void testFFCache() async {
final cache = FFCache();
// initialize. most methods call init() internally if not initialized.
// For web platform calling init() is required.
await cache.init();
// insert 'key':'value' pair
await cache.setString('key', 'value');
// get value for 'key'
final value = await cache.getString('key');
// check if 'key' exists
if (await cache.has('key')) {
// remove cache for 'key'
await cache.remove('key');
}
// cache expires after Duration.
await cache.setStringWithTimeout('key', 'value', Duration(hours: 3));
// remove all cache
await cache.clear();
// setBytes & getBytes
{
final str = 'string data';
List<int> bytes = utf8.encode(str);
await cache.setBytes('bytes', bytes);
final rBytes = await cache.getBytes('bytes');
}
// setJSON & getJSON
{
final jsonData = json.decode('''[{"id":1,"data":"string data","nested":{"id":"hello","flutter":"rocks"}}]''');
await cache.setJSON('json', jsonData);
final rJsonData = await cache.getJSON('json');
}
}
Available from https://pub.dev/documentation/ffcache/latest/ffcache/FFCache-class.html
Cache files are stored in the temporary directory of the app. It uses path_provider's getTemporaryDirectory(). Files in temporary directory can be deleted by the OS at any time. So, FFCache is not for general purpose key value store.
Old cache entries are deleted when FFCache is initialized. By default, cache expires after 1 day.
Run this command:
With Flutter:
$ flutter pub add ffcache
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
ffcache: ^1.1.0
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:ffcache/ffcache.dart';
example/lib/main.dart
import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:ffcache/ffcache.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FFCache Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(title: Text('FFCache Demo')), body: FFCacheTestPage()),
);
}
}
class FFCacheTestPage extends StatefulWidget {
FFCacheTestPage({Key? key}) : super(key: key);
@override
_FFCacheTestPageState createState() => _FFCacheTestPageState();
}
class _FFCacheTestPageState extends State<FFCacheTestPage> {
void testFFCacheSaved() async {
final cache = FFCache(name: 'test');
await cache.init();
if (!await cache.has('key1')) {
await cache.setString('key1', 'test');
}
if (!await cache.has('key2')) {
await cache.setStringWithTimeout('key2', 'test', Duration(seconds: 60));
}
if (!await cache.has('key3')) {
await cache.setStringWithTimeout('key3', 'test', Duration(hours: 10));
}
print(cache.remainingDurationForKey('key1'));
print(cache.remainingDurationForKey('key2'));
print(cache.remainingDurationForKey('key3'));
print(await cache.ageForKey('key1'));
}
void testFFCache() async {
final cache = FFCache(debug: true);
await cache.clear();
// test setString & getString
{
final value = 'value';
await cache.setString('key', value);
final retValue = await cache.getString('key');
assert(retValue == 'value');
}
// getString return null if not found
{
final retValue = await cache.getString('unknownkey');
assert(retValue == null);
}
{
assert(await cache.has('key') == true);
assert(await cache.remove('key') == true);
assert(await cache.has('key') == false);
}
{
final str = 'string data';
List<int> bytes = utf8.encode(str);
await cache.setBytes('bytes', bytes);
final rBytes = await cache.getBytes('bytes');
assert(ListEquality().equals(bytes, rBytes));
}
{
final jsonData = json.decode(
'''[{"id":1,"data":"string data","nested":{"id":"hello","flutter":"rocks"}}]''');
await cache.setJSON('json', jsonData);
final rJsonData = await cache.getJSON('json');
assert(jsonData.toString().compareTo(rJsonData.toString()) == 0);
}
{
final willExpireKey = 'willexpirekey';
await cache.setStringWithTimeout(
willExpireKey, 'value', Duration(milliseconds: 100));
assert(!cache.remainingDurationForKey(willExpireKey).isNegative);
// sleep(Duration(milliseconds: 150)); // doesn't work on web
await Future.delayed(const Duration(milliseconds: 150));
assert(cache.remainingDurationForKey(willExpireKey).isNegative);
assert(await cache.getString(willExpireKey) == null);
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("testFFCache() passed all asserts. Everything went ok."),
backgroundColor: Colors.blue,
));
}
// void test2() async {
// final cache = FFCache(debug: true);
// await cache.init();
// await cache.setString('test1', 'aaa');
// await cache.setString('test2', 'bbb');
// await cache.setString('test3', 'ccc');
// }
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
child: Text("test FFCache"),
onPressed: testFFCache,
),
// RaisedButton(
// child: Text("test 2"),
// onPressed: test2,
// ),
],
),
);
}
}
Author: Mix1009
Source Code: https://github.com/mix1009/ffcache
License: MIT license
1661440380
A session store backend for gorilla/sessions - src using Riak.
Depends on the Riaken riaken-core Riak library.
go get github.com/boj/riakstore
Available on godoc.org.
See http://www.gorillatoolkit.org/pkg/sessions for full documentation on underlying interface.
// Fetch new store.
addrs := []string{"127.0.0.1:8083", "127.0.0.1:8084", "127.0.0.1:8085", "127.0.0.1:8086", "127.0.0.1:8087"}
store := NewRiakStore(addrs, 5, "sessions", []byte("secret-key"))
defer store.Close()
// Get a session.
session, err := store.Get(req, "session-key")
if err != nil {
log.Error(err.Error())
}
// Add a value.
session.Values["foo"] = "bar"
// Save.
if err = sessions.Save(req, rsp); err != nil {
t.Fatalf("Error saving session: %v", err)
}
// Delete session.
session.Options.MaxAge = -1
if err = sessions.Save(req, rsp); err != nil {
t.Fatalf("Error saving session: %v", err)
}
See http://docs.basho.com/riak/latest/ops/advanced/backends/multi/ for how to configure multiple backends and bucket level TTL props.
Additional FAQs on TTL:
Author: Boj
Source Code: https://github.com/boj/riakstore
License: MIT license