How to Create a Sticky Image Effect with Three.js

Original Source: http://feedproxy.google.com/~r/tympanus/~3/FDQVPCkh4Lo/

If you recently browsed Awwwards or FWA you might have stumbled upon Ultranoir’s website. An all-round beautifully crafted website, with some amazing WebGL effects. One of which is a sticky effect for images in their project showcase. This tutorial is going to show how to recreate this special effect.

The same kind of effect can be seen on the amazing website of MakeReign.

Understanding the effect

When playing with the effect a couple of times we can make a very simple observation about the “stick”.

In either direction of the effect, the center always reaches its destination first, and the corners last. They go at the same speed, but start at different times.

With this simple observation we can extrapolate some of the things we need to do:

Differentiate between the unsticky part of the image which is going to move normally and the sticky part of the image which is going to start with an offset. In this case, the corners are sticky and the center is unsticky.
Sync the movements

Move the unsticky part to the destination while not moving the sticky part.
When the unsticky part reaches its destination, start moving the sticky part

Getting started

For this recreation we’ll be using three.js, and Popmotion’s Springs. But you can implement the same concepts using other libraries.

We’ll define a plane geometry with its height as the view height, and its width as 1.5 of the view width.

const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 10000);
const fovInRadians = (camera.fov * Math.PI) / 180;
// Camera aspect ratio is 1. The view width and height are equal.
const viewSize = Math.abs(camera.position.z * Math.tan(fovInRadians / 2) * 2);
const geometry = new THREE.PlaneBufferGeometry(viewSize *1.5,viewSize,60,60)

Then we’ll define a shader material with a few uniforms we are going to use later on:

u_progress Elapsed progress of the complete effect.
u_direction Direction to which u_progress is moving.
u_offset Largest z displacement

const material = new THREE.ShaderMaterial({
uniforms: {
// Progress of the effect
u_progress: { type: “f”, value: 0 },
// In which direction is the effect going
u_direction: { type: “f”, value: 1 },
u_waveIntensity: { type: “f”, value: 0 }
},
vertexShader: vertex,
fragmentShader: fragment,
side: THREE.DoubleSide
});

We are going to focus on the vertex shader since the effect mostly happens in there. If you have an interest in learning about the things that happen in the fragment shader, check out the GitHub repo.

Into the stick

To find which parts are going to be sticky we are going to use a normalized distance from the center. Lower values mean less stickiness, and higher values mean more sticky. Since the corners are the farthest away from the center, they end up being most sticky.

Since our effect is happening in both directions, we are going to have it stick both ways. We have two separate variables:

One that will stick to the front. Used when the effect is moving away from the screen.
And a second one that will stick to the back. Used when the effect is moving towards the viewer.

uniform float u_progress;
uniform float u_direction;
uniform float u_offset;
uniform float u_time;
void main(){
vec3 pos = position.xyz;
float distance = length(uv.xy – 0.5 );
float maxDistance = length(vec2(0.5,0.5));
float normalizedDistance = distance/sizeDist;
// Stick to the front
float stickOutEffect = normalizedDistance ;
// Stick to the back
float stickInEffect = -normalizedDistance ;
float stickEffect = mix(stickOutEffect,stickInEffect, u_direction);
pos.z += stickEffect * u_offset;
gl_Position =
projectionMatrix *
modelViewMatrix *
vec4(pos, 1.0);
}

Depending on the direction, we are going to determine which parts are not going to move as much. Until we want them to stop being sticky and move normally.

The Animation

For the animation we have a few options to choose from:

Tween and timelines: Definitely the easiest option. But we would have to reverse the animation if it ever gets interrupted which would look awkward.
Springs and vertex-magic: A little bit more convoluted. But springs are made so they feel more fluid when interrupted or have their direction changed.

In our demo we are going to use Popmotion’s Springs. But tweens are also a valid option and ultranoir’s website actually uses them.

Note: When the progress is either 0 or 1, the direction will be instant since it doesn’t need to transform.

function onMouseDown(){

const directionSpring = spring({
from: this.progress === 0 ? 0 : this.direction,
to: 0,
mass: 1,
stiffness: 800,
damping: 2000
});
const progressSpring = spring({
from: this.progress,
to: 1,
mass: 5,
stiffness: 350,
damping: 500
});
parallel(directionSpring, progressSpring).start((values)=>{
// update uniforms
})

}

function onMouseUp(){

const directionSpring = spring({
from: this.progress === 1 ? 1 : this.direction,
to: 1,
mass: 1,
stiffness: 800,
damping: 2000
});
const progressSpring = spring({
from: this.progress,
to: 0,
mass: 4,
stiffness: 400,
damping: 70,
restDelta: 0.0001
});
parallel(directionSpring, progressSpring).start((values)=>{
// update uniforms
})

}

And we are going to sequence the movements by moving through a wave using u_progress.

This wave is going to start at 0, reach 1 in the middle, and come back down to 0 in the end. Making it so the stick grows in the beginning and decreases in the end.

void main(){

float waveIn = u_progress*(1. / stick);
float waveOut = -( u_progress – 1.) * (1./(1.-stick) );
float stickProgress = min(waveIn, waveOut);
pos.z += stickEffect * u_offset * stickProgress;
gl_Position =
projectionMatrix *
modelViewMatrix *
vec4(pos, 1.0);
}

Now, the last step is to move the plane back or forward as the stick is growing.

Since the stick grow starts in different values depending on the direction, we’ll also move and start the plane offset depending on the direction.

void main(){

float offsetIn = clamp(waveIn,0.,1.);
// Invert waveOut to get the slope moving upwards to the right and move 1 the left
float offsetOut = clamp(1.-waveOut,0.,1.);
float offsetProgress = mix(offsetIn,offsetOut,u_direction);
pos.z += stickEffect * u_offset * stickProgress – u_offset * offsetProgress;
gl_Position =
projectionMatrix *
modelViewMatrix *
vec4(pos, 1.0);
}

And here is the final result:


Conclusion

Simple effects like this one can make our experience look and feel great. But they only become amazing when complemented with other amazing details and effects. In this tutorial we’ve covered the core of the effect seen on ultranoir’s website, and we hope that it gave you some insight on the workings of such an animation. If you’d like to dive deeper into the complete demo, please feel free to explore the code.

We hope you enjoyed this tutorial, feel free to share your thoughts and questions in the comments!

How to Create a Sticky Image Effect with Three.js was written by Daniel Velasquez and published on Codrops.

90% Off: Get the Essential Digital Photography Master Class Bundle for Only $19

Original Source: http://feedproxy.google.com/~r/Designrfix/~3/-tz6LxtX2vg/90-off-get-the-essential-digital-photography-master-class-bundle-for-only-19

The use of digital cameras have become more and more common since the 1990s. Even smartphone cameras take decent quality photos. As such, it is easier now more than ever to get started with photography. If you want to take better photos, then the Essential Digital Photography Master Class Bundle can be of great hep […]

The post 90% Off: Get the Essential Digital Photography Master Class Bundle for Only $19 appeared first on designrfix.com.

Understanding Subresource Integrity

Original Source: https://www.smashingmagazine.com/2019/04/understanding-subresource-integrity/

Understanding Subresource Integrity

Understanding Subresource Integrity

Drew McLellan

2019-04-09T12:30:59+02:00
2019-04-09T15:15:05+00:00

If you’ve ever used a CDN-hosted version of a JavaScript library, you may have noticed a strange looking integrity attribute on the script tag. This attribute contains seemingly endless alphanumeric junk that you may be tempted to strip out in the quest for cleaner code.

All that junk is actually a really useful security feature called Subresource Integrity (SRI) that can help to defend your site against certain types of hacks and compromises. In this article, we’ll take a look at what SRI is, how it can help protect you, and how you can start using it in your own projects, not just for files hosted on CDNs.

A Bit Of History

Way back in the days when JavaScript was very much the poorer cousin to HTML and CSS, we didn’t need to think too much about how our scripts could be used as an attack vector for our websites. Most sites were all hosted on a single physical server somewhere on our own hosting infrastructure, and it was the server we thought about defending when it came to security best practices.

As browsers became more capable and net connections got fatter, we started to use more and more JavaScript, and eventually, reusable JavaScript libraries began to spring up. In those early days, libraries like script.aculo.us, Prototype and eventually jQuery began to gain adoption amongst developers looking to add more interactivity into their pages.

With these added libraries and subsequent plugins came added page weight, and before long we were starting to think seriously about front-end performance. Resources like Content Delivery Networks (CDNs) that had previously been the reserve of giant corporations were becoming commonplace for everyday folk building snappy websites.

Along the way, some bright spark noticed that sites were all requesting their own copies of common libraries — things like the latest jQuery — and if there was a common CDN version of those libraries that could be used by every site, then the user wouldn’t need to keep downloading the same file. They’d take the hit for the first site to use the file, but then it would sit in their local browser cache and downloads could be skipped for each subsequent site. Genius!

This is why you’ll see CDN links for your favorite libraries using URLs like jsdelivr.com — they’re making use of a common CDN to host the files so that their users see the performance benefits.

What Could Go Wrong?

This remains a good, practical way to work, but it does introduce a potential vector for attack. Let’s imagine that it’s 2012 and everyone is using the brand new jQuery 1.8. Back with the traditional way of doing things, everyone would have their own jQuery 1.8 file hosted as part of their own website on their own server.

If you were some kind of evil actor — like some sort of jQuery-based Hamburglar — and had figured out a sneaky way to hack the library for your own evil gains, you’d have to target every website individually and compromise their servers to have any impact. That’s a lot of effort.

But that’s not how things are now, as everyone is using jQuery loaded from a common CDN. And when I say everyone, I don’t mean hundreds of web pages. I mean millions of web pages. Suddenly that one file has become a very attractive target for our shady hacker. If they can compromise that one file, they can very quickly have code running in millions of web pages across the globe.

It doesn’t matter what that code is. It could be a prank to deface pages, it could be code to steal your passwords, it could be code to mine cryptocurrency, or it could be sneaky trackers to follow you around the web and make a marketing profile. The important thing is that the innocent file that the developer added to a page has been changed and you now have some evil JavaScript running as part of your site. That’s a big problem.

Enter Subresource Integrity

Rather than rolling back the clocks and abandoning a useful way to use code, SRI is a solution that adds a simple level of security on top. What SRI and the integrity attribute does is make sure that the file you linked into a page never changes. And if it does change, then the browser will reject it.

Checking that code hasn’t changed is a very old problem in computer science and thankfully it has some very well established solutions. SRI does a good job of adopting the simplest — file hashing.

File hashing is the process of taking a file and running it through an algorithm that reduces it to a short string representation, known as a hash or checksum. Without getting into the weeds, the process is either repeatable or reversible, so much that if you were to give someone else a file along with the hash they’d be able to run the same algorithm to check that the two match. If the file changes or the hash changes, then there’s no longer a match and you know something is wrong and should distrust the file.

When using SRI, your webpage holds the hash and the server (CDN or anywhere) holds the file. The browser downloads the file, then quickly computes to make sure that it is a match with the hash in the integrity attribute. If it matches the file is used, and if not it is blocked.

Trying It Out

If I go to getbootstrap.com today to get a CDN link to a version of Bootstrap, I’m given a tag that looks like this:

<script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js” integrity=”sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM” crossorigin=”anonymous”></script>

You can see that the src attribute is as we’re used to, and the integrity attribute holds what we now know to be a hash.

The hash is actually in two parts. The first is a prefix to declare which hashing algorithm to use. In this case, it’s sha384. This is followed by a dash and then the hash itself, encoded with base64.

You may be familiar with base64 as a way of encoding inline files like images into pages. It’s not a cryptographic process — it’s just a fast and convenient way to encode potentially messy data in a way that translates neatly to ASCII. This is why it’s used a lot on the web.

On seeing this, the browser will download bootstrap.min.js. Before executing it, it will base64 decode the hash and then use the sha384 hashing algorithm to confirm that the hash matches the file it’s just downloaded. If it matches, the file is executed.

I can test this out by putting that tag in a page, and then flipping to the Network tab in my browser tools to see that the file has been loaded.

Network tab

(Large preview)

I can see that bootstrap.min.js (and also the jQuery file it needs) have loaded successfully.

Let’s see what would happen if I update the hash to be something I know to be incorrect.

<script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js” integrity=”sha384-SmashingMagazineIsCoolForCats” crossorigin=”anonymous”></script>

hash

(Large preview)

As you can see, the hash that’s specified in my page no longer matches the file, so the file gets blocked.

Using SRI In Your Own Projects

Having this capability for libraries on a CDN is great, and if you see the option to use an embedded file with an integrity attribute then you should definitely favor that option. But it’s not limited to big projects on CDNs, you can use this yourself for your own sites.

It’s not at all far fetched to imagine a scenario where a hacker manages to get access to just a few files on your site. I think most of us have see a client, colleague or friend who has at some point had a WordPress site compromised with a load of nasty junk that they didn’t even realise was there.

SRI can protect you from this too. If you generate integrity hashes for your own files, then you can have your site reject any changes just as it would for a remotely hosted file.

Generating Hashes

You can, as you’d expect, run some commands at your computer’s terminal to generate a hash for a file. This example of how to do so comes from the MDN Subresource Integrity page:

cat FILENAME.js | openssl dgst -sha384 -binary | openssl base64 -A

That’s getting the content of FILENAME.js and passing it as input to openssl to create a digest using sha384, which is then passed as input into another openssl command to base64 encode the result. Not only is that complicated and obscure, but it’s also not the sort of thing you want to be doing by hand every time your JavaScript file changes.

More usefully, you’ll want to integrate this somehow into your site’s build process, and as you’d imagine, there are plenty of ready-made options there. The exact implementation is going to vary wildly based on your project, but here are some building blocks.

If you use Gulp to build your sites, there’s gulp-sri which will output a JSON file with a list of your files and their hashes. You can then make use of this in your site. For example, for a dynamically rendered site, you might create a template plugin to read that file and add the hashes to your templates where needed.

If you’re still with Gulp but have a static site (or a statically generated site) you might use gulp-sri-hash which will actually run through your HTML pages and modify the pages to add hashes where needed, which is very handy.

If you’re using Webpack, there’s webpage-subresource-integrity which in true Webpack style is more complex than any human might expect it to be, but does appear to work.

For those using the Handlebars templating engine, there appear to be options available to you, and if your build process is just basic JavaScript, there are simple solutions there too.

If you’re using a CMS like WordPress, I found a plugin that appears to make it easy, although I’ve not tried it myself. Googling for your own platform of choice with SRI or Sub Resource Integrity will likely point you in the right direction.

You essentially want to hook your hashing in after your JavaScript files have been minified and then make that hash available in some way to whatever part of your system outputs the <script> tags. One of the wonders of the web platform is that it’s so technically diverse, but that sadly leaves me unable to give you good implementation instructions!

Other Things To Note

In this article, I’ve talked a lot about JavaScript files because that’s really where it makes the most sense to defend against hacking attacks. SRI also works with CSS, and so you can use it in exactly the same way there. The risk for malicious CSS is much lower, but the potential to deface a site still exists and who knows what browser bugs could also lead to CSS inadvertently exposing your site to a hacker. So it’s work using SRI there too.

Another interesting thing you can do is use a Content Security Policy to specify that any script (or styles) on your page must use SRI, and of course that SRI must validate.

Content-Security-Policy: require-sri-for script;

This is a way to ensure that SRI is always used, which could be useful on sites worked on by multiple team members who may or may not be fully up to speed with how to do things. Again, a good place to read more about this is the always-great MDN docs for Subresource Integrity.

The last thing that’s worth talking about is browser support for SRI. Support in modern browsers is broad, with the main exception being Internet Explorer. Due to the backwards-compatible way the specification has been implemented, however, it’s safe to use immediately. Browsers that understand the integrity attribute will use the hash and check integrity, and older browsers will just carry on as they always have and keep working. Of course, you’ll not get the added protection in those older browsers, but you will in the browsers that do offer support.

Conclusion

We’ve seen not only what those weird hashes in the integrity attributes do, but how we can use them to defend against certain types of attacks on our website. Of course, there’s no one silver bullet that will defend our sites against every type of exploit, but Subresource Integrity is a really useful tool in the chain.

Exploiting a security flaw is often about getting multiple small pieces to line up. If A is in place, and you can make B happen, then a bug in C makes D possible. Browser features like SRI give us a good way to tie things down just a little bit more and potentially break that chain and prevent a hacker from getting what they want. What’s more, if you can integrate it into your build process or CMS, it’s something you should be able to set up once and then forget about and it won’t cause you day to day inconvenience.

As such, I’d really recommend taking a serious look at Subresource Integrity and implementing it on your sites if you can.

Smashing Editorial
(yk, il)

Relive your Snake addiction with Google's April Fool's gag

Original Source: http://feedproxy.google.com/~r/CreativeBloq/~3/0VBAOZSEVGo/relive-your-snake-addiction-with-googles-april-fools-gag

For readers of a certain age, the game Snake will bring back hazy memories of squinting at the screen of a Nokia 3210 as you furiously try to beat your best mate's high score. To give people the chance to relive the classic game, Google has added a version of Snake to Google Maps today as an April Fool's Day treat.

Rolling out worldwide today across Android and iOS, Snake on Google Maps sees players control buses and trains instead of a slithering serpent. The aim of the game is still the same though: players have to gobble up objects, in this case tourists and famous landmarks, while making sure they don't overlap themselves or run off the map. After a few goes, you'll realise (or remember) that this isn't as easy as it sounds.

Players get to choose from a variety of locations from Google Maps, including Cairo, London, San Francisco, São Paulo, Sydney and Tokyo. Each map and its associated landmarks are picked out in colourful pixel art, ensuring that this version of Snake brings out all of your '90s nostalgia.

According to Google Maps product manager Omar Abdelaziz, Snake on Google Maps will be available in the app for "about a week". However, if you just can't get enough of the game, you'll be pleased to hear that it has a standalone site, so you will be able to keep playing "long after April Fools is over."

As far as pranks go, Google is playing it very safe this year. That's if you can even call Snakes on Google Maps a prank. However, given that your social media feeds have probably been inundated with joke stories this morning, we appreciate that the search engine giant is saving you a bit of hassle by being upfront with its mild tomfoolery.

Another reason that Google is treading carefully around April Fool's Day could be related to a 2016 prank that backfired. That year Google launched the 'Mic Drop', a feature which temporarily replaced the 'Send and Archive' button. By clicking 'Mic Drop', users sent everyone in the conversation a GIF of a Minion dropping a microphone, as well as stopping further replies from appearing in your inbox.

The Mic Drop prank caused headaches for companies, with at least one freelancer losing work as a result of it burying their replies. Hilarious. In response to the fallout, Google issued an apology and deactivated the feature, so we can't really blame it for not taking a risk this April Fool's Day.

Related articles:

Google's new gaming logo is cleverly off-brandThe Period Game is Dream Phone with ovaries5 ads that tried to be cool, but failed

SitePoint Premium New Releases: Node, Android, React Native & More

Original Source: https://www.sitepoint.com/sitepoint-premium-new-releases-node-android-react-native-more/

We’re working hard to keep you on the cutting edge of your field with SitePoint Premium. We’ve got plenty of new books and mini-books to check out in the library — let us introduce you to them.

Mastering the Faster Web with PHP, MySQL, JavaScript

Make data-driven web apps run faster with advanced PHP, SQL and JS techniques. Ensure seamless implementation of a JS-, HTML 5- and CSS-based front end and PHP-based back end. Learn about problem identification, best strategies, and UI design patterns as well to build a clean, fast web app.

Read Mastering The Faster Web with PHP, MySQL, JavaScript.

Learning Java by Building Android Games Second Edition

Develop engaging games for the Android platform with Java. Learn Java, Android, and object-oriented programming from scratch. Build games including Sub Hunter, Retro Pong, and Bullet Hell. Create and design your own games, such as an open-world platform game.

Read Learning Java by Building Android Games Second Edition.

Internet of Things Programming Projects

This book is a practical, project-based guide to help you build and control your IoT projects. Leverage the full potential of IoT with the combination of Raspberry Pi 3 and Python. Build complex, Python-based apps with IoT. Work on various IoT projects and understand the basics of electronics.

Read Internet of Things Programming Projects.

Real-Time 3D Graphics with WebGL 2 – Second Edition

Create interactive, visually stunning, high-performance 3D applications for the web with JavaScript and WebGL 2. This complete course on 3D computer graphics covers rendering, 3D math, lighting, cameras, and more, unlocking a variety of new and advanced WebGL 2 features.

Read Real-Time 3D Graphics with WebGL 2 – Second Edition.

Android Programming for Beginners – Second Edition

Through this first-principles introduction to Java, via Android, you’ll learn all the Java and Android skills you need to start making powerful mobile apps with practical and actionable steps, and how to publish apps to the Google Play marketplace.

Read Android Programming for Beginners Second Edition.

Mastering React Native

Get up to speed with all the React Native building blocks necessary for creating expert, cutting-edge apps. Learn how to apply Flexbox, build rich animations, integrate third-party libraries, develop customized components, combine React Native with Redux, Redux middleware, a remote API, and more.

Read Mastering React Native.

Vue.js: Tools & Skills

In this book, we’ll examine some of the most popular Vue,js tools, and look at some related skills that will help you on your journey to becoming an expert Vue developer.

Read Vue.js: Tools & Skills.

CSS Animation 101

We’re going to learn about CSS transitions and animations. By the end of the book, you’ll have a good understanding of CSS animations as well as the tools to create and experiment with our own.

Read CSS Animation 101.

How to Build a Game with Vue.js

In this tutorial, we’ll explore one of the less obvious uses for Vue: game development,. We’ll build an electronic variant of the popular Match Pairs game.

Read How to Build a Game with Vue.js.

Node.js Web Development Fourth Edition

Create real-time apps with Node.js, Docker, MySQL, MongoDB, and Socket.IO. Learn about live deployment, including HTTPS and hardened security, the latest JS features and ES modules, and walk through different stages of developing robust apps using Node.js 10.

Read Node.js Web Development Fourth Edition.

And More to Come…

We’re releasing new content on SitePoint Premium almost every day, so we’ll be back next week with the latest updates. And don’t forget: if you haven’t checked out our offering yet, take our 7 day free trial for a spin.

The post SitePoint Premium New Releases: Node, Android, React Native & More appeared first on SitePoint.

How We Used WebAssembly To Speed Up Our Web App By 20X (Case Study)

Original Source: https://www.smashingmagazine.com/2019/04/webassembly-speed-web-app/

How We Used WebAssembly To Speed Up Our Web App By 20X (Case Study)

How We Used WebAssembly To Speed Up Our Web App By 20X (Case Study)

Robert Aboukhalil

2019-04-05T12:00:29+02:00
2019-04-05T19:06:22+00:00

If you haven’t heard, here’s the TL;DR: WebAssembly is a new language that runs in the browser alongside JavaScript. Yes, that’s right. JavaScript is no longer the only language that runs in the browser!

But beyond just being “not JavaScript”, its distinguishing factor is that you can compile code from languages such as C/C++/Rust (and more!) to WebAssembly and run them in the browser. Because WebAssembly is statically typed, uses a linear memory, and is stored in a compact binary format, it is also very fast, and could eventually allow us to run code at “near-native” speeds, i.e. at speeds close to what you’d get by running the binary on the command line. The ability to leverage existing tools and libraries for use in the browser and the associated potential for speedup, are two reasons that make WebAssembly so compelling for the web.

So far, WebAssembly has been used for all sorts of applications, ranging from gaming (e.g. Doom 3), to porting desktop applications to the web (e.g. Autocad and Figma). It is even used outside the browser, for example as an efficient and flexible language for serverless computing.

This article is a case study on using WebAssembly to speed up a data analysis web tool. To that end, we’ll take an existing tool written in C that performs the same computations, compile it to WebAssembly, and use it to replace slow JavaScript calculations.

Note: This article delves into some advanced topics such as compiling C code, but don’t worry if you don’t have experience with that; you will still be able to follow along and get a sense for what is possible with WebAssembly.

Background

The web app we will work with is fastq.bio, an interactive web tool that provides scientists with a quick preview of the quality of their DNA sequencing data; sequencing is the process by which we read the “letters” (i.e. nucleotides) in a DNA sample.

Here’s a screenshot of the application in action:

Interactive plots showing the user metrics for assessing the quality of their data

A screenshot of fastq.bio in action (Large preview)

We won’t go into the details of the calculations, but in a nutshell, the plots above provide scientists a sense for how well the sequencing went and are used to identify data quality issues at a glance.

Although there are dozens of command line tools available to generate such quality control reports, the goal of fastq.bio is to give an interactive preview of data quality without leaving the browser. This is especially useful for scientists who are not comfortable with the command line.

The input to the app is a plain-text file that is output by the sequencing instrument and contains a list of DNA sequences and a quality score for each nucleotide in the DNA sequences. The format of that file is known as “FASTQ”, hence the name fastq.bio.

If you’re curious about the FASTQ format (not necessary to understand this article), check out the Wikipedia page for FASTQ. (Warning: The FASTQ file format is known in the field to induce facepalms.)

fastq.bio: The JavaScript Implementation

In the original version of fastq.bio, the user starts by selecting a FASTQ file from their computer. With the File object, the app reads a small chunk of data starting at a random byte position (using the FileReader API). In that chunk of data, we use JavaScript to perform basic string manipulations and calculate relevant metrics. One such metric helps us track how many A’s, C’s, G’s and T’s we typically see at each position along a DNA fragment.

Once the metrics are calculated for that chunk of data, we plot the results interactively with Plotly.js, and move on to the next chunk in the file. The reason for processing the file in small chunks is simply to improve the user experience: processing the whole file at once would take too long, because FASTQ files are generally in the hundreds of gigabytes. We found that a chunk size between 0.5 MB and 1 MB would make the application more seamless and would return information to the user more quickly, but this number will vary depending on the details of your application and how heavy the computations are.

The architecture of our original JavaScript implementation was fairly straightforward:

Randomly sample from the input file, calculate metrics using JavaScript, plot the results, and loop around

The architecture of the JavaScript implementation of fastq.bio (Large preview)

The box in red is where we do the string manipulations to generate the metrics. That box is the more compute-intensive part of the application, which naturally made it a good candidate for runtime optimization with WebAssembly.

fastq.bio: The WebAssembly Implementation

To explore whether we could leverage WebAssembly to speed up our web app, we searched for an off-the-shelf tool that calculates QC metrics on FASTQ files. Specifically, we sought a tool written in C/C++/Rust so that it was amenable to porting to WebAssembly, and one that was already validated and trusted by the scientific community.

After some research, we decided to go with seqtk, a commonly-used, open-source tool written in C that can help us evaluate the quality of sequencing data (and is more generally used to manipulate those data files).

Before we compile to WebAssembly, let’s first consider how we would normally compile seqtk to binary to run it on the command line. According to the Makefile, this is the gcc incantation you need:

# Compile to binary
$ gcc seqtk.c
-o seqtk
-O2
-lm
-lz

On the other hand, to compile seqtk to WebAssembly, we can use the Emscripten toolchain, which provides drop-in replacements for existing build tools to make working in WebAssembly easier. If you don’t have Emscripten installed, you can download a docker image we prepared on Dockerhub that has the tools you’ll need (you can also install it from scratch, but that usually takes a while):

$ docker pull robertaboukhalil/emsdk:1.38.26
$ docker run -dt –name wasm-seqtk robertaboukhalil/emsdk:1.38.26

Inside the container, we can use the emcc compiler as a replacement for gcc:

# Compile to WebAssembly
$ emcc seqtk.c
-o seqtk.js
-O2
-lm
-s USE_ZLIB=1
-s FORCE_FILESYSTEM=1

As you can see, the differences between compiling to binary and WebAssembly are minimal:

Instead of the output being the binary file seqtk, we ask Emscripten to generate a .wasm and a .js that handles instantiation of our WebAssembly module
To support the zlib library, we use the flag USE_ZLIB; zlib is so common that it’s already been ported to WebAssembly, and Emscripten will include it for us in our project
We enable Emscripten’s virtual file system, which is a POSIX-like file system (source code here), except it runs in RAM within the browser and disappears when you refresh the page (unless you save its state in the browser using IndexedDB, but that’s for another article).

Why a virtual file system? To answer that, let’s compare how we would call seqtk on the command line vs. using JavaScript to call the compiled WebAssembly module:

# On the command line
$ ./seqtk fqchk data.fastq

# In the browser console
> Module.callMain([“fqchk”, “data.fastq”])

Having access to a virtual file system is powerful because it means we don’t have to rewrite seqtk to handle string inputs instead of file paths. We can mount a chunk of data as the file data.fastq on the virtual file system and simply call seqtk’s main() function on it.

With seqtk compiled to WebAssembly, here’s the new fastq.bio architecture:

Randomly sample from the input file, calculate metrics within a WebWorker using WebAssembly, plot the results, and loop around

Architecture of the WebAssembly + WebWorkers implementation of fastq.bio (Large preview)

As shown in the diagram, instead of running the calculations in the browser’s main thread, we make use of WebWorkers, which allow us to run our calculations in a background thread, and avoid negatively affecting the responsiveness of the browser. Specifically, the WebWorker controller launches the Worker and manages communication with the main thread. On the Worker’s side, an API executes the requests it receives.

We can then ask the Worker to run a seqtk command on the file we just mounted. When seqtk finishes running, the Worker sends the result back to the main thread via a Promise. Once it receives the message, the main thread uses the resulting output to update the charts. Similar to the JavaScript version, we process the files in chunks and update the visualizations at each iteration.

Performance Optimization

To evaluate whether using WebAssembly did any good, we compare the JavaScript and WebAssembly implementations using the metric of how many reads we can process per second. We ignore the time it takes for generating interactive graphs, since both implementations use JavaScript for that purpose.

Out of the box, we already see a ~9X speedup:

Bar chart showing that we can process 9X more lines per second

Using WebAssembly, we see a 9X speedup compared to our original JavaScript implementation. (Large preview)

This is already very good, given that it was relatively easy to achieve (that is once you understand WebAssembly!).

Next, we noticed that although seqtk outputs a lot of generally useful QC metrics, many of these metrics are not actually used or graphed by our app. By removing some of the output for the metrics we didn’t need, we were able to see an even greater speedup of 13X:

Bar chart showing that we can process 13X more lines per second

Removing unnecessary outputs gives us further performance improvement. (Large preview)

This again is a great improvement given how easy it was to achieve—by literally commenting out printf statements that were not needed.

Finally, there is one more improvement we looked into. So far, the way fastq.bio obtains the metrics of interest is by calling two different C functions, each of which calculates a different set of metrics. Specifically, one function returns information in the form of a histogram (i.e. a list of values that we bin into ranges), whereas the other function returns information as a function of DNA sequence position. Unfortunately, this means that the same chunk of file is read twice, which is unnecessary.

So we merged the code for the two functions into one—albeit messy—function (without even having to brush up on my C!). Since the two outputs have different numbers of columns, we did some wrangling on the JavaScript side to disentangle the two. But it was worth it: doing so allowed us to achieve a >20X speedup!

Bar chart showing that we can process 21X more lines per second

Finally, wrangling the code such that we only read through each file chunk once gives us >20X performance improvement. (Large preview)

A Word Of Caution

Now would be a good time for a caveat. Don’t expect to always get a 20X speedup when you use WebAssembly. You might only get a 2X speedup or a 20% speedup. Or you may get a slow down if you load very large files in memory, or require a lot of communication between the WebAssembly and the JavaScript.

Conclusion

In short, we’ve seen that replacing slow JavaScript computations with calls to compiled WebAssembly can lead to significant speedups. Since the code needed for those computations already existed in C, we got the added benefit of reusing a trusted tool. As we also touched upon, WebAssembly won’t always be the right tool for the job (gasp!), so use it wisely.

Further Reading

“Level Up With WebAssembly,” Robert Aboukhalil
A practical guide to building WebAssembly applications.
Aioli (on GitHub)
A framework for building fast genomics web tools.
fastq.bio source code (on GitHub)
An interactive web tool for quality control of DNA sequencing data.
“An Abridged Cartoon Introduction To WebAssembly,” Lin Clark

Smashing Editorial
(rb, ra, il)

Collective #505

Original Source: http://feedproxy.google.com/~r/tympanus/~3/Bxenxt_Awkk/

C505_WOTW

Inspirational Website of the Week: Dogstudio

A perfect symphony of exciting WebGL, modern typography and great layout. Our pick this week.

Get inspired

C489_NW

This content is sponsored via Syndicate Ads
Northwestern’s Online MS in Information Design and Strategy

Build the in-demand skills, such as UX, UI, and HCI, needed to drive user interactions. Choose a specialization in content strategy, analytics, or learning design.

Apply now

C505_yetanother

Yet Another JavaScript Framework

A wonderful article by Jason Hoffman on the history of JavaScript frameworks and the legacy they left behind.

Read it

C505_CSSBattle

CSSBattle

Use your CSS skills to replicate targets with smallest possible code.

Play it

C505_vertigo

Accessibility for Vestibular Disorders: How My Temporary Disability Changed My Perspective

Facundo Corradini shares his experience with temporary vertigo and how it changed his mindset on accessibility for good.

Read it

C505_zindex

Managing Z-Index In A Component-Based Web Application

Pavel Pomerantsev describes an approach for successfully managing stacking in a web app.

Read it

C505_Dogstudio

Some dogstudio.co insights

Kevin Chapelier provides some valuable insight into the initial implementation of the WebGL/three.js dog scene on dogstudio.co.

Check it out

C505_component

A progressive disclosure component

Andy Bell discusses some key elements of a progressive and accessible disclosure component.

Read it

C505_editor

Editor.js

The next generation block styled editor got a major update.

Check it out

C505_grass

Grass

A stunning grass shader with three.js by Al Ro.

Check it out

C505_hip

You probably don’t need that hip web framework

Owen Williams explains why obsession with finding better frameworks is killing ideas before they reach the world.

Read it

C505_api

Upcoming WebHID API – access Bluetooth/USB HID devices in web applications

Robat Williams takes a look at the exciting, yet to be released WebHID API and shows what you might be able to do with it.

Read it

C505_onlick

How I failed the <a>

Remy Sharp shares how and why you should be extra careful when adding onClick to a component.

Read it

C505_gimli

Gimli

A promising looking Visual Studio Code extension enabling smart visual tools for front-end developers. You can back it on Kickstarter.

Check it out

C505_pagination

combine-pagination

A JavaScript library for paginating across multiple data sources at once, whilst retaining the sort order.

Check it out

C505_danhooks

Dan Abramov teaches me React Hooks

Watch Mattias Petter Johansson get a React Hooks master class by Dan Abramov in this Fun Fun Function live stream recording.

Watch it

C505_xray

x-ray

In case you didn’t know it: A simple HTML debugger, executable by bookmark, that let’s you visualize the HTML structure of a website.

Check it out

C505_icons

Remix Icon

A great set of open source neutral style system symbols.

Get it

C505_Font

Free Font: Explorer

A playful uppercase typeface by Kristaps Zelmenis.

Get it

C505_colortheory

Color theory for designers – a crash course

An infographic that will teach you some important aspects of color theory applied to web design. By Micah Bowers.

Check it out

C505_shoperr

shoperr

With shoperr you can create your own custom shop in minutes, and stock up on referral links to your favorite products.

Check it out

C505_slideshow

From Our Blog
Crossroads Slideshow

An experimental slideshow with an inclined look, three slide previews and a content view on click.

Check it out

Collective #505 was written by Pedro Botelho and published on Codrops.

How to Build a News App with Ionic 4 & Angular

Original Source: https://www.sitepoint.com/ionic-4-angular-build-app/

In this tutorial we’ll be using Ionic 4 to build a news application that makes use of a third-party news API.

Ionic 4 is the latest version of Ionic, a mobile framework originally built on top of Cordova and Angular. Ionic allows users to create hybrid mobile apps with HTML, CSS and JavaScript and their related web technologies.

What makes Ionic 4 the best version yet is that it’s now framework agnostic. This means it’s not dependent on Angular anymore, and you you’ll be able to use it with any framework or library you are familiar with, or with plain JavaScript.

But at the time of this writing, Ionic CLI only supports generating Ionic projects based on Angular, so we’ll be using an Angular/Ionic project to build our news application.

See a hosted version of the application we’ll be building and grab the source code from this GitHub repository.

Prerequisites

Let’s get started with the prerequisites you need to be able to follow this tutorial comfortably.

The post How to Build a News App with Ionic 4 & Angular appeared first on SitePoint.

The best iPad stylus in 2019: top iPad styluses for drawing and note-taking

Original Source: http://feedproxy.google.com/~r/CreativeBloq/~3/2tklqxlfueg/best-ipad-stylus

If you want to use one of the many fantastic iPads available now as a tool for drawing, you're going to need a stylus. Your impulse may well be to simply pick up the Apple Pencil, and while this is a great buy and you won't go wrong with it, we'd recommend taking a moment to consider some of the alternative options out there. 

There are many iPad-compatible styluses available from other manufacturers, and many of them are extra-attractive by virtue of the fact that they cost considerably less than Apple's version. We've picked out the best of the best styluses available right now, for all iPad users and all budgets, so you can find which one is right for you and get to drawing.

The best tablets with a stylus for drawing and note-taking

In the following guide, we'll walk you through the best iPad styluses with integrated buttons that you can customise for different functions, and we'll help you decide whether an iPad stylus with a hard nib or soft nib is likely to be better for your requirements. Read on to find out exactly what stylus for your iPad you should buy – and where to buy it for the best price.

Apple Pencil next to two iPads showing artwork

The new Apple Pencil (2018) works with the third-generation 12.9-inch iPad Pro or the 11-inch iPad Pro. The original Apple Pencil works with iPad Pro 12.9-inch (second and first generation), iPad Pro 10.5-inch, iPad Pro 9.7-inch and iPad (6th generation).

The Apple Pencil is, of course, the natural choice of stylus for iPad – but only if you own one of the two iPad models that are compatible with it: an iPad Pro or sixth-generation iPad (2018). If you do, there isn't a better stylus to write and draw with on the market. Not only is it exceptionally comfortable to use, Apple has eliminated many of the issues that can dog other styluses – such as inadequate palm rejection and clear lag that instantly makes you feel disconnected to what you're producing on the screen. The astonishing pressure levels mean that the Apple Pencil reproduces your movements perfectly, at even the most acute angles, and it enhances all your favourite creative iOS apps. The bottom line is that if you've forked out the cash for an iPad Pro, you'd be daft not to swallow the extra expense and go straight for an Apple Pencil.

Also read: Apple Pencil review

Wacom boasts an industry-leading reputation thanks to its fabulous range of dedicated drawing tablets. So it's only natural that the company produces an attractive line of styluses as well. As well as being our favourite iPad stylus for artists, the Wacom Bamboo Sketch also takes the plaudits for general use on the iPad Air and iPad Mini series thanks to its compatibility with iOS devices. Rather than trying to exactly mimic a traditional rounded pen, the Bamboo Sketch favours an ergonomic triangular design for better grip. It's an excellent all-rounder, but its fine tip and pressure-sensitive nibs make it just about as close an experience to sketching on paper as you can get. With an epic battery life (recharged via USB) it uses Bluetooth to connect to your iPad, which brings the integrated shortcut buttons into play, too, enabling you to set up handy shortcuts within your chosen iOS apps.

Despite the fact that you can snag one for less than £30, the Hahakee iPad stylus does a good job of feeling like a premium product, thanks to an aluminium alloy build with a polished finish. It's pleasant to hold and use, and thanks to the healthy forty-hour battery life, you'll find yourself easily getting lost in your projects before it needs a charge. Charging is accomplished via the micro-USB port concealed in the top. With a fine tip, the Hahakee stylus is pleasingly precise, and spare nibs in the box ensure it'll keep on being usable for a long time (indeed, probably considerably longer than the iPad you're drawing on). It's no Apple Pencil, but for the money, it's a great buy.

Adonit has been refining its stylii for more than eight years now, and the Pixel is still one of its best for drawing on iPad. Bluetooth enabled and compatible with many of the sorts of apps creatives will likely be using on their tablets, the Pixel boasts 2048 levels of pressure sensitivity and a range of function buttons on its body that can be assigned to the user's preferred tools (though be warned these can be easy to knock accidentally if you're not paying attention). The battery should last for about 15 hours of use, allowing you to get really stuck into your projects, and the sleek design makes the Pixel stylus genuinely enjoyable to use.

If you're not sold on the idea of spending upwards of $20/£20 on a simple pointing device, and don't need the specialised functioning of the iPad styluses above, then Adonit's budget option – the Adonit Mark – is worth considering. Despite its cheap price tag, this stylus has been designed to feel as comfortable as possible in your hand, with its triangular anti-roll design. It retains the precision you'd expect from the sole-purpose stylus manufacturer, largely thanks to its smudge-free mesh tip. The Adonit Mark won't win any innovation awards, but if you just want a stylus for navigating around your iPad, you won't find a better cheaper iPad stylus than this. 

Related articles:

The best tablets with styluses10 top new best tools for traditional artists Best cheap Wacom tablets you can buy

9 Time Tracking Apps for Freelancers

Original Source: http://feedproxy.google.com/~r/1stwebdesigner/~3/Bdbz1qkfd8s/

When you’re not working on the typical schedule of a nine-to-five job, it’s easy to lose track of all those hours. Where is all that time going? If you’re struggling to stay on task, or just want to make the most of your hours, one of these time tracking apps is just the thing. It’s time to reclaim your work life!

Toggl

Toggl

How does free/cheap time tracking software sound? Toggl is flexible and designed for teams of any size. One-click timers turn into valuable insight and business statistics, so you can reclaim those lost hours. Super affordable per-user billing means you don’t need to pay more than the app is worth, and teams up to five can use Toggl for free!

Harvest

Harvest

Harvest is a business-oriented time tracking app, rich with features and loaded with everything you need to keep you and your team on target. The program works by letting you set timers or fill out a timesheet yourself – super simple. Manage projects, see how your team is doing and bill clients from your phone, desktop or browser.

Clockify

Clockify

A simple time tracker, 100% free with no strings attached. Clockify was created because every team and freelancer should have an easy way to track their time. It may not have the flashy features of other apps, but it does exactly what you need. Individual, team and project tracking, hassle-free.

DropTask

DropTask

Made for visual thinkers, DropTask is the free management software for those looking for something a little more flexible. If other software is too restrictive, you’ll be pleased with this app. Work alone or together in real time with two teammates, or try the business version if you need even more control.

RescueTime

RescueTime

Time to create a balanced work-life schedule! RescueTime runs in the background and creates a report on what apps and websites you’ve spent your time on, letting you accurately identify distractors.

The software is free, but the premium version lets you block websites or set up alerts. RescueTime for organizations offers insight into your employees’ habits while allowing them to keep their privacy with generalized reports.

Hubstaff

Hubstaff

Running a freelancing team? Hubstaff is made for businesses and freelancers who need a way to track employees’ time spent. You can also use it for free by yourself! This is an all-in-one program that includes time tracking features as well as payroll, invoicing, scheduling, and more.

Billings Pro

Billings Pro

The no-nonsense slogan sums it up pretty well: “Track, invoice, and get paid”. Send clients quotes, track your billable time while creating helpful reports and send an invoice when you’re done. Simple and to the point. The cross-platform app even has Apple Watch support!

Hours

Hours

Hours is easy to sign up for, easier to use, and lets you switch between timers with just a tap. The app’s timeline feature allows you to easily adjust your logged hours when there’s a mistake and get more accurate reports. You can use it on any device or right in the browser.

TimeCamp

TimeCamp

Need a free way to track what you’re doing on your computer? Try TimeCamp. For one user, the app is free forever. And its reports are super detailed, down to logging when you turn your PC on or off. With the paid versions, you get team support and access to dozens of helpful addons.

Eliminate Distractions

Time is money. How much is yours worth? When work isn’t getting done and you’re not sure why, it’s time to turn to one of these awesome time tracking apps. It can really be enlightening to learn how much time you spend on distractions throughout the day. And, armed with this knowledge, you’ll be able to cut out those wasteful hours and stay productive.