08 June 2020

Recent Advances in Google Translate




Advances in machine learning (ML) have driven improvements to automated translation, including the GNMT neural translation model introduced in Translate in 2016, that have enabled great improvements to the quality of translation for over 100 languages. Nevertheless, state-of-the-art systems lag significantly behind human performance in all but the most specific translation tasks. And while the research community has developed techniques that are successful for high-resource languages like Spanish and German, for which there exist copious amounts of training data, performance on low-resource languages, like Yoruba or Malayalam, still leaves much to be desired. Many techniques have demonstrated significant gains for low-resource languages in controlled research settings (e.g., the WMT Evaluation Campaign), however these results on smaller, publicly available datasets may not easily transition to large, web-crawled datasets.

In this post, we share some recent progress we have made in translation quality for supported languages, especially for those that are low-resource, by synthesizing and expanding a variety of recent advances, and demonstrate how they can be applied at scale to noisy, web-mined data. These techniques span improvements to model architecture and training, improved treatment of noise in datasets, increased multilingual transfer learning through M4 modeling, and use of monolingual data. The quality improvements, which averaged +5 BLEU score over all 100+ languages, are visualized below.
BLEU score of Google Translate models since shortly after its inception in 2006. The improvements since the implementation of the new techniques over the last year are highlighted at the end of the animation.
Advances for Both High- and Low-Resource Languages
Hybrid Model Architecture: Four years ago we introduced the RNN-based GNMT model, which yielded large quality improvements and enabled Translate to cover many more languages. Following our work decoupling different aspects of model performance, we have replaced the original GNMT system, instead training models with a transformer encoder and an RNN decoder, implemented in Lingvo (a TensorFlow framework). Transformer models have been demonstrated to be generally more effective at machine translation than RNN models, but our work suggested that most of these quality gains were from the transformer encoder, and that the transformer decoder was not significantly better than the RNN decoder. Since the RNN decoder is much faster at inference time, we applied a variety of optimizations before coupling it with the transformer encoder. The resulting hybrid models are higher-quality, more stable in training, and exhibit lower latency.

Web Crawl:Neural Machine Translation (NMT) models are trained using examples of translated sentences and documents, which are typically collected from the public web. Compared to phrase-based machine translation, NMT has been found to be more sensitive to data quality. As such, we replaced the previous data collection system with a new data miner that focuses more on precision than recall, which allows the collection of higher quality training data from the public web. Additionally, we switched the web crawler from a dictionary-based model to an embedding based model for 14 large language pairs, which increased the number of sentences collected by an average of 29 percent, without loss of precision.

Modelling Data Noise:Data with significant noise is not only redundant but also lowers the quality of models trained on it. In order to address data noise, we used our results on denoising NMT training to assign a score to every training example using preliminary models trained on noisy data and fine-tuned on clean data. We then treat training as a curriculum learning problem — the models start out training on all data, and then gradually train on smaller and cleaner subsets.

Advances That Benefited Low-Resource Languages in Particular
Back-Translation:Widely adopted in state-of-the-art machine translation systems, back-translation is especially helpful for low-resource languages, where parallel data is scarce. This technique augments parallel training data (where each sentence in one language is paired with its translation) with synthetic parallel data, where the sentences in one language are written by a human, but their translations have been generated by a neural translation model. By incorporating back-translation into Google Translate, we can make use of the more abundant monolingual text data for low-resource languages on the web for training our models. This is especially helpful in increasing fluency of model output, which is an area in which low-resource translation models underperform.

M4 Modelling: A technique that has been especially helpful for low-resource languages has been M4, which uses a single, giant model to translate between all languages and English. This allows for transfer learning at a massive scale. As an example, a lower-resource language like Yiddish has the benefit of co-training with a wide array of other related Germanic languages (e.g., German, Dutch, Danish, etc.), as well as almost a hundred other languages that may not share a known linguistic connection, but may provide useful signal to the model.

Judging Translation Quality
A popular metric for automatic quality evaluation of machine translation systems is the BLEU score, which is based on the similarity between a system’s translation and reference translations that were generated by people. With these latest updates, we see an average BLEU gain of +5 points over the previous GNMT models, with the 50 lowest-resource languages seeing an average gain of +7 BLEU. This improvement is comparable to the gain observed four years ago when transitioning to phrase-based NMT.

Although BLEU score is a well-known approximate measure, it is known to have various pitfalls for systems that are already high-quality. For instance, several works have demonstrated how the BLEU score can be biased by translationese effects on the source side or target side, a phenomenon where translated text can sound awkward, containing attributes (like word order) from the source language. For this reason, we performed human side-by-side evaluations on all new models, which confirmed the gains in BLEU.

In addition to general quality improvements, the new models show increased robustness to machine translation hallucination, a phenomenon in which models produce strange “translations” when given nonsense input. This is a common problem for models that have been trained on small amounts of data, and affects many low-resource languages. For example, when given the string of Telugu characters “ష ష ష ష ష ష ష ష ష ష ష ష ష ష ష”, the old model produced the nonsensical output “Shenzhen Shenzhen Shaw International Airport (SSH)”, seemingly trying to make sense of the sounds, whereas the new model correctly learns to transliterate this as “Sh sh sh sh sh sh sh sh sh sh sh sh sh sh sh sh sh”.

Conclusion
Although these are impressive strides forward for a machine, one must remember that, especially for low-resource languages, automatic translation quality is far from perfect. These models still fall prey to typical machine translation errors, including poor performance on particular genres of subject matter (“domains”), conflating different dialects of a language, producing overly literal translations, and poor performance on informal and spoken language.

Nonetheless, with this update, we are proud to provide automatic translations that are relatively coherent, even for the lowest-resource of the 108 supported languages. We are grateful for the research that has enabled this from the active community of machine translation researchers in academia and industry.

Acknowledgements
This effort is built on contributions from Tao Yu, Ali Dabirmoghaddam, Klaus Macherey, Pidong Wang, Ye Tian, Jeff Klingner, Jumpei Takeuchi, Yuichiro Sawai, Hideto Kazawa, Apu Shah, Manisha Jain, Keith Stevens, Fangxiaoyu Feng, Chao Tian, John Richardson, Rajat Tibrewal, Orhan Firat, Mia Chen, Ankur Bapna, Naveen Arivazhagan, Dmitry Lepikhin, Wei Wang, Wolfgang Macherey, Katrin Tomanek, Qin Gao, Mengmeng Niu, and Macduff Hughes.

The economic benefits of climate action | Marcelo Mena

The economic benefits of climate action | Marcelo Mena

Marcelo Mena, the former environment minister of Chile, is on a mission to create a zero-emission economy in his country by 2050. In a conversation about climate action, he discusses how the COVID-19 pandemic is changing Chile's ambitious plan to tackle climate change -- and explains why the green recovery needs to be powered by both political leaders and citizens alike. (This virtual conversation, hosted by TED current affairs curator Whitney Pennington Rodgers and global curator Bruno Giussani, was recorded on May 26, 2020.)

Click the above link to download the TED talk.

HBO Max vs. HBO Now vs. HBO Go: What Are the Differences?


hbo-differences

WarnerMedia has launched the much-hyped HBO Max, promising a large catalog of exclusive and original streaming content. But how is HBO Max different from the HBO Now and HBO Go?

With so many HBO-branded packages, it can get confusing for the average consumer. So, in this article, we look at HBO Max vs. HBO Now vs. HBO Go to help you decide which service to choose.

What Is HBO Now?

hbo now streaming service

HBO Now is HBO’s standalone streaming service for the United States. It is similar to Netflix in that users stream directly from HBO and therefore do not require a third-party site, service, or cable package.

HBO Now costs $14.99/month, excluding tax. Since the service does not form part of a cable package, you are billed monthly and can cancel your subscription at any time without being locked into a longer contract period.

HBO Now includes the full catalog of HBO content, including popular HBO series, but not content from other WarnerMedia properties.

What Is HBO Go?

hbo go streaming website

HBO Go is the streaming app for customers in the United States who have a cable TV package subscription to HBO. Unlike HBO Now, HBO Go is part of a TV package and is not a standalone service. Without a cable account with an HBO subscription, you can’t log into the HBO Go app.

The price of HBO Go varies according to the channel subscription prices for different cable providers.

However, it provides access to the exact same content and catalog as HBO Now.

What Is HBO Max?

hbo max streaming service

HBO Max is also a streaming platform for HBO movies and series. However, rather than only featuring HBO content, it also offers content from across WarnerMedia’s catalog. The platform will also host original content specific to HBO Max called Max Originals.

The service includes all of HBO’s catalog, as well as titles from other WarnerMedia networks and franchises. This includes content from DC, CNN, TNT, TBS, truTV, Cartoon Network, Adult Swim, Crunchyroll, Rooster Teeth, Looney Tunes Cartoons, and select TCM classic films.

An HBO Max subscription costs $14.99/month (excluding tax) if purchased directly from HBOMax.com. However, WarnerMedia states that if you buy it as part of a package or from another provider, prices may vary.

For example, if you purchase HBO Max access via Hulu, YouTube TV, or your cable provider, prices may differ. AT&T and other internet providers also include access to HBO Max as a part of certain packages.

HBO Max Vs. HBO Now Vs. HBO Go: The Main Differences

With so many HBO-branded streaming apps, it’s no wonder that people are confused about which service to use and subscribe to. So what’s the difference between HBO Go, HBO Now, and HBO Max?

HBO Now and HBO Go differ in terms of how you access HBO content: either as a standalone streaming service for the former, or through a cable TV package for the latter.

HBO Max, on the other hand, is essentially the replacement for HBO Now and HBO Go. It offers a central platform through which HBO subscribers can access content, with a bigger catalog of series and movies thanks to the inclusion of WarnerMedia properties. HBO Max also includes Max Originals, which will be exclusive content that can’t be streamed on any other platforms.

While HBO Go and HBO Now still remain functional, this appears to be for the benefit of devices and providers that don’t yet support HBO Max. HBO Max is essentially the future of streaming HBO content thanks to its more centralized login process and larger catalog.

How to Get HBO Max

HBO Max is only available to customers in the United States and select US territories. The streaming platform cannot be accessed from outside the US. But how do you subscribe to the service if you want the expanded catalog on offer?

The process differs slightly depending on whether you already have an HBO subscription or are a new customer.

Existing HBO Subscribers

Existing direct-billed subscribers for HBO Now are automatically upgraded to HBO Max at no extra cost, so long as the update is supported by your device. The subscription plans are the same price when billed directly by HBO, making the transition seamless.

However, customers billed through Apple, Google Play, Samsung, Optimum, and Verizon Fios Internet can also upgrade their HBO Now app to HBO Max without paying extra.

HBO Go users are able to move to HBO Max, but this will depend on cable provider support for the new platform.

According to WarnerMedia, HBO Go users direct-billed through AT&T, AT&T TV, DIRECTV, U-Verse TV, Cox, Hulu, Optimum, Spectrum, Suddenlink, Verizon Fios TV, or select independent providers can also access HBO Max at no extra cost.

If your cable provider supports HBO Max, you will be able to use your cable account details to log into HBO Max. But if you get the error message “Currently Unavailable” when you open HBO Max, this means your provider doesn’t currently support the service.

New HBO Subscribers

If you don’t already subscribe to HBO through one of its older services or a third party, you can get HBO Max by signing up on the HBO Max website. This is the most direct way to access the service.

You can also sign up via the HBO Max app on Android, iOS, or Samsung smart TVs.

Other providers who offer HBO Max access include:

  • Apple TV Channels
  • Hulu
  • YouTube TV

Alternatively, you can sign up for HBO Max via your cable provider.

HBO Max is also available through certain internet providers, including:

  • AT&T
  • Consolidated Communications
  • Liberty
  • Optimum
  • Verizon

You will have to check which packages and plans include HBO Max access as part of their bundled services.

Which HBO Service Should You Subscribe To?

If you’re not currently subscribed to a streaming service for HBO content, HBO Max is the way to go. It’s the same price as HBO Now and offers more content. Of course, you might still use HBO Go if your cable provider doesn’t provide access to HBO Max yet.

However, if you’re looking for an alternative streaming service, there are many others you can choose from. Take a look at our list of the best TV streaming services for more options.

Read the full article: HBO Max vs. HBO Now vs. HBO Go: What Are the Differences?


Read Full Article

The 6 Best Fans for Cooling in 2020


Air conditioning units are one of the most effective ways to stay cool during the summer months. However, a reliable unit can be expensive, while also taking up space in your home. Fans are an affordable alternative. They also have much lower operating costs than their AC counterparts.

Many homes are equipped with ceiling fans to keep entire rooms cool. However, pedestal and desk fans can facilitate personal cooling. Whether you’re after a more effective fan or hoping to add some smart home features, we’re here to help.

These are the best cooling fans you can buy today.

1. Vornado Silver Swan Oscillating Fan

Vornado Silver Swan Oscillating Fan Vornado Silver Swan Oscillating Fan Buy Now On Amazon $149.99

Desktop fans have a distinctive design that hasn’t varied much over the years. However, that’s because the design is effective at helping you stay cool. The Vornado Silver Swan Oscillating Fan is one of the best desktop fans thanks to its pitched metal blades. While there are cheaper fans out there, many use plastic rather than metal blades, reducing their effectiveness and usually increasing the volume, too.

The Silver Swan Oscillating Fan comes with a three-speed manual control to set the level to your preference. The fan has a small footprint, so you can easily keep it on your desk without taking up too much space. The tilt-head is adjustable and can be locked into a fixed position or oscillate. To ease your mind, this fan comes with a five-year hassle-free promise.

2. Dyson Air Multiplier AM06

Dyson Air Multiplier AM06 Dyson Air Multiplier AM06 Buy Now On Amazon $272.00

The Dyson Air Multiplier AM06 doesn’t look like a traditional fan. The circular device doesn’t use blades to create airflow, relying instead on the company’s air multiplier motor to pull air into the unit, before releasing it through the top ring. This has the dual effect of making the fan safer as there are no moving parts, while also creating an uninterrupted stream of airflow.

As you’d expect for a Dyson product, each feature has been engineered to make the AM06 easy to use. The oscillation can be controlled using the included remote, which also allows you to set a sleep timer and adjust the fan’s airflow. The remote is magnetic and can attach to the fan for secure storage as well. You can tilt the Air Multiplier AM06 up and down with little effort as the unit pivots around its center of gravity.

3. Genesis Clip Fan

Genesis Clip Fan Genesis Clip Fan Buy Now On Amazon $12.20

The Genesis Clip Fan is one of the best affordable fans, especially for those working in a home office. As the name suggests, the six-inch fan comes with a clip stand, allowing you to attach the unit to your desk or other furniture. As most fans take up a lot of room, this is ideal for anyone looking to save space.

At this price, you shouldn’t expect the most efficient cooling. However, the Genesis Clip Fan does offer two fans speeds and quiet operation. As the clip is an optional attachment, you can convert the unit into a more stable desktop fan as well. Although this isn’t an oscillating fan, you can still adjust the head up or down to change the direction of airflow.

4. AmazonBasics Dual-Blade Pedestal Fan

AmazonBasics Dual-Blade Pedestal Fan AmazonBasics Dual-Blade Pedestal Fan Buy Now On Amazon $38.99

The AmazonBasics Dual-Blade Pedestal Fan is one of the best fans for cooling an apartment available today. Where desktop fans are designed to keep you cool at close distances, pedestal fans are ideal for cooling entire rooms. This option comes with a remote control, allowing you to adjust the speed, mode, and oscillation as well as set a timer.

Most fans use a single blade, but this AmazonBasics pedestal fan uses a dual-blade setup for more effective cooling, especially across larger spaces. The fan is equipped with three operating modes: Nature, Sleep, and Normal. As with most oscillating fans, the head of the AmazonBasics Dual-Blade Pedestal Fan can be adjusted up or down and can rotate or be locked in a single direction.

5. Dyson Pure Cool TP04

Dyson Pure Cool TP04 Dyson Pure Cool TP04 Buy Now On Amazon $549.99

We noted earlier that fans are often more affordable than air conditioning units. However, that isn’t always the case. The Dyson Pure Cool TP04 is an expensive tower fan, but like many of the company’s products, it comes with a feature-set to justify the price.

Fans circulate air around the room to keep you cool, but this also means they circulate any dirt or pollutants in the air. The Pure Cool TP04 passes the air through a HEPA filter before distributing it so that you can breathe easier. While this filtering is good for your health, the fan tracks the level of pollution in the air and can alert you to significant air quality changes.

The filtering makes the unit one of the best fans for the bedroom. This is especially the case as it has an oscillation range of 350 degrees and a quiet operation. The Pure Cool TP04 can also be controlled through the Dyson Link smartphone app or via voice commands to Alexa and Siri.

6. Honeywell QuietSet Tower Fan

Honeywell QuietSet Tower Fan Honeywell QuietSet Tower Fan Buy Now On Amazon $64.99

The Dyson Pure Cool TP04 is undoubtedly an intriguing device. However, the Honeywell QuietSet Tower Fan is the best affordable tower fan and another excellent option. This fan comes in at just a fraction of the Pure Cool price but doesn’t compromise on cooling effects. It comes equipped with an eight-speed control, ranging from a mild breeze to more powerful airflow.

Tower fans are more suited towards cooling entire rooms and are generally quieter than their desktop alternatives. However, the Honeywell QuietSet Tower Fan reduces the volume even further, keeping you cool but not disturbed. There is a built-in timer that can be configured to turn the fan off after one, two, four, or eight hours. This oscillating fan comes with a remote and on-device touch controls.

The Best Fans for Summer

Fans are one of the most affordable ways to stay cool throughout the warmer months. Some companies, like Dyson, have begun making fans smarter, integrating voice assistants and smartphone controls. Whatever your requirement, you should find a fan to suit your needs here.

That said, you may still decide to run an AC unit to keep your home cool. In that case, be sure you avoid these air conditioning blunders throughout the summer season.

Read the full article: The 6 Best Fans for Cooling in 2020


Read Full Article

10 Productive Ways to Kill Time With Your Smartphone


productive-kill-time

Boredom often strips your mind of all the possible ways you could spend your time. When you’re bored, it’s easy to do nothing. But you usually come out of that slump full of regrets over such a waste of time.

If you find yourself bored with your phone around, there are many productive ways to spend your time. Even if you’re still bored after working through these tasks, you’ll at least have something to show for your effort. And since these are general tips, they’re applicable to both iPhone and Android users.

1. Clear Out Your Email Inbox

Spark email app with seven unread notifications

It’s common to let unimportant emails pile up, unread, in your inbox. The danger of this is that you might miss an important email when it does come in, as it gets lost in a high number of unread messages. You might also find that the stack of unread messages weighs on your subconscious; it’s yet another task you need to get around to sooner or later.

The good news is that it usually only takes five minutes to scan your unread emails and put them where they belong: archive, trash, or spam. You should also take this opportunity to unsubscribe to any newsletters you don’t want to receive anymore. That way, you’re less likely to find yourself buried under junk emails in the future.

2. Organize Your Apps

If you’re someone who likes to try out a lot of new apps, your phone might be cluttered with all the ones you don’t use anymore. When you find yourself with time to spare, review your Home screen and delete any apps you no longer need.

You could also rearrange your iPhone apps to make your favorite ones more accessible. An organized Home screen makes it easier to find apps when you’re looking for them.

3. Check Your Notifications

Notification Center showing Clear All button

Almost every app on your phone begs for your attention through notifications. If you don’t dismiss them, these notifications stack up in the Notification Center, making you less likely to notice the important ones.

Swipe down from the top of the screen to access your Notification Center. Tap on a notification to open the relevant app or swipe it left and tap Clear to dismiss it. Tap and hold the X button and choose Clear All Notifications to dismiss them all at once.

4. Update Your To-Do List

There are a lot of great to-do list apps, but all of them get cluttered if you don’t spend time updating your tasks. Make sure you tick off any items you’ve already completed, change the deadline for ones you need to delay, and delete the jobs you don’t need to do anymore.

Another productive way to spend time on your device is to empty your head of everything you need to do and put it into a to-do list. That way you can’t forget them. Be sure to assign deadlines or reminders for any time-sensitive tasks.

5. Sort Through Your Photos

Photos app on Years view

One of the luxuries of a smartphone is that you’ve always got a camera on you to snap new pictures. The downside is that this can result in a bloated library filled with countless similar photos from when you were too eager with the shutter button.

There’s nothing better to do when you’re bored on your phone than sorting through your photo library. Take a little time to delete pictures you don’t need, edit the ones that need a touch-up, highlight your favorites, and create albums for different memories. We’ve looked at how to organize iPhone photos if you need some tips.

6. Spend Some Time Meditating

Choosing to do nothing can be a very productive way to spend your time, if you choose to do so deliberately. Try downloading one of the best meditation apps for your phone and spend five minutes clearing your mind.

This might not seem useful at first. But the clarity and peace of mind you get from meditating can spur you on to greater productivity throughout the rest of the day. If you keep up the habit, you should find yourself better able to deal with stress throughout your day-to-day life.

7. Write a Grocery List

Grocery List in Reminders app on iPhone

One of the best ways to save money from week to week is by writing a grocery list based on the meals you plan to eat. That way, you won’t need to head to the store for last-minute ingredients and you shouldn’t find yourself throwing out food you didn’t get around to eating.

Use the Notes app to plan out breakfast, lunch, and dinner for each day in the next week. Then write a grocery list with all the ingredients you need for those meals. Your next shopping trip will be a breeze with this preparation behind you.

8. Learn a Language or Study

One of the most productive ways to spend time on your device is by learning a new skill. There are countless language-learning apps that you can download for free. Otherwise, take a look on YouTube, Skillshare, or even wikiHow to teach yourself something new.

You could learn essential skills for work, get started with a new hobby, or begin working toward that second language on your bucket list. Whatever you choose to learn, there are plenty of ways to study it using nothing but your phone and an internet connection.

9. Manage Your Contacts

New Contact page on iPhone

People change their contact details all the time: they move to a new address, change their number, update their email addresses, and even marry into new last names. If you’re bored, open the Contacts app on your device and make sure everyone’s details are up to date.

It’s common to find you’ve got duplicate entries for the same people or multiple different phone numbers in a single contact card. You’re also likely to find one-time contacts that you don’t need anymore, such as taxi drivers or hotels.

10. Write a Diary or Journal Entry

Keeping a diary or a journal is good for your mental health and a fantastic way to organize your thoughts. It doesn’t matter whether you write a five-page essay about your day or a five-word partial sentence capturing half a thought in your head. Spending some effort to write is always a useful way to spend time.

You can keep a digital diary or journal in the default Notes app or download a dedicated app for this purpose instead. There are plenty of journaling apps to choose from, and many of them tag your posts with locations, activities, and even music.

There Are Unproductive Ways to Your Spend Time, Too

Each of the tasks above offers a useful and productive way to spend time on your iPhone or Android phone, but they might not stop you from feeling bored. Sometimes when you’re bored, being productive is the exact opposite of what you want.

If that’s the case, there are plenty of mindless activities you can do on your device as well. Check out this list of fun activities to do online. Most of them aren’t productive, but all of them are available on your phone, and they might offer a fun way to pass the time.

Read the full article: 10 Productive Ways to Kill Time With Your Smartphone


Read Full Article

Intraday Trading Calls for 9-June-2020

Intraday Trading Calls for 9-June-2020

Please click on the following link to view full post.

https://marketctl.blogspot.com/2020/06/intraday-trading-calls-for-9-june-2020.html

Via https://marketctl.blogspot.com/

Challenger bank Bnext revamps rewards for purchases in partner stores


Spanish startup Bnext is revamping its cashback program so that you can buy from partner stores directly from the Bnext app and get some money back. The company has partnered with Button and the feature is available as an open beta.

Traditional cashback portals are a bit clunky. When you find an offer that gives you 2% of your money back, you click on the offer, get redirected to the partner site and hope that your purchase will be registered. A bit later, you get some money back on the cashback website, which you need to cash out to your bank account.

If you’re using Bnext as your bank account, you’ll be able to access rewards directly from your banking app. In addition to that, you don’t get redirected to another site as you purchase goods directly from the Bnext app.

There are multiple levels. If you’re making your first purchase through the feature, you get 1% in savings on average. If you’ve made more than three purchases over the past 30 days, you get 3% in savings on average. In order to reach level 3, you need a premium Bnext subscription. With that level, you get 5% in savings on average.

Partners include AliExpress, Booking.com, eDreams, Europcar, Nike, Just Eat and more. Eventually, the startup wants to let you earn rewards from in-store purchases as well. Bnext is creating a new revenue stream with this feature as the startup will keep a share of the revenue from each transaction.

Bnext provides current accounts and payment cards. You can receive notifications for each transaction with your card, and temporarily lock and unlock your card. You don’t pay any foreign transaction fee as long as you spend less than €2,000 per month with a standard account.

The company has also put together a marketplace of fintech products. You can earn interest by lending money to small companies on October, get a loan, an insurance product and more.

Earlier this year, the startup expanded to Mexico. The company plans to roll out rewards in Mexico soon. Bnext has managed to attract a bit less than 400,000 users.


Read Full Article

How to Use Google Sheets with D3.js and Google Visualization


The D3.js visualization library can be used for creating beautiful graphs and visualizations using data from external sources including CSV files and JSON data.

To give you an example, this D3.js animation inside the Google Sheets associated with the COVID-19 tracker project visualizes the growth of Coronavirus cases in India over time. It uses the Google Visualization API, D3.js and the very-awesome Bar Chart Race component built by Mike Bostock, the creator of D3.js.

Google Sheets and D3.js

This guide explains how you can use data in your Google Spreadsheets to create charts with D3.js using the Visualization API. The data is fetched in real-time so if the data in your Google Sheets is updated, it is reflected in the graph as well.

D3.js Chart with Google Sheets

Step 1: Make the Google Sheets public

Make your Google Spreadsheet public - you can either share the sheet with “anyone who has the link can view” access or make it public so even search engines that find your sheet that has the Charts data.

We are using this Google Sheet for this tutorial.

Step 2: Load the Libraries in HTML

Load the D3.js (v5) and the Google charts library in your index.html file. The JavaScript for rendering the D3 chart is written in the index.js file.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://d3js.org/d3.v5.min.js"></script>
  </head>

  <body>
    <svg></svg>
  </body>
  <script src="./index.js"></script>
</html>

Step 3: Initialize the Google Visualization API

Here specify the URL of your publish Google Spreadsheet (the gid should point to the sheet that has the data). The Google Visualization API Query Language (reference) lets you use SQL like syntax to specify columns that should be used for fetching data from the Google sheet. You can also use offset, where and limit clauses to limit the data that is returned by Google Sheets.

google.charts.load('current');
google.charts.setOnLoadCallback(init);

function init() {
  var url =
    'https://docs.google.com/spreadsheets/d/1YpiTo7Fc3QvBdbuReCIcwtg7lnmZupQAH57phrDLotI/edit#gid=0';
  var query = new google.visualization.Query(url);
  query.setQuery('select A, B');
  query.send(processSheetsData);
}

Step 4: Prepare the Data for D3.js

After the spreadsheet data is available, manipulate the response in an Array of Objects that can be read by d3.js. Google Sheets returns numerical data as String so we can either use parseInt or the Unary (+) operator to convert the String to Integer.

function processSheetsData(response) {
  var array = [];
  var data = response.getDataTable();
  var columns = data.getNumberOfColumns();
  var rows = data.getNumberOfRows();
  for (var r = 0; r < rows; r++) {
    var row = [];
    for (var c = 0; c < columns; c++) {
      row.push(data.getFormattedValue(r, c));
    }
    array.push({
      name: row[0],
      value: +row[1],
    });
  }
  renderData(array);
}

Step 5: Render the D3.js chart

Next, we create a Bar Chart in D3.js using the data from Google Sheets. You may follow this tutorial on @ObservableHQ to understand how to make bar charts inside D3.js. The chart is rendered in SVG.

function renderData(data) {
  const margin = { top: 30, right: 0, bottom: 30, left: 50 };
  const color = 'steelblue';
  const height = 400;
  const width = 600;
  const yAxis = (g) =>
    g
      .attr('transform', `translate(${margin.left},0)`)
      .call(d3.axisLeft(y).ticks(null, data.format))
      .call((g) => g.select('.domain').remove())
      .call((g) =>
        g
          .append('text')
          .attr('x', -margin.left)
          .attr('y', 10)
          .attr('fill', 'currentColor')
          .attr('text-anchor', 'start')
          .text(data.y)
      );

  const xAxis = (g) =>
    g.attr('transform', `translate(0,${height - margin.bottom})`).call(
      d3
        .axisBottom(x)
        .tickFormat((i) => data[i].name)
        .tickSizeOuter(0)
    );
  const y = d3
    .scaleLinear()
    .domain([0, d3.max(data, (d) => d.value)])
    .nice()
    .range([height - margin.bottom, margin.top]);

  const x = d3
    .scaleBand()
    .domain(d3.range(data.length))
    .range([margin.left, width - margin.right])
    .padding(0.1);

  const svg = d3
    .select('svg')
    .attr('width', width)
    .attr('height', height)
    .attr('fill', color);

  svg
    .selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('x', (d, i) => x(i))
    .attr('y', (d) => y(d.value))
    .attr('height', (d) => y(0) - y(d.value))
    .attr('width', x.bandwidth());

  svg.append('g').call(xAxis);

  svg.append('g').call(yAxis);
}

How to Use Images in Gatsby


This guide explains how you can use the gatsby-image plugin with GraphQL queries to display optimized images inside your Gatsby pages and React components. The images are lazy-loaded with blurred SVG background, the large images are resized automatically and the meta data is stripped from images.

<Image src="sunset.png" alt="Sunset" />

Gatsby Images

The gatsby-image plugin generates multiple versions of an image for different display/device scenarios and these are served inside the <picture> element. Small images are embedded inline and served as base64 while SVG images are not processed by the plugin.

Here’s how the image is served inside the HTML:

<div class="gatsby-image-wrapper" style="position: relative; overflow: hidden;">
  <picture
    ><source
      srcset="
        /static/images/6d161/175833.png 150w,
        /static/images/630fb/175833.png 300w,
        /static/images/2a4de/175833.png 600w,
        /static/images/40a00/175833.png 647w
      "
      sizes="(max-width: 600px) 100vw, 600px" />
    <img
      sizes="(max-width: 600px) 100vw, 600px"
      srcset="
        /static/images/6d161/175833.png 150w,
        /static/images/630fb/175833.png 300w,
        /static/images/2a4de/175833.png 600w,
        /static/images/40a00/175833.png 647w
      "
      src="/static/images/2a4de/175833.png"
      alt="Upload files from Google Drive"
      loading="lazy"
      style="position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; object-fit: cover; object-position: center center; opacity: 1; transition: opacity 500ms ease 0s;"
  /></picture>
</div>

Step 1: Create the Images Folder

Open the src folder in your Gatsby directory and create a subfolder called images. All images that wish to serve via Gatsby images plugin should reside in this folder.

Step 3: Install the Gatsby Image plugin

npm install --save gatsby-transformer-sharp gatsby-plugin-sharp gatsby-source-filesystem gatsby-image

Step 3: Update the Gatsby Configuration

Update your gatsby-config.js file to include the image plugins and for reading the image files in your images folder.

const path = require(`path`);

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: path.join(__dirname, `src`, `images`),
      },
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
  ],
};

Step 4: Create the Image Component

Go to the src/components folder and create an Image.js file. Here the maximum width of the generate image file is set at 600 pixels but you can modify it to suite your Gatsby site’s layout.

import React, { useMemo } from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import Img from 'gatsby-image';
import PropTypes from 'prop-types';

const Image = ({ src, ...rest }) => {
  const data = useStaticQuery(graphql`
    query {
      images: allFile(
        filter: { internal: { mediaType: { regex: "/image/" } } }
      ) {
        edges {
          node {
            relativePath
            extension
            publicURL
            childImageSharp {
              fluid(maxWidth: 600) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `);

  const match = useMemo(
    () => data.images.edges.find(({ node }) => src === node.relativePath),
    [data, src]
  );

  if (!match) return null;

  const { node: { childImageSharp, publicURL, extension } = {} } = match;

  if (extension === 'svg' || !childImageSharp) {
    return <img src={publicURL} {...rest} />;
  }

  return <Img fluid={childImageSharp.fluid} {...rest} />;
};

Image.propTypes = {
  src: PropTypes.string.isRequired,
  alt: PropTypes.string,
};

export default Image;

Gatsby Image GraphQL Query

The GraphQL query filters all files that have mimeType of images and then compares the relativePath of the image with the fileName passed in the src props.

If the file is found, it looks at the extension of the file. SVG images are served without optimization while all other image formats are served compressed and optimized.

Step 5. Embed Images in Gatsby

Now copy the image that you wish to use in your React component / Gatsby page in the images/ folder. Let’s say the name of the file is sunset.png. Include the image in your component using the new Image tag.

import React from 'react';
import Image from 'src/components/Image';

const Sunset = () => {
  return (
    <>
      <p>Sunset Image</p>
      <Image
        src="sunset.png"
        className="mx-auto shadow-xl"
        alt="Sunset Image"
        style={{
          border: '10px solid green',
        }}
      />
    </>
  );
};

export default Sunset;

You can include custom CSS styles, classes, alt tag and all other attributes that are available with the HTML <img> tag.