Tumgik
qvault · 3 years
Text
What are UUIDs, and should you use them?
The post What are UUIDs, and should you use them? first appeared on Qvault.
A universally unique identifier (UUID) is a 128-bit format for creating IDs in code that has become popular in recent years, especially in relation to database keys. By using UUIDs, you ensure that your ID is not just unique in the context of a single database table or web application, but is truly unique in the universe. No other ID in existence should be the same as yours.
Sorry to interrupt! I just wanted to mention that you should check out my new free Go course. It’s designed to teach you all the fundamentals of my favorite coding language.
Learn Golang Now
It is important to note that while the probability that a UUID will collide with another is not zero, its practically zero. The chances of collision are so astronomically low, worrying about it would be ridiculous. The total number of possible UUIDs is 2^128 or 340282366920938463463374607431768211456.
UUID Generator Online
Generate UUID!
function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } const button = document.getElementById('uuidButton'); const result = document.getElementById('uuidOut'); const genUUID = () => { result.value = uuidv4(); } button.addEventListener('click', genUUID);
Why use a UUID?
The main advantage of using UUIDs is that you can create a UUID and use it to identify something, such as a row in a database, with near certainty that the identifier will not exist in another row in your system or anyone else’s. UUIDs used by completely unrelated companies or organizations can be referenced together without duplication.
Let’s take a real-world example and analyze why using UUIDs can make our lives easier. Let’s pretend we have a web application with a single database. One of the tables in that database is the “users” table. Each user has a primary key, and like many databases, that primary key is just an integer. So the first user will have the ID “1”, the next will be “2”, and so on.
1Plato2Aristotle3Marcus Aurelius
That may be fine for a while, but now imagine that we introduce more services into our backend architecture. For example, there may be a separate database that stores social media posts and we need to know which user made the posts. Well, we need to store a user ID, so we just start storing the user’s ID in that separate database as a kind of foreign key. If we need a list of posts, we look in the “users” database to see what information we have about the author. So far, so good.
Now let’s break things down. Let’s say we acquire a new company and that company has their own user database and they have done the same thing using integers for their user IDs, so now we have a system where a single user ID can potentially point to two different records! To fix the problem, we would have to create a new list of IDs and painstakingly go through each data store in our architecture and update the IDs. In some systems, this would be almost impossible, especially without introducing some bugs.
By using UUIDs (or another kind of universally unique ID) we can save ourselves all this headache. I’m open to the possibility that universally unique IDs could create issues in a system’s archiecture, I’ve just never experienced it, and I can’t think of why it would be problematic.
Why are UUIDs only recently gaining popularity?
All I can really do is guess, but I have a couple of candidate hypotheses.
1. Making a UUID is slightly more complicated than just incrementing an integer
You have to have a bit of custom code that generates a specific format of the string, and you need to ensure that you have enough entropy in your system to ensure uniqueness.
2. They take up a bit more memory
UUIDs take up 128 bits in memory and can take up more if stored as a string. In systems where resources are precious, it could make sense to use a more compact format. That said, in modern web development, I think we’d be penny-wise and dollar-stupid to care about such negligible resource usage.
The UUID Format
While you could just generate 32 random digits and call your home-grown ID format “good enough”, it’s nice to use standards that already exist. Aside from the fact that there are safe libraries you can use to work with standard UUIDs, it’s nice to look at the UUID format and know “hey, this is an ID”! If you roll your own format, you’ll likely confuse members of your team. They could think it’s an encoded JWT, or perhaps a private key. Best to avoid that confusion.
A UUID is made up of 32 hex (base-16) digits, displayed in five sections. For example, bc2d0f53-5041-46e8-a14c-267875a49f0c. The sections are broken in the form 8-4-4-4-12. Including the four hyphens, it comes to a total of 36 characters. UUIDs are also typically displayed in lowercase, which to be honest is a bit unique for hex encoding. You can read more about the specifics of UUID formatting on Wikipedia.
UUID Versions
There are 5 versions of UUIDs out there. Versions 1 and 2 are time and MAC address-based. The idea is there’s some determinism in the system. You can get the same UUID if you use the same time and MAC address as inputs when generating the UUID. Versions 3 and 5 are similar, but instead of using time and MAC addresses, they use namespaces.
Version 4 is probably what you want. If you’re interested in using UUIDs to tag disparate entities in a software system, it’s very likely you just want random UUIDs.
UUIDs vs GUIDs
The term GUID, which stands for Globally Unique Identifier, is an industry standard defined by Microsoft. As we know, UUID stands for Universal Unique Identifier. So the two terms basically mean the same thing. Apart from the fact that GUIDs (Microsoft’s version) and UUIDs (an open Internet standard defined by RFC4122) look similar and serve similar purposes, there are minor differences.
Some GUIDs may contain any hex digit in any position, while RFC4122 requires specific values for the version and variant fields. Also, GUIDs are typically written in upper case, while UUIDs should be written in lower case. Sometimes these subtle differences can cause incompatibilities between code libraries.
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article, please let me know so I can get it corrected!
from Qvault https://ift.tt/3kRywh4
0 notes
qvault · 3 years
Text
What is Go Good For? (And What Is Golang Used For?)
The post What is Go Good For? (And What Is Golang Used For?) first appeared on Qvault.
In 2007, frustrated by some of C++’s inefficiencies and overcomplicated nature, and desiring a programming language designed specifically for multi-core processors and effectively managing large projects, three Google engineers, Robert Griesemer, Rob Pike, and Ken Thompson, designed the Go language.
The goal was to build an improved C++ that was much easier to use — Go was developed based on C’s disciplined syntax — but also took inspiration from some of Python’s simplicity and Javascript’s useful features.
Sorry to interrupt! I just wanted to mention that you should check out my new free Go course. It’s designed to teach you all the fundamentals of my favorite coding language.
Learn Golang Now
This combination makes Go one of the most effective languages for large-scale infrastructure, and one of the simplest languages for debugging complex projects.
The open-source Go project was first announced in 2009, and version 1.0 was officially released in 2012. Major new features have since been added, such as generics and error handling in 2018.
Go vs Golang: what to call Go The official name of the language is Go, with the confusion over its name mostly due to the golang.org domain name (go.org wasn’t available). Though the official term is Go, some find Golang is more convenient to use and prevents confusion with the strategy game Go, so it survives as a cherished alternative name.
What is Go?
Go is statically typed
The difference between Go and dynamically typed languages like JavaScript and Python:
With static languages, you need to declare your variable data types before you use them.
With dynamically typed languages, you only perform type checking at runtime — rather than at compile time.
Statically typed programs will fail to compile until errors have been fixed, whereas dynamic scripts can start up even if they contain key errors that may crash later during execution.
For more differences between Go and dynamically typed languages like Python, read our Go vs Python guide
Go’s static typing ensures conversions and compatibility while avoiding the run-type errors and difficulty debugging that can occur with dynamically typed languages.
Go is compiled rather than interpreted
As a compiled language, Go is expressed in the instructions of the target machine in 0s and 1s. Whereas interpreted languages are interpreted (without compiling it into machine code), the program instructions use a virtual machine rather than the target machine. 
This lets Go runs faster and offer better performance than interpreted language programs. Compiled language errors prevent the code from compiling, whereas errors in the interpreted language programs are found at run-time, with interpreted languages able to modify code even while the program is still running.
Concurrent & multi-core support
Since Go was designed from the very beginning to run on multiple cores, it has rich support for concurrency and for scaling when more cores are added.
Go uses “goroutines” and channels, concurrent functions that allow the rest of the program to compute while they run, making for efficient dependency management.
Goroutines are great as they continue if you have a network timeout or even an entire database failure, so you can work around any problems that come up. Go’s automatic garbage collection mimics Python and makes for a more convenient coding experience. 
Go modules is Golang’s simple package manager publishable using a small set of commands. Go’s Gofmt tool is helpful for automatically formatting and indenting code, with other tools like Go run, Go get and Godoc also convenient. It’s very versatile, and easy to replace your scripting languages with Golang.
Go is highly paid, and in high demand
Now over 10 years since Go’s original open source release, Go is the second highest paid language with median earnings of $140,000 in the USA, is one of the most loved languages by programmers, and Go devs are more in higher demand than ever before.
It’s never been a better time to learn Go, and here’s why:
What is Go Good For?
Simple Syntax & Easy To Learn
Go contains a small number of popular concepts inspired by other languages, designed to create the simplest possible code. This saves time scanning code to check it, as well as time saved writing less code.
For example, Go has very few data types, such as int, string, bool, float64 and complex128, that each have default options that cover most uses. With such few options and concepts to learn, experienced programmers can learn Go in just a few days.
The language itself is similar to C, just without some of C’s frustrating inefficiencies that reduce the time required to clean complex code. If you have either previous Java or C experience, you’ll have no issues understanding Go as all these languages follow the same procedural approach.
And if you’re struggling to find a course that teaches you Go right from the beginning, try our Go Mastery course.
Go is Fast
Go code is compiled and directly translated into processor-understandable formats. This makes it far faster than languages like Java that first need to compile into byte code, before executing it via a virtual machine (VM). 
Boasting small application sizes, Go binary files can be up to 10x smaller than their Java equivalent. This is especially notable for large applications deployed on multiple servers, heavily reducing file loading time and making for much improved performance.
Go programs are lightweight, as Go runtimes clean up unused memory as extra code within the executable binary. This makes it easier to write memory-efficient Go code as the Go compiler has some spare code logic within each program.
Languages like Rust and C++ use slightly less memory than Go however — but this is because they afford developers more control over memory usage, whereas Go runtime automatically handles this for efficiency.
Designed for multi-core processors and well-scaled for concurrency, making it ideal for large-scale projects
Many languages designed prior to the adoption of multi-core processors (such as Java, JavaScript, C++ and Python) have difficulties scaling and are one-threaded. As a more modern language designed for multi-core processors, Go contains effective support for parallel processes (as do C#, Erlang and other languages). It’s also designed in the internet age, and so Go doesn’t require third-party libraries for web service support.
Goroutines are scalable and non-blocking, ideal for when multiple concurrent processes are required — and take up just 2kb of overhead memory. Goroutines are a convenient combination of Javascript’s async features with standard Java multi-threading. As a result, open-source projects like Kubernetes, Docker, InfluxDB and Jaeger all opted for Go as their programming language.
Golang’s quick and efficient compilation makes it effective for even the largest projects. Even the most complex projects can be quickly built and worked on efficiently to reduce bugs and aid easy debugging.
On large projects where many developers work together to maintain and develop in teams, it’s integral that they be able to work in sync and understand each other’s solutions. Go is designed based on the philosophy that there should be very few solutions (ideally just one) rather than a wide variety of ambiguous solutions, so that maintaining these large and complex projects is as simple as possible. 
What is Go Used For?
Infrastructure 
Popular open source tools like Kubernetes, Docker and Prometheus are written in Go for container deployment, scaling and management for running and bundling applications.
Cloud service tools like Terraform and OpenShift are written in Go to offer additional cloud and deployment options, with OpenShift running on top of Kubernetes and used by companies such as KPMG to automate and enhance their AI workflows.
For server-side operations, Netflix uses Go for some of its server architecture, writing its Rend proxy on Go. Netflix said:
“The decision to use Go was deliberate, because we needed something that had lower latency than Java (where garbage collection pauses are an issue) and is more productive for developers than C, while also handling tens of thousands of client connections. Go fits this space well.”
Dropbox also switched from Python to Go in 2014 for performance-critical backend features.
Command-line interfaces
Companies like Comcast, GitHub, Stripe and Uber use Go for their command-line interfaces. Comcast maintains an open source client library written in Go, whereas Uber uses Go for CLI API for Jaeger.
Web applications
Large web apps like Monzo’s online banking app have been built in Go since their inception, and now use it to host over 1,600 microservices. Monzo has been using Go solely since 2015, working with Kubernetes and highlighting that Go is “quite simple, it’s statically typed, and it makes it easy for us to get people on board.”
SoundCloud have also been using Go since as early as 2012 in their build and deployment system, though they mostly use Ruby on Rails. SoundCloud developed what eventually became Prometheus in 2012, which is now used by AT&T, Honeywell, JP Morgan & Chase, and many other large companies.
Our Qvault web app, designed to teach you computer science interactively, is also written in Go.
Other large companies that use Go include Google & YouTube (obviously), Medium, BBC, Dailymotion, SendGrid, and Badoo.
Cryptography and cryptocurrency
Most notably, implementations of the Bitcoin Lightning Network is written in Go, as well as Geth, the main Ethereum implementation.
Machine learning and data science
Both Go and Python have been considered some of the best programming languages for AI and machine learning, yet Go trails way behind R and Python as the most popular data science and machine learning languages.
Go can handle complex math problems much faster than Python, though Python has advantages with its versatility, readability and multi-purpose use for data science. You can now run Tensorflow models in Go as opposed to just Python to take advantage of some of Go’s speed advantages.
We believe that Go will become a much more widely adopted machine learning language in the future.
Limitations of Go
Go doesn’t support generic functions — You can’t write implicit code, and the lack of generics support hurts efficiency and reduces your code’s reusability. That said, generics are coming in version 2.
Go icode takes longer to write than Python — Go’s simple syntax makes it easy to code in, but Python can often write in just a few lines what Go could require more than double to replicate.
Not suitable for some types of applications — Go is great for some things like maintaining complex systems serving large audiences for backend system scaling, but the same features that make it so exceptional for these uses, like its small memory footprint, also make it less useful for simpler and smaller-scale projects. For rapidly prototyping an application or creating a bite-size demo, you’d favor Python and its dynamic typing over Go.
Go is newer, and therefore has a less extensive library and community than some languages, such as Python.
Conclusion: Should You Code in Go?
Go programmers command some of the highest salaries, love writing code with Go, and companies are clamoring to hire Go devs.
So should you learn Go, too?
We absolutely think so.
We’re huge fans of Golang at Qvault, and created our Go Mastery courses to help teach Go as effectively as possible — by learning by doing. Our interactive lessons have you code in Go to fix problems, create programs, and we even built a specialized Go Interview Prep course for landing a job once you’ve gained the core skills.
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article, please let me know so I can get it corrected!
from Qvault https://ift.tt/2UcVMeK
0 notes
qvault · 3 years
Text
Golang vs C++: Which is Best For Your Next Project
The post Golang vs C++: Which is Best For Your Next Project first appeared on Qvault.
Needing to be a math genius to learn code is a thing of the past, as more high-level programming languages offer an alternative to low-level machine code, making it more accessible than ever to get coding.
But with dozens of languages available, which ones are worth learning?
Regardless of whether you plan to work in computer science, or casually dabble in code, the best thing you can do is understand what each language does and who uses them. That way, you know you’re learning a language that benefits you.
Sorry to interrupt! I just wanted to mention that you should check out my new free Go course. It’s designed to teach you all the fundamentals of my favorite coding language.
Learn Golang Now
Now, you may have seen our breakdown of Golang vs. Python, but now it’s time to see how Golang matches up to C++. We’ll compare their design, performance, speed, and security, as well as discuss key differences between the two languages and how they’re used in the real world.
Golang vs C++: A Brief History
When it comes to history, C++ and Golang sit at opposite ends of the spectrum.
The first edition of C++ was released in 1985, originally named C with Classes, bringing the first C language superset to the market. Development started in 1979 by Danish computer scientist Bjarne Stroustrup at Bell Laboratories, to create an easier version of C that uses classes or code templates.
Golang (or Go) 1.0, however, wasn’t on the market until 2012, after being developed by Robert Griesemer, Rob Pike, and Ken Thompson, who, ironically, were powered by their mutual frustration with C++. In the end, they took the best of everything – the best of Java, Python, and C languages – to create Go. Its C-inspired syntax also makes learning Golang for C++ programmers effortless.
Go vs C++: Which Has a Better Design?
Let’s start by taking a straightforward view of the basic make-up of these languages.
GoC++High-level languageMid-level languageProceduralObject-oriented (mostly)Top-down approachBottom-up approach
As we can see, they’re different in almost every way possible. Top-down, bottom-up, mid-level, high-level – but what does this all mean?
High vs Mid-Level Language
First, we have the level of language.
Golang is a high-level language. This means it’s easy to read, understand and learn because it’s the most simplified version of machine code. Alternatively, C++ is a mid-level language, which means it’s harder to understand and less simplified.
Machine code is the language computers speak, and instead of us racking our brains to understand it, abstractions are used to hide all the unnecessary noise. That way, when reading code we mostly see our natural language, making the syntax easier to understand.
Go, as a high-level language, has significantly more of these abstractions than our friend C++ here, which is only a mid-level language. Golang also has limitations and features embedded in its structure, so it’s easier to develop programs without issues.
Mid-level languages, or pseudo languages, aren’t directly machine code, but they are much closer to it. For example, C++ interacts directly with the abstraction layer of a computer system, whereas Golang is more heavily translated before the computer can understand it.
C++ also doesn’t come with any user-friendly features, however, it’s a completely open book, and if you can think of it then you can create it with C++.
Type of Approach
The bottom-up and top-down approach is about how general or specific the language is.
Imagine you’re in a clear lake, looking down at the water. You can tell from the surface there are other things in the water, but you only get a general view of what they could be.
However, if you break through the surface, you find rocks, shells, sand, fish – all of the specific objects that are in the lake.
Golang is like the surface. With a top-down approach, you only work with the general functions and programs you want — and avoid mingling with specific objects.
C++ is like the lakebed. With a bottom-up approach, you build each specific layer, code each rock, fish, and shell, until you get to the surface — you have full creative control, and full responsibility.
Different Language Types: Go vs C++ and OOP vs Procedural
Finally, we have object-oriented and procedural language types.
Object-oriented (or OOP) is when you manipulate the object, rather than the logic and functions around the object. Thanks to abstractions and encapsulations, C++ can directly manipulate the object it wants.
Now again, it doesn’t possess as many layers as high-level languages, but it has enough that you can directly control the action you’re trying to achieve. This isn’t an easy job though, as creating programs based on the interaction of objects is extremely complex.
It’s important to note that while C++ is an OOP language, it’s also a multi-paradigm language, so it can support procedural and functional programming. However, OOP, especially with modern C++, is its most common application.
Golang, on the other hand, is a procedural language. For this, you simply write down the steps of the task in the order you want the computer to run them. It’s based on the concept of a series of computational steps. Golang is also a multi-paradigm language and supports functional programming.
Overall, in terms of design, Golang is better in the sense it’s more user-friendly, but if you’re looking for more control then C++ is a better choice.
Golang vs C++: Which Is Faster?
When it comes to asking “is Golang faster than C++” there are two ways you need to look at it: writing time and compile time.
Writing time is how fast and easily can you write the language.
Harkening back to our understanding of Golang as a high-level language, Go was purposefully built to make coding faster, easier, and scalable. As a high-level language, its syntax is much more readable and compact than C++.
Go also has a faster compile time. Codes must be compiled before they run, and after every change you make – a.k.a. you’ll be compiling a lot. So, this is necessary when considering coding speed.
Compile time is dependent on what you’re coding, however, C++ is famous for its slow compile time. Go’s compact style makes compiling quicker than C++’s long drawn-out form. 
Overall, Golang beats C++ hands down when it comes to coding speed.
Golang Performance vs C++ Performance
Both languages boast fantastic performance.
Go’s efficient garbage collector, static types, and compilation make it incredibly fast, as well as its memory management and use of pointer over references. It constantly outdoes other interpretive and dynamic languages.
But, C++ is an undeniable beast at performance.
I wasn’t kidding earlier when I said C++ is a drawn-out, complex, and lengthy language, but this is where it all pays off. Because it’s a mid-level language and not heavily abstracted from machine code, the information and task you’re trying to communicate to the computer are understood more easily, resulting in stronger performance.
Features that make Go fun and easy to use, like the garbage collector, end up adding drag to the performance time, whereas C++’s minimalist and traditional structure makes it perfect for boosting performance.
Golang vs C++: Which Has Better Security?
Programming languages are either built for power or safety, and if C++ offers better performance, then you can probably guess which language has the better security.
C++ is notorious for suffering from buffer overflows.
Buffers are memory storage containers that hold the information and data while it transfers between locations, and when you put too much information in it, you get a buffer overflow. This is when the information spills over and gets written on adjacent memory locations.
Now, this may not sound too bad, except this anomaly can cause the program to crash and create holes in even airtight systems.
Buffer overflows aren’t naturally a part of C++, but it’s an easy mistake for coders to make if they’re not careful. What gives Go the advantage here is its limitations in the code that prevent this from happening. It doesn’t give coders the option to buffer overflow.
For instance, with Go, you can’t use pointer arithmetic, meaning you can’t step through arrays using pointer values, you have to access them using an index. This forces you to use methods that include checks and bounds, that prevent overflows.
Advantages of Go vs C++ for Experienced Programmers
Go vs C++: Which is higher paid?
According to the 2020 Stack Overflow Survey, in the United States, Go developers earn $140,000 per year — making it the second-highest-paid language in the US, and third in the world.
In contrast, C++ developers earn $120,000, a whole $20K lower than Go developers, and good enough only for 13th place on the highest-paid languages list.
Conclusion: Go is better than C++ for earning higher salaries.
Which is more loved by programmers?
In the same survey, programmers ranked Golang 5th for the most loved programming language, whereas C++ sits at number 8 for the most dreaded.
I argue part of this is attributed to Go’s compact language and easy-going learning curve. Golang may be C-inspired, but it brings a level of readability that C++ can’t compete with.
However, C++ is a powerful language that’s perfect for experienced programmers who want to create everything. Its unlimited capability is one of the big reasons it’s still so popular today even after 40 years! It gives experienced coders the advantage of in-depth control over the program.
Conclusion: Programmers tend to prefer Golang over C++.
Is Go or C++ better for your coding project?
C++ is mostly used in system programming and graphic-heavy software, like video games and photo and movie editing, where access to every nook and cranny of a system and fast rendering and processing is an absolute necessity.
Oppositely, Go is a safe system that gives experienced programmers a user-friendly coding experience and less liability when it comes to large-scale projects.
Golang is heavily used for back-end web development and known for its robust ability to handle extensive network servers and systems. It’s a scalable, clean and straightforward language that was specifically built to solve the issues Google had when it came to working on their large network servers.
With such different strengths, the real advantage for experienced programmers is to learn both, as together they will give you a well-rounded skillset.
Conclusion: for infrastructure and large systems, Go wins. For creating games, applications and other powerful systems, consider C++.
Golang vs C++: The Final Verdict
The final verdict is … it’s up to you!
Go and C++ are two amazing languages that operate at opposite ends of the programming spectrum. C++ is an old-timer that handles the small details, while Golang is contemporary and meant for the big picture.
C++ is perfect for traditionalists that like to get their hands dirty in code and work without bounds and have the skill to do so. It’s a strong and versatile language that gives direct access to a program’s core.
Golang is the modern person’s language. People from all kinds of backgrounds are making the shift to tech, and Go welcomes them with open arms. It’s easy to use and has a scalable nature that promises a fruitful career to anyone using it.
We’re big fans of Go at Qvault, so much so that we’ve created three courses to help you learn Go! No matter your skill level, our two Go Mastery courses will get you the skills you need to work as a Go programmer, and once you’ve got the skills, our Go Interview Prep course will get you prepped to land that job!
Overall, to figure out which one is best, you need to figure which one are you. No matter the choice, Golang and C++ only continue to grow in popularity and will benefit you way into the future.
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article, please let me know so I can get it corrected!
from Qvault https://ift.tt/36vxejv
0 notes
qvault · 3 years
Text
Beautiful Language and Beautiful Code
The post Beautiful Language and Beautiful Code first appeared on Qvault.
“Dead Poet’s Society” is a classic film, and has become a recent favorite of mine. There’s a scene in particular that I enjoy, where Robin William’s character explains that it’s bad practice to use terms like “very tired” or “very sad”, instead we should use descriptive words like “exhausted” or “morose”!
youtube
I wholeheartedly agree with what’s being taught to the students in this scene. It’s tiresome to read a novel where the author drones on within the bounds of a lackluster vocabulary. This brings me to the point I wanted to emphasize in this short article:
Beautiful language and beautiful code are far from the same.
Beautiful language doesn’t simply communicate instructions from one human to another. Language well-used arouses emotions, illustrates scenery, exposes nuance, and can sing through rhyme and meter. Its purpose isn’t purely functional, it’s a rich medium of creative expression.
Beautiful code, at least by my standards, is purely functional. Its goal is to communicate exactly what it does. Emotion, motif, and narrative be damned. Beautiful code should be written so that machines carry out the instructions as efficiently as possible, and humans grok the instructions as easily as possible. The ideal piece of code is perfectly efficient and can be understood by any human that reads it.
Why shouldn’t code be more like its more expressive counterpart?
If you’re a part of /r/shittyprogramming on Reddit, you may have noticed several weeks back when the community became interested in writing the most ridiculous and inefficient way to calculate whether or not a given number is even. Here are some highlights.
const isEven = n => 'x'.repeat(n).replace(/xx/g, '') === '';
Code language: JavaScript (javascript)
source
function isEven(number) { if (0 == number) { return true; } else if (number < 0) { //I actually don't remember if JS has an absolute value function, return !isEven(number+1); // so this is how we handle negative numbers } else { return !isEven(number-1); } }
Code language: JavaScript (javascript)
source
#include <stdio.h> #include <unistd.h> #include <stdlib.h> char isEvenFile() { while (access("/tmp/isEven", F_OK)) ; //We have to wait until the other process created the file FILE *comms = fopen("/tmp/isEven", "r"); int c = EOF; while (c == EOF) c = fgetc(comms); //In case we were so fast that the other process didn't write to the file for (;;) { int newC = fgetc(comms); if (newC != ' ') //the number has been sent c = newC; else { FILE *out = fopen("/tmp/out", "w+"); switch (c) { case '0': case '2': case '4': case '6': case '8': fprintf(out, "b"); break; default: fprintf(out, "a"); //printing a null char would be the end of the string. break; } fflush(out); break; } } fclose(comms); exit(0); } char isEven(int n) { char input[10]; sprintf(input, "%d", n); int pid = fork(); if (pid == -1) return 2; //error if (pid == 0) { isEvenFile(); } else { FILE *comms = fopen("/tmp/isEven", "w+"); fprintf(comms, "%d ", n); fflush(comms); //send the number to stdin of the child while (access("/tmp/out", F_OK | R_OK)) ; FILE *out = fopen("/tmp/out", "r"); int result = EOF; while (result == EOF) result = fgetc(out); //Again, we have to wait until the other process is done result = result == 'b'; fclose(comms); fclose(out); remove("/tmp/isEven"); remove("/tmp/out"); return (char) result; } }
Code language: C++ (cpp)
Source
One Redditor went so far as to apply machine learning to the problem and annotate an “isEven” training set.
My point with all this “isEven” nonsense is that code can be fun, interesting, and entertaining – I’m not trying to say it can’t be. I’m doing some mental gymnastics, however, in that I define all these “jokes through code” as normal language. It’s a medium through which humans express themselves creatively to one another, just like film, poetry, novels, or blogging.
None of the examples above are actually intended to run in production. If they were, they would be examples of ugly code indeed.
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
from Qvault https://ift.tt/3qAdEMh
0 notes
qvault · 3 years
Text
Intro to the One-Time Pad Cipher
The post Intro to the One-Time Pad Cipher first appeared on Qvault.
In cryptography, the one-time pad, or OTP is a way of encrypting information so securely that it’s impossible to be cracked. That said, OTP has a major drawback in that it requires both parties to have access to the same key before a message is encrypted.
Sorry to interrupt! I just wanted to mention that you should check out my new free Go cryptography course. It’s designed to teach you all the crypto fundamentals you’ll need to get started in cybersecurity.
Start Cryptography Course
How the one-time pad cipher works
When using the one-time pad, a message and a secret key are required to start. Each bit of the original messageg, assuming we can use binary data, is encrypted by using an XOR operation on it and the corresponding bit from the secret key.
Refresher on XOR
XOR, or “exclusive or” is a binary operator that works with binary data. It returns true if both of its inputs are opposites (one false and one true), otherwise, it returns false.
true XOR false = true false XOR true = true true XOR true = false false XOR false = false
Code language: PHP (php)
Check out my other article, why exclusive or is important in cryptography, if you want more information.
One-time pad step-by-step
So, for example, if we start with the message “hello word” and the key “I not know”, first we’d covert the text to binary data.
hello world = 01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01100100 I not know = 01001001 00100000 01101110 01101111 01110100 00100000 01101011 01101110 01101111 01110111
Next, we’ll perform the XOR operation on all the data.
01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01100100 XOR 01001001 00100000 01101110 01101111 01110100 00100000 01101011 01101110 01101111 01110111 = 00100001 01000101 00000010 00000011 00011011 00000000 00011100 00000001 00011101 00010011
Code language: PHP (php)
The resulting binary data is now the “cipher text”. In order to convert it back, all we need to do is XOR the ciphertext with the key and we’ll get the original message back.
00100001 01000101 00000010 00000011 00011011 00000000 00011100 00000001 00011101 00010011 XOR 01001001 00100000 01101110 01101111 01110100 00100000 01101011 01101110 01101111 01110111 = 01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01100100
Code language: PHP (php)
Convert the result back to text and we have the original message decrypted.
01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01100100 = hello world
Perfect secrecy in the one-time pad
A cipher is said to have perfect security if an attacker who has access to only the ciphertext can infer absolutely nothing of interest about the plaintext. The one-time pad does have perfect security. That said, it only has perfect security if the following conditions can be met:
The key must be at least as long as the plaintext
The key must never be reused
The key must be kept completely secret to the outside world yet shared by both parties
The key must have a uniform distribution that is independent of the plaintext
The Caesar cipher is a great example of a cipher that is not perfectly secure or practically secure. As we demonstrated earlier, when given access to the ciphertext of a Caesar cipher, an attacker can see the positions and patterns of characters in the plaintext.
Issues using the one-time pad in production
Most production ciphers are not perfectly secure, but are “close enough”. In short, trade-offs are made that add to the practical security of a system while sacrificing the perfect theoretical security of the cipher itself.
In accordance with the requirements outlined above, it’s really hard to implement a secure one-time pad in a real-world system. Let’s look at the first requirement, that the key needs to be at least as long as the plaintext it encrypts. This means that if I want to encrypt the contents of my computer’s hard drive, I need a key that’s hundreds of gigabytes in length. There’s no way I’ll remember that key, let alone be able to write it down.
The second requirement, that the key can’t be reused, is a huge pain! This means memorizing keys is out of the question because I always need a new one. Not only that, but whatever security vulnerabilities are introduced by needing to communicate a shared key to my intended recipient will be repeated each time a new message is sent.
Lastly, the last requirement, that it must be kept secret yet somehow communicated to the intended recipient, is a tall order. In fact, all symmetric encryption algorithms suffer from this problem. As a result, if you need to communicate with another entity you probably need to use a separate asymmetric encryption scheme.
Example of the one-time pad code in Golang
func encrypt(plaintext, key []byte) []byte { final := []byte{} for i := range plaintext { final = append(final, plaintext[i]^key[i]) } return final } func decrypt(ciphertext, key []byte) []byte { final := []byte{} for i := range ciphertext { final = append(final, ciphertext[i]^key[i]) } return final }
Code language: Go (go)
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
from Qvault https://ift.tt/3hdj37I
0 notes
qvault · 3 years
Text
16 Great Coding Challenges You Can Try Out
The post 16 Great Coding Challenges You Can Try Out first appeared on Qvault.
Coding challenges are a fun way to improve your coding quickly.
When I started to learn coding in school, coding challenges were the furthest thing from my mind. In fact, I was struck with one particular issue: I didn’t really want to learn to code. I didn’t care enough about coding. I didn’t care about the language. I wanted to get a decent grade and get out.
Like a lot of other coders, I’m competitive by nature, but only when it suits me. I need a reason to care. That’s why one of my earliest coding successes was a personal coding challenge. Could I get a python bot up and running? If so, the reward was more Instagram followers for my cats.
Suddenly, I was motivated to trawl through error code explanations, figure out the best libraries, and read through dozens of stackoverflow answers. 
Coding challenges are a great way to give yourself a reason to pick up a new coding language, whether you’re looking for interview coding challenges or specific languages like Python or Javascript coding challenges. This list of 16 online coding challenges will motivate you to learn, investigate, and finish something, with an actual possible reward at the end.
Language-Specific Coding Challenges
Before you dive into these sixteen challenges, it’s worth thinking about what the purpose. If you want to secure a specific job, language challenges like these below will be helpful, but not the end-all-be-all — you’d be better off doing a more holistic challenge.
But if you’re just keen to test yourself on your Go mastery, for example, then language-based challenges like these are best.
Javascript
This challenge, which is a set of 26 exercises, is a perfect Javascript coding challenge for beginners. It doesn’t require any fancy Javascript coding knowledge and is designed to be solvable for beginners using simple, classic Javascript programming elements. It comes with the solutions, too – but make sure you actually try to solve them before peeking!
When you’re done with the first set, ITbulls also offers a second Javascript coding challenge set, aimed at intermediate coders. 
These aren’t time sensitive. You can do them one per day, or set up a marathon session and time yourself – whatever works for you. The only person you have to be accountable to is yourself.
Go
Go, also known as Golang, is a coding language built for purpose by Google. This Go coding challenge, by Golangr, runs you through a lot of the typical aspects of Go, including naming conventions and Goroutines. 
It’s specifically created for beginners but if you’re an intermediate Gopher, why not do a time trial through these challenges and see how many best practices you still remember?
This Go coding challenge asks you to complete specific exercises, and then you can click on each prompt to reveal a thorough runthrough of the recommended method.
Sorry to interrupt! I just wanted to mention that you should check out my new free Go course. It’s designed to teach you all the fundamentals of my favorite coding language.
Learn Golang Now
Java
Java (not to be confused with Javascript) is a pretty powerful general purpose coding language. Java Coding Monk offers a list of articles that walk through various problems and the solutions in an article format. To challenge yourself, why not try to see how many you can solve within an hour? 
The cool thing about Java Code Monk’s Java coding challenges is that they often offer multiple approaches. Unlike languages like Go, which have a limited syntax and only one way to accomplish tasks, Java is more flexible.
Being able to see the different possible paths to solutions can be really helpful for challenging your Java coding skills. Another way to learn from these Java coding challenges is to see if you can figure out more than one way to get to the answer before reading the article for the solution.
C++
The best coding challenges for C++ are on a site called Hackerrank, which I’ll also dive into a little lower down in this article. Hackerrank’s C++ coding challenges are great because they give you a ton of information up front on the coding challenge.
You can see the difficulty score, what percentage of coders solve it, and how many points you’ll be able to get for solving it.
But the really cool thing is how interactive it is with the coding community.
Not only can you view the submissions and solutions of other programmers, but there’s also a discussion section where folks can complain about the wording of a prompt, help each other out, and just collaborate on these coding challenges.
Finally, each challenge comes with an official Editorial Solution so you can see the correct answer from the staff.
Python
Python Principles offers a comprehensive set of Python coding challenges perfect for beginners. This resource is great because it is mobile-friendly, meaning you can complete these on the go.
Plus, they have two levels of help – a hint, and then the solution.
This is great when you can’t for the life of you figure out which direction to go in, but you don’t want the answer right away. It also helps you learn properly.
Ascending in difficulty, completing these Python coding challenges can help you get to grips with this awesome language. 
For-purpose Coding Challenges
While coding challenges are a great way to learn and brush up on your skills in a particular coding language, programmers might have other reasons to practice coding challenges. 
For interviews
It doesn’t matter if you’re in your twentieth year of coding or you’re aiming for an entry-level programming job: you’ll be subjected to the coding interview.
These often don’t rely on a specific language, as many jobs ask that you code in more than one discipline.They’re usually problem-oriented instead, meaning you’ll be asked to figure out the best way to solve X problem. Rather than looking for a right answer, they’re making sure you know how to think analytically under pressure.  
I loved these programming challenges for the coding interview because they reflect a lot of the research I did – they look not just for your ability to code, but your ability to think. It also includes some interesting back-and-forth discussion beneath some of the questions that can really help you understand what hiring managers are looking for.
For beginners
No matter what language you’re working in, there will be a core set of skills you should know in order to pass muster, like printing “hello world.” That’s why I adore Adriann’s Simple Programming Problems for being language agnostic.
These serve as a simple set of coding challenges for beginners (including the classic “hello world”) all the way up to advanced, like writing a program that plays Hangman.
No matter what your level, language, or job, you’ll be able to find value challenging yourself to complete these coding challenges.
The downside is because they’re so generic, there’s no written solution or troubleshooting. You’ll have to use Google and a hefty dose of patience to get the right answer to your problem.
Company Coding Challenges
And then there are so many employers who are famous for their company coding challenges and interviews that they get their very own section.
If you want to get a programming job at Google, you should look at Google’s programming challenges. As of today, their Kick Start coding challenge is still open for registration. 
IBM’s coding challenge Call for Code is similar – it’s a once-early program with awesome rewards like $200,000 for the winner. It’s a huge challenge, asking participants to solve very real-world problems, but it’s a great way to stretch.
Other companies like Amazon don’t hold open coding challenges like Google does, but it’s an integral part of their interview process, enough so that platforms like StrataScratch have compiled a list of example questions that serve as an Amazon coding challenge.
J.P. Morgan’s coding challenge is called the Code for Good hackathon event, but it’s a holistic event. You go in-person to “work alongside our technology experts in teams to solve real-world problems for nonprofits,” according to their website. It’s definitely a coding challenge, but not one for the casual coder. 
More places to look for coding challenges
This is far from a comprehensive list of coding challenges, so I’ve listed some best coding challenge websites below that will often have more coding challenges whatever your coding need is.
Hackerrank offers a ton of coding challenges on a rolling basis. It also lets you look at previous coding competitions so you can learn from the archives. 
Topcoder is a similar website to Hackerrank, and is a great coding challenge website. The cool thing about Topcoder is you can filter by career track if you want, like data scientist or QA.
Coderbyte is a very career-oriented coding challenge platform, built specifically to help programmers get a job. Some of the completed coding challenges come with video solutions, which can be really helpful. 
Project Euler is less career-focused, and more about challenging your understanding of basic computer science principles. The challenges there serve as a great baseline for your fundamentals.
Exercism.io helpfully breaks challenges down by language, so you can choose if you want a Python coding challenge, one for Julia, or any of their other 50 language tracks.
Coding challenges are a great way to boost your skills
Maybe you’re doing it for fun. Maybe you’re doing it to polish your language skills. Maybe you’re trying to get a job. No matter what your need, these coding challenges are a great resource to help motivate you to accomplish whatever it is you’re trying to do with coding. 
I know when I was learning to code, challenges were instrumental in helping me not just get started, but actually finish what I was doing.
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
from Qvault https://ift.tt/3qpTTag
0 notes
qvault · 3 years
Text
Building a Red-Black Binary Tree in Python
The post Building a Red-Black Binary Tree in Python first appeared on Qvault.
A red-black tree is a kind of self-balancing binary search tree. Each node stores an extra bit, which we will call the color, red or black. The color ensures that the tree remains approximately balanced during insertions and deletions. When the tree is modified, the new tree is rearranged and repainted to restore the coloring properties that constrain how unbalanced the tree can become in the worst case.
The purpose of a red-black tree is to stay balanced which ensures that its common operations, like lookup and delete, never degrade to worse than O(n*log(n)).
Sorry to interrupt! I just wanted to mention that you should check out my new free Python course, “Big-O Data Structures”. You’ll learn all you need to know to crush your upcoming coding interviews and whiteboard sessions.
Start Python Data Structures Course
What is a balanced binary tree?
Since the reason colors are added to a binary tree is to ensure that it remains balanced, we need to understand how and why a binary tree is balanced. To put it simply, a balanced tree’s branches differ in height by no more than 1.
The following tree is balanced because between its two branches one has a height of 2, and the other 3, meaning they differ by no more than 1.
A / \ B C / D
The next tree is unbalanced because it’s branches differ in height by more than 1. C‘s right side has a height of 2 while its left side has a height of 4).
A / \ B C / / D E / G
Why do we want balanced trees?
Balanced binary search trees ensure speed. The speed of an operation in a binary tree depends on the height of the tree. If the tree is balanced, then the height is only the log of the number of nodes, which means the tree will work as fast as possible. However, if the tree is unbalanced, for example with one really long branch, then the height because the total number of nodes rather than the log.
A / B / C / D
Properties of a red-black tree
In addition to all the properties of a Binary Search Tree, a red-black tree must have the following:
Each node is either red or black
The root is black. This rule is sometimes omitted. Since the root can always be changed from red to black, but not necessarily vice versa, this rule has little effect on analysis.
All nil leaf nodes are black.
If a node is red, then both its children are black.
All paths from a single node go through the same number of black nodes in order to reach any of its descendant nil nodes.
Implementing a Red-Black Tree in Python
Step 1 – RBNode Class
Our implementation will use a Tree class and a Node class. The Node will be fairly simple, it’s just a constructor.
class RBNode: def __init__(self, val): self.red = False self.parent = None self.val = val self.left = None self.right = None
Code language: Python (python)
Step 2 – RBTree Class
Next let’s create a tree class with a constructor.
class RBTree: def __init__(self): self.nil = RBNode(0) self.nil.red = False self.nil.left = None self.nil.right = None self.root = self.nil
Code language: Python (python)
Step 3 – Insert method
def insert(self, val): # Ordinary Binary Search Insertion new_node = RBNode(val) new_node.parent = None new_node.left = self.nil new_node.right = self.nil new_node.red = True # new node must be red parent = None current = self.root while current != self.nil: parent = current if new_node.val < current.val: current = current.left elif new_node.val > current.val: current = current.right else: return # Set the parent and insert the new node new_node.parent = parent if parent == None: self.root = new_node elif new_node.val < parent.val: parent.left = new_node else: parent.right = new_node # Fix the tree self.fix_insert(new_node)
Code language: Python (python)
The insert method will look a lot like a traditional binary tree insert method. The biggest difference is that after doing an insert, we’ll call a special fix_insert method. For now just call it, we’ll implement it in just a moment.
Step 4 – Rotate left
We’ll need some rotation methods in our “fix” step that’s coming up. Let’s code those now.
# rotate left at node x def rotate_left(self, x): y = x.right x.right = y.left if y.left != self.nil: y.left.parent = x y.parent = x.parent if x.parent == None: self.root = y elif x == x.parent.left: x.parent.left = y else: x.parent.right = y y.left = x x.parent = y
Code language: Python (python)
Step 5 – Rotate right
# rotate right at node x def rotate_right(self, x): y = x.left x.left = y.right if y.right != self.nil: y.right.parent = x y.parent = x.parent if x.parent == None: self.root = y elif x == x.parent.right: x.parent.right = y else: x.parent.left = y y.right = x x.parent = y
Code language: Python (python)
Step 6 – Fix insert
The real bread and butter is in this step, it’s what makes a red-black tree balanced.
def fix_insert(self, new_node): while new_node != self.root and new_node.parent.red: if new_node.parent == new_node.parent.parent.right: u = new_node.parent.parent.left # uncle if u.red: u.red = False new_node.parent.red = False new_node.parent.parent.red = True new_node = new_node.parent.parent else: if new_node == new_node.parent.left: new_node = new_node.parent self.rotate_right(new_node) new_node.parent.red = False new_node.parent.parent.red = True self.rotate_left(new_node.parent.parent) else: u = new_node.parent.parent.right # uncle if u.red: u.red = False new_node.parent.red = False new_node.parent.parent.red = True new_node = new_node.parent.parent else: if new_node == new_node.parent.right: new_node = new_node.parent self.rotate_left(new_node) new_node.parent.red = False new_node.parent.parent.red = True self.rotate_right(new_node.parent.parent) self.root.red = False
Code language: Python (python)
Full Example of Red-Black Tree in Code
import random class RBNode: def __init__(self, val): self.red = False self.parent = None self.val = val self.left = None self.right = None class RBTree: def __init__(self): self.nil = RBNode(0) self.nil.red = False self.nil.left = None self.nil.right = None self.root = self.nil def insert(self, val): # Ordinary Binary Search Insertion new_node = RBNode(val) new_node.parent = None new_node.left = self.nil new_node.right = self.nil new_node.red = True # new node must be red parent = None current = self.root while current != self.nil: parent = current if new_node.val < current.val: current = current.left elif new_node.val > current.val: current = current.right else: return # Set the parent and insert the new node new_node.parent = parent if parent == None: self.root = new_node elif new_node.val < parent.val: parent.left = new_node else: parent.right = new_node # Fix the tree self.fix_insert(new_node) def fix_insert(self, new_node): while new_node != self.root and new_node.parent.red: if new_node.parent == new_node.parent.parent.right: u = new_node.parent.parent.left # uncle if u.red: u.red = False new_node.parent.red = False new_node.parent.parent.red = True new_node = new_node.parent.parent else: if new_node == new_node.parent.left: new_node = new_node.parent self.rotate_right(new_node) new_node.parent.red = False new_node.parent.parent.red = True self.rotate_left(new_node.parent.parent) else: u = new_node.parent.parent.right # uncle if u.red: u.red = False new_node.parent.red = False new_node.parent.parent.red = True new_node = new_node.parent.parent else: if new_node == new_node.parent.right: new_node = new_node.parent self.rotate_left(new_node) new_node.parent.red = False new_node.parent.parent.red = True self.rotate_right(new_node.parent.parent) self.root.red = False def exists(self, val): curr = self.root while curr != self.nil and val != curr.val: if val < curr.val: curr = curr.left else: curr = curr.right return curr # rotate left at node x def rotate_left(self, x): y = x.right x.right = y.left if y.left != self.nil: y.left.parent = x y.parent = x.parent if x.parent == None: self.root = y elif x == x.parent.left: x.parent.left = y else: x.parent.right = y y.left = x x.parent = y # rotate right at node x def rotate_right(self, x): y = x.left x.left = y.right if y.right != self.nil: y.right.parent = x y.parent = x.parent if x.parent == None: self.root = y elif x == x.parent.right: x.parent.right = y else: x.parent.left = y y.right = x x.parent = y def __repr__(self): lines = [] print_tree(self.root, lines) return '\n'.join(lines) def print_tree(node, lines, level=0): if node.val != 0: print_tree(node.left, lines, level + 1) lines.append('-' * 4 * level + '> ' + str(node.val) + ' ' + ('r' if node.red else 'b')) print_tree(node.right, lines, level + 1) def get_nums(num): random.seed(1) nums = [] for _ in range(num): nums.append(random.randint(1, num-1)) return nums def main(): tree = RBTree() for x in range(1, 51): tree.insert(x) print(tree) main()
Code language: Python (python)
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
from Qvault https://ift.tt/3zS4MpF
0 notes
qvault · 3 years
Text
Quick Sort in Golang
The post Quick Sort in Golang first appeared on Qvault.
Quicksort is an efficient sorting algorithm that’s widely used in production sorting implementations. Like merge sort, quick sort is a divide and conquer algorithm. True to its name, quicksort is one of the fastest sorting algorithms, that said, you need to be careful with the implementation details because if you’re not careful the speed can degrade quickly.
Sorry to interrupt! I just wanted to mention that you should check out my new free algorithms course. You’ll learn the basics of Big O notation while writing awesome code in the Go programming language.
Learn Big O Algorithms Now
Divide
Select a pivot element that will preferably end up close to the center of the sorted pack
Move everything onto the “greater than” or “less than” side of the pivot
The pivot is now in its final position
Recursively repeat the operation on both sides of the pivot
Conquer
Return a sorted array after all elements have been through the pivot operation
Quicksort Pseudocode
Partition() function in Golang
Quicksort actually makes use of two functions, the main quicksort() function as well as the partition() function. The meat of the algorithm counter-intuitively lives in the partition() function. It’s responsible for finding the pivot and moving everything to the correct side of the pivot.
In Go, the complete code would look like this.
func partition(arr []int, low, high int) ([]int, int) { pivot := arr[high] i := low for j := low; j < high; j++ { if arr[j] < pivot { arr[i], arr[j] = arr[j], arr[i] i++ } } arr[i], arr[high] = arr[high], arr[i] return arr, i }
Code language: Go (go)
QuickSort() function in Golang
The quickSort() function is really just a wrapper around the partition function, and it handles the recursive nature of the algorithm.
func quickSort(arr []int, low, high int) []int { if low < high { var p int arr, p = partition(arr, low, high) arr = quickSort(arr, low, p-1) arr = quickSort(arr, p+1, high) } return arr }
Code language: Go (go)
Example of using Quicksort in real code
fmt.Println(quickSortStart([]int{5, 6, 7, 2, 1, 0)) // prints // [0, 1, 2, 5, 6, 7]
Code language: Go (go)
Why use Quicksort?
On average, quicksort has a Big O of O(n*log(n)). In the worst case, and assuming we don’t take any steps to protect ourselves, it can break down to O(n^2). The partition() function has a single for-loop that ranges from the lowest index to the highest index in the array. By itself, the partition() function is O(n). The overall complexity of quicksort is dependent on how many times partition() is called.
In the worst case, the input is already sorted. An already sorted array results in the pivot being the largest or smallest element in the partition each time. When this is the case, partition() is called a total of n times. In the best case, the pivot is the middle element of each sublist which results in log(n) calls to partition().
Quick sort has the following properties.
Very fast in the average case
In-Place: Saves on memory, doesn’t need to do a lot of copying and allocating
More complex implementation
Typically unstable: changes the relative order of elements with equal keys
Ensuring a fast runtime in Quicksort
While the version of quicksort that we implemented is almost always able to perform at speeds of O(n*log(n)), it’s Big O complexity is still technically O(n^2). We can fix this by altering the algorithm slightly. There are two approaches:
Shuffle input randomly before sorting. This can trivially be done in O(n) time.
Actively find the median of a sample of data from the partition, this can be done in O(1) time.
Random shuffling optimization
The random approach is easy to code, works practically all of the time, and as such is often used. The idea is to quickly shuffle the list before sorting it. The likelihood of shuffling into a sorted list is astronomically unlikely, and is also more unlikely the larger the input.
Finding the median optimization
One of the most popular solutions is to use the “median of three” approach. Three elements (for example: the first, middle, and last elements) of each partition are chosen and the median is found between them. That item is then used as the pivot. This approach has the advantage that it can’t break down to O(n^2) time because we are guaranteed to never use the worst item in the partition as the pivot. That said, it can still be slower because a true median isn’t used.
Ready to get coding?
Try our coding courses free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
from Qvault https://ift.tt/3cR5zNE
0 notes
qvault · 3 years
Text
How to Write Insertion Sort in Go
The post How to Write Insertion Sort in Go first appeared on Qvault.
Insertion sort builds a final sorted list one item at a time. It’s much less efficient on large lists than more advanced algorithms like quicksort or merge sort. Insertion sort is a simple algorithm that works just like you would arrange playing cards in your hands. A slice is first split into sorted and unsorted sections, then values from the unsorted section are inserted into the correct position in the sorted section.
Full example of the insertion sort algorithm
func insertionSort(arr []int) []int { for i := 0; i < len(arr); i++ { for j := i; j > 0 && arr[j-1] > arr[j]; j-- { arr[j], arr[j-1] = arr[j-1], arr[j] } } return arr }
Code language: Go (go)
Sorry to interrupt! I just wanted to mention that you should check out my new free Go course. It’s designed to teach you all the fundamentals of my favorite coding language.
Learn Golang Now
As you can see, the insertionSort() function starts by iterating over the entire slice in a nested for loop. The job of the inner for loop is to consume one value for each repetition, and grow the sorted output list, which are all the elements before index i. At each repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted first section, and inserts it there. It repeats until no input elements remain.
Using insertion sort in code
func main() { fmt.Println(insertionSort([]int{5,3,2,1,0,4)) // prints // [0, 1, 2, 3, 4, 5] }
Code language: Go (go)
Why use insertion sort?
Insertion sort has a Big O complexity of O(n^2), because that is its worst-case complexity. The outer loop of insertion sort executes n times, while the inner loop depends on the input. In the worst case (a reverse sorted array) the inner loop executes n times as well. In the best case (a sorted array) the inner loop immediately breaks resulting in a total complexity of O(n).
Like bubble sort, the algorithm is just too slow for general-purpose production use, but can be a great learning tool. Here are some additional properties of insertion sort.
Simple implementation, easy to write
Fast for very small data sets
Faster than other simple sorting algorithms like Bubble Sort
Adaptive: Faster for partially sorted data sets
Stable: Does not change the relative order of elements with equal keys
In-Place: Only requires a constant amount of memory
Online: Can sort a list as it receives it
Some production sorting implementations use merge sort for very small inputs under a certain threshold (very small, like 10-ish). Insertion sort is better for very small lists than some of the faster algorithms because:
There is no recursion overhead
Tiny memory footprint
It’s a stable sort as described above
Ready to take action and get coding?
Try out our coding courses for free
Join our Discord community
Have questions or feedback?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
from Qvault https://ift.tt/35hysOy
0 notes
qvault · 3 years
Text
Merge Sort in Golang with Examples
The post Merge Sort in Golang with Examples first appeared on Qvault.
Merge sort is a recursive sorting algorithm and, luckily for us, it’s quite a bit faster than bubble sort. Merge sort is a divide and conquer algorithm.
Divide
Divide the input slice into two (equal) halves
Recursively sort the two halves
Conquer
Merge the two halves to form a sorted array
Sorry to interrupt! I just wanted to mention that you should check out my new free Go course. It’s designed to teach you all the fundamentals of my favorite coding language.
Learn Golang Now
Full example of the merge sort algorithm
Merge sort actually has two functions involved, the recursive mergeSort function, and the merge function.
Let’s write the mergeSort() function first. It’s a recursive function, which means it calls itself, and in this case, it actually calls itself twice. The point of the mergeSort function is to split the array into two roughly equal parts, call itself on those parts, then call merge() to fit those halves back together.
func mergeSort(items []int) []int {     if len(items) < 2 {         return items     }     first := mergeSort(items[:len(items)/2])     second := mergeSort(items[len(items)/2:])     return merge(first, second) }
Code language: HTML, XML (xml)
The merge() function is used for merging two sorted lists back into a single sorted list, its where the “magic” really happens. At the lowest level of recursion, the two “sorted” lists will each have a length of 1. Those single element lists will be merged into a sorted list of length two, and we can build of from there.
func merge(a []int, b []int) []int {     final := []int{}     i := 0     j := 0     for i < len(a) && j < len(b) {         if a[i] < b[j] {             final = append(final, a[i])             i++         } else {             final = append(final, b[j])             j++         }     }     for ; i < len(a); i++ {         final = append(final, a[i])     }     for ; j < len(b); j++ {         final = append(final, b[j])     }     return final }
Code language: PHP (php)
Using the algorithm in code
func main() { unsorted := []int{10, 6, 2, 1, 5, 8, 3, 4, 7, 9}     sorted := mergeSort(unsortedInput) // sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }
Code language: JavaScript (javascript)
Why use merge sort?
Pros
Fast. Merge sort is much faster than bubble sort, being O(n*log(n)) instead of O(n^2).
Stable. Merge sort is also a stable sort which means that values with duplicate keys in the original list will be in the same order in the sorted list.
Cons
Extra memory. Most sorting algorithms can be performed using a single copy of the original array. Merge sort requires an extra array in memory to merge the sorted subarrays.
Recursive: Merge sort requires many recursive function calls, and function calls can have significant resource overhead.
If you need a sorting algorithm to use in a production system, I recommend not reinventing the wheel and using the built-in sort.Sort method.
Merge sort Big-O complexity
Merge sort has a complexity of O(n*log(n)). Don’t be fooled because there aren’t an explicit number of for-loops to count in the code. In merge sort’s case, the number of recursive function calls is important.
Thanks for reading, now take a course!
Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.
Start coding now
Questions?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
Subscribe to my newsletter for more coding articles delivered straight to your inbox.
from Qvault https://ift.tt/3ga87sd
0 notes
qvault · 3 years
Text
Writing Bubble Sort in Go from Scratch
The post Writing Bubble Sort in Go from Scratch first appeared on Qvault.
Bubble sort is named for the way elements “bubble up” to the top of the list. Bubble sort repeatedly steps through a slice and compares adjacent elements, swapping them if they are out of order. It continues to loop over the slice until the whole list is completely sorted.
Full example of the bubble sort algorithm
func bubbleSort(input []int) []int {     swapped := true     for swapped {         swapped = false         for i := 1; i < len(input); i++ {             if input[i-1] > input[i] {                 input[i], input[i-1] = input[i-1], input[i]                 swapped = true             }         }     }     return input }
Using the algorithm in code
func main() { unsorted := []int{10, 6, 2, 1, 5, 8, 3, 4, 7, 9}     sorted := bubbleSort(unsortedInput) // sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }
Why use bubble sort?
Bubble sort is famous for how easy it is to write. It’s one of the slowest sorting algorithms, but can be useful for a quick script or when the amount of data to be sorted is guaranteed to be small. If you need a sorting algorithm to use in a production system, I recommend not reinventing the wheel and using the built-in sort.Sort method.
Bubble sort Big-O complexity
While bubble sort is considered fast and easy to write, its actually one of the slowest sorting algorithms out there. Because bubble sort needs to move through the entire list for each element in the list, which in code is a nested for-loop, bubble sort has a complexity of O(n^2).
Thanks for reading, now take a course!
Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.
Start coding now
Questions?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
Subscribe to my newsletter for more coding articles delivered straight to your inbox.
from Qvault https://ift.tt/34X2Q0P
0 notes
qvault · 3 years
Text
Check for Standards Before Creating a New One
The post Check for Standards Before Creating a New One first appeared on Qvault.
I recently had a ticket opened on my team’s backlog board requesting the ability to bypass our API’s caching system. For context, our front-end team uses my team’s API to make fairly heavy requests to ElasticSearch, and one of the features of our API gateway is to cache the results of heavy aggregations for ~30 seconds. It turns out, every once in a while they need to run two of the same query within the ~30-second caching window and want an updated result set.
The request that was opened read something like, “the API needs a parameter to disable caching for certain queries”. When working in a REST-ish-ful API there are approximately math.MaxInt ways to accomplish that, and some of the first ones that immediately came to mind were:
A ?cache=false query parameter
A resource/no-cache endpoint extension
A cache: false HTTP header
A "cache": false" JSON payload in the body
As it turns out, there’s already a standard for this sort of thing, the Cache-Control request directives.
Cache-Control: max-age=<seconds> Cache-Control: max-stale[=<seconds>] Cache-Control: min-fresh=<seconds> Cache-Control: no-cache Cache-Control: no-store Cache-Control: no-transform Cache-Control: only-if-cached
Using the standard header Cache-Control: no-cache not only makes my job easier by requiring fewer API design decisions but also ensures that my API’s clients aren’t surprised by a new way to accomplish a common task.
I do want to point out, however, that just because you’ve decided to use a fairly well-supported standard, doesn’t mean there aren’t other standards your users will expect. It also doesn’t mean that your users are aware of the existence of the standard you’ve chosen.
https://xkcd.com/927/
Regardless of whether or not you think your API’s behavior is “standard” or “to be expected”, just add the behavior to your docs anyway. For me, the following snippet in our Readme.md was all we needed.
## Cache busting If you don't want your query cached, use the Cache-Control header. Cache-Control: no-cache
Thanks for reading, now take a course!
Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.
Start coding now
Questions?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
Subscribe to my newsletter for more coding articles delivered straight to your inbox.
from Qvault https://ift.tt/34UjgH1
0 notes
qvault · 3 years
Text
How to Properly Use Defer in Golang
The post How to Properly Use Defer in Golang first appeared on Qvault.
What is the “defer” keyword in Go?
In the Go programming language, defer is a keyword that allows developers to delay the execution of a function until the current functions returns. What throws some people off is that the deferred function’s arguments are evaluated immediately, but the function itself doesn’t fire until the wrapping function exits.
Simple defer example – hello world
func main() { defer fmt.Println("world") // deferred until main() exits fmt.Println("hello") } // prints: // hello // world
When would you want to defer something?
After programming in Go, it’s really hard to remember how I dealt with closing connections or files in other languages. The defer statement is a very clean way to deal with any sort of “cleanup” that needs to happen in a function.
resp, err := http.Get(url) if err != nil{ log.Println(err) } defer resp.Body.Close()
In Go’s standard http library, the documentation points out that HTTP responses must be closed by the client when it’s finished. The client must close the response body when finished with it.
In the example above, you might be thinking, “I’ll just close the response when I’m done with it, why should I defer it?”. In my experience, the main reason to use defer is due to Go developers’ liberal use of guard clauses. When a function has many exit points (places where it can return early), you don’t want to prefix every return with a response closure. What if you miss one? Let’s look at an example.
func getUser() (User, error) { resp, err := http.Get("https://example.tld/users") if err != nil{ return User{}, err } dat, err := io.ReadAll(resp.Body) if err != nil { resp.Body.Close() return err } user := User{} err = json.Unmarshal(dat, &user) resp.Body.Close() return user, err }
Notice how resp.Body.Close() needs to be called in two places – at each potential exit point. With defer, we can simply our code.
func getUser() (User, error) { resp, err := http.Get("https://example.tld/users") if err != nil{ return User{}, err } defer resp.Body.Close() dat, err := io.ReadAll(resp.Body) if err != nil{ return err } user := User{} err = json.Unmarshal(dat, &user) return user, err }
Defer, panic and recover – Why you shouldn’t do it
I don’t want to spend too much time on this, but some people have stumbled across Go’s built-in recover() function and thought it might be a good idea to use panic() and recover() like try and catch in other languages.
What is the recover() function in Go?
Simply put, recover is a builtin function that regains control of a panicking goroutine. Recover is only used inside deferred functions. Calling recover() inside a deferred function stops the panicking sequence by and retrieves the error message passed to the panic() function call.
func recoverWithMessage() { if r := recover(); r!= nil { fmt.Println("recovered from", r) } } func fullName(firstName *string, lastName *string) string { defer recoverWithMessage() if firstName == nil { panic("first name cannot be nil") } if lastName == nil { panic("last name cannot be nil") } return fmt.Sprintf("%s %s\n", *firstName, *lastName) } func main() { firstName := "Lane" lastName := "Wagner" fmt.Println(fullName(&firstName, &lastName)) fmt.Println(fullName(nil, nil)) } // prints: // Lane Wagner // recovered from first name cannot be nil
The example above is a complicated and non-idiomatic way to handle runtime problems that would have been better dealt with by just passing error values. I understand that there are definitely edge-cases where use of panic() and recover() might make sense. That said, I’ve been writing Go professionally for about 5 years now and I’ve never felt a sufficient need, especially in application code. Do your best to refactor your project so you can just return errors like the good designers intended.
When are function arguments evaluated?
Unlike other higher-order functions in Go, when you “pass” a function to the defer keyword, you pass an entire function call, not just the name of the function. This allows the function’s arguments to be evaluated immediately. The defer keyword just ensures that the body of the function won’t run until the parent function returns.
func main() { printMath(5, 6, multiply) // the "multiply" function is passed without arguments } // printMath does some math and prints the result func printMath(x, y int, mathFunc func(int, int) int) { fmt.Println(mathFunc(x, y)) } func multiply(x, y int) int { return x * y }
The defer keyword on the other hand does take arguments.
defer fmt.Println(x + y)
x+y evaluates immediately, but doesn’t print until main() exits.
What happens with multiple defer statements?
Deferred function calls are pushed onto a stack data structure. When the parent function returns, all its deferred calls are executed in the reverse order that they were created.
defer fmt.Println("third") defer fmt.Println("second") defer fmt.Println("first") // prints: // first // second // third
Thanks for reading, now take a course!
Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.
Start coding now
Questions?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
Subscribe to my newsletter for more coding articles delivered straight to your inbox.
from Qvault https://ift.tt/34ClCdC
0 notes
qvault · 3 years
Text
How to Properly Use Defer in Golang
"How to Properly Use Defer in Golang" #golang #go #codenewbies
What is the “defer” keyword in Go? In the Go programming language, defer is a keyword that allows developers to delay the execution of a function until the current functions returns. What throws some people off is that the deferred function’s arguments are evaluated immediately, but the function itself doesn’t fire until the wrapping function exits. Simple defer example – hello world func…
Tumblr media
View On WordPress
0 notes
qvault · 3 years
Text
6 Critical Reasons Beginner Programmers Should Learn JavaScript in 2021
The post 6 Critical Reasons Beginner Programmers Should Learn JavaScript in 2021 first appeared on Qvault.
“Why learn JavaScript?” I asked my sister when she was in college and starting to pick up the fundamentals of JavaScript. “Isn’t it ancient? Do people still use it?” 
I was surprised to learn that JavaScript was the most used programming language in 2020, but I shouldn’t have been – it’s held that spot for the past eight years, according to StackOverflow’s developer survey. It’s a really popular language for mobile apps and web development especially. You’re looking at a website built with JavaScript right now. 
As the no-code movement gains a foothold, beginner programmers might wonder why they learn JavaScript at all, given there are endless numbers of JavaScript frameworks providing ready-to-use code, and many websites and apps can be built entirely free of code.
To those naysayers, I will only say that it’s always worth understanding how something works before you start taking shortcuts. And JavaScript, of all the languages I frequently write about, is one of the languages most likely to outlive any fads. It’s used by 94.5% of all websites, and the world wide web isn’t going anywhere. When I asked her “Why learn JavaScript?” I didn’t know the extent of its influence. 
Now, a bit wiser, I know there are several good answers to why beginner programmers especially should learn JavaScript. They revolve around how easy it is to get started – and to keep going, crucially; how learning JavaScript can help your programming career flourish; and the practical advantages of JavaScript over other languages. 
Let’s get into six reasons why you, a beginner programmer, should learn JavaScript. 
1. You’ll be a popular hire in whatever you want to do.
Getting a job in programming is the absolute number one reason you should learn JavaScript. It’s been pretty well-documented that computer science graduates are among the most sought-after of grads. So much so that it’s actually increasingly common to get a programming job without a degree at all. Companies need more employees that can code than are currently graduating from college. 
Out of all the coding languages, JavaScript coders are close to the top of that list, and for good reason. “Mastering this key programming language could see you go on to work in full-stack development, games development, information security software engineering, machine learning, and artificial intelligence,” writes Emily Stevens in CareerFoundry. It’s versatile for hobbies and for employers. 
This demand explains why you should learn JavaScript: 72% of companies are looking for a JavaScript coder. As a JavaScript developer, the median wage in the US is around $112k per year. 
Even if you don’t want to program websites or apps for a career, being able to create your own website with JavaScript in order to host your portfolio can be a huge help in your job hunt. 
2. It makes you a versatile programmer.
JavaScript is kind of a lingua franca among coding languages. If you know how to code in JavaScript, there’s no cap to the kind of cool stuff you can program. JavaScript gained a foothold by helping developers code on the client-side (frontend) of websites, but recently, there have been additions to the JavaScript frameworks that make it a great language for coding on the server-side or backend of websites using Node.js. 
“Javascript everywhere’ (i.e. node.js) has really become the default web-development paradigm,” writes Tom Critchlow in his blog post on web browsers. His answer to why you should learn JavaScript is simply that it’s a language with a can-do attitude, no matter what you want to do with it.
Plus, you can get in on some app action, creating web apps, mobile apps, and desktop apps using React, React Native, and Electron. It’s even a decent contender against the likes of Python for doing machine learning work with TensorFlow.js. 
In short, if you can learn JavaScript, there’s very little you can’t accomplish with this workhorse of a coding language. Unlike R, that’s best for data viz and statistics; or Swift, that’s only useful for iOS, JavaScript is a great language to learn to accomplish a lot of different things. Why learn JavaScript? Because it’ll see you through a wide range of programming tasks you might want to accomplish. 
3. It comes pre-installed in your browser.
Running is the perfect hobby for me because I don’t need anything other than a sports bra and some running shoes to get a workout in. Part of the reason behind why learning JavaScript is awesome is that it’s kind of like the running of coding languages – you don’t need any fancy equipment, development environments, or branded textbook. If you have a computer with a browser, you can code in JavaScript. 
Even similarly simple languages like Python are hard compared to JavaScript. When I began learning Python, in order to do anything fancy, I had to get my feet wet with the terminal, which I find tedious and annoying. Frankly, that was an obstacle. Meanwhile, your computer already has a javascript GUI and runtime. With any text editor and browser, you can code in JavaScript. 
This makes it ultra-accessible for beginners like me. With a very basic understanding, you can follow a tutorial like this one from Oreilly and write a program within minutes. Why learn JavaScript only by rote, when you can do it hands-on? 
You can also learn by poking around in the Javascript that runs an overwhelming majority of websites, by right-clicking and selecting “inspect” on any website. It’s a fun way to pick apart pre-existing JavaScript and see what happens when you change things.
4. There are a lot of shortcuts, when you’re ready to take them.
Coding can include a lot of repetitive tasks – there are shortcuts in JavaScript that can make your life easier. It’s best to understand the underlying bones of any language before you start looking for shortcuts. However, if you use JavaScript for anything serious, there will be a time when you have a good understanding of the basics of Javascript. At that point, you might want to know how to make things easier. 
Plain old JavaScript (also called “vanilla” JavaScript) can do a lot, but when you’ve grasped the basics, you can begin to take advantage of the many shortcuts that exist in the form of JavaScript libraries and frameworks. 
These assets have grab-and-go JavaScript code that’s been pre-written for your use. These frameworks act as a structure, with a lot of the elements and components already built and ready for use or modification. It can help you build whatever it is you’re building a heck of a lot faster and with greater ease.
It’s the difference between building a house from scratch, versus coming to a house that already has the blueprints in place and even a few furnishings that can let you build your dream home faster. You’re still doing the work – and you need to understand how those foundations work, or else you’ll run the risk tearing the whole thing down because you don’t know what you’re doing – but it’s simpler to get the house ready. 
5. You’ll find a way to learn.
Many people ask, “why learn JavaScript when there are so many newer languages out there?” When I listed the most popular coding languages of 2021, I noticed a definite rift. One on hand, relative newcomers like Rust, Go, and Swift are growing rapidly in popularity but don’t have a really wide range of ways to learn yet. Swift and Go are company-sponsored (Apple and Google respectively), and Rust users are a tiny minority. No matter how popular in the community, these are bleeding-edge users with a limited set of learning resources. 
By comparison, I also reviewed languages like Python, Perl and JavaScript that have stood the test of years. Thanks to simply existing longer, they have a much more developed library of assets. There are simply more free JavaScript basics courses (like the free JavaScript course we have at QVault, created specifically for beginners), more tutorials, more YouTube videos, more free textbooks. Plus, there’s a much larger community of developers who can help you with basic errors and questions on places like StackOverflow, Discord, and newsletters. 
When you’re learning a new language, it helps tremendously to know you’re not alone, and to rely on the community around you who’s been where you are now. JavaScript has literal generations of devoted coders who are more than happy to lend their expertise to any novice coder still struggling with the basics, hanging out all over the internet like in QVault’s Discord community. That kind of group feeling can make or break your ability to stick with a language. 
6. JavaScript can make you a renaissance programmer
Nowadays, knowing only one coding language is good, but most jobs ask that you can code in more than one language. JavaScript is a great contender for that first one for the reasons listed above, but also because it’s a great primer to any future programming languages you might want to learn. The benefits of JavaScript are fantastic on their own, but it’s also good to know that learning JavaScript first is a good bet for any up-and-coming programmer.
“JavaScript provides a crucial introduction to key principles and practices that you’ll take with you throughout your career as a developer,” writes Stevens in Career Foundry. Same as C++, Python and Java, JavaScript supports object-oriented, functional, and imperative styles of programming. That means that when you’re fully versed in JavaScript and thinking about picking up language number 2, you’ll be able to pick it up much faster than normal. 
A lot of languages borrow concepts from each other, or are built to shore up the weaknesses of another. JavaScript is one of the few that has completely transferable skills that can help you hit the ground running when you start to learn another programming language. Why learn JavaScript? Because it’ll help you learn Python, or C++, or any other similar language. 
Why Learn JavaScript? Final Thoughts
This language is more than a synonym for CoffeeHandwriting – it’s the perfect programming language for beginners to use immediately in their career, as well as providing a perfect jumping-off point for any future developments. It’s totally future-proof, since nearly all of the web relies on it. Why learn JavaScript? To summarize the reasons I’ve listed above, the reasons why you should learn JavaScript are:
It’s a multifunctional language.
It’s easy to get started with.
There’s a comprehensive set of frameworks and libraries to make your life easier.
The community is firmly entrenched and stellar.
It’s a highly sought-after professional skill.
It can help you learn your next programming language.
In other words, it’s a great language that can help you accomplish a lot both in your personal life and in your professional life. Out of all the programming languages you could start learning in 2021, JavaScript must come top of the list.
Thanks for reading, now take a course!
Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.
Start coding now
Questions?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
Subscribe to my newsletter for more coding articles delivered straight to your inbox.
from Qvault https://ift.tt/3hShlus
0 notes
qvault · 3 years
Text
Comprehensive Guide to Dates and Times in Go
The post Comprehensive Guide to Dates and Times in Go first appeared on Qvault.
Keeping track of time in code has long been a developer’s nightmare. While no language or package manages time perfectly, I’m of the opinion that Golang does a pretty good job out-of-the-box. This full tutorial is designed to answer ~90% of the questions you’ll have about managing time in Go.
Table of Contents
Overview – How dates and times are stored in Go
Get the current time with time.Now()
Create a time object for a specific date
Printing, parsing, and formatting times in Go
Time durations
Convert between separate timezones
Get the timezone from an existing time object
Create a new time.Location object
Convert a time from one location to another
Custom timezone name
Add and subtract time
Add time and duration
Get difference between two times
Compare two times to see which comes after the other
Intervals, sleeping, and tickers
Force the current goroutine to sleep
Execute code on an interval using tickers
Saving memory with TinyDate and TinyTime
Overview – How dates and times are stored in Go
The first thing to know is that you probably don’t need any third-party packages to manage times and dates in Go. The Go standard library’s time package is very robust and can do almost anything you’re going to want to do.
The default time.Time type represents an instant in time with nanosecond precision. It’s a struct that has no exported fields, which means you’ll never need to use a dot operator to access different fields. Instead, various methods are available to get the data you need. For example, time.Year() returns the year (as an integer) of the time object in question.
The two most common ways to create a new time object are to use the current time, or to provide a date as input.
Get the current time with time.Now()
The time.Now() function returns the current local time. If you work on the backend, it’s likely you’ll also want to immediately convert it to UTC.
currentTime := time.Now() currentTimeUTC := time.Now().UTC()
Create a time object for a specific date
If instead you want a time object for a specific date, you can use the time.Date() function.
// takes a year, month, day, hour, minute, second, nanosecond, and location someonesBirthday := time.Date(1990, time.May, 10, 23, 12, 5, 3, time.UTC)
Printing, parsing, and formatting times in Go
While dates and times are typically stored as time.Time objects within Go programs, we frequently need to save them to databases, marshal them to JSON, or just print them to the console. It’s nice that Go provides functions to format and parse dates easily. That said, the way it’s handled is unique compared to most coding languages.
Let’s say we have a time object and we want to be able to print in a specific format. The Go formatting engine takes a layout of specific constants, and uses that as an example for how to format the time.
The reference time is defined in the docs as:
Mon Jan 2 15:04:05 -0700 MST 2006
So if we want to format our time object a specific way, we can just use the constants from the reference time but rearrange them how we want.
t := time.Now().UTC() fmt.Println(t.Format("2006 01 02 MST")) // prints 2021 05 16 UTC (assuming that's the current time)
The time.Parse() function works the same way, but takes a time string and a layout as an input, and attempts to create a new time object.
t, err := time.Parse("2006 01 02 MST", "2021 05 16 UTC") if err != nil{ log.Fatal(err) } fmt.Println(t) // Prints "2021-05-16 00:00:00 +0000 UTC" assuming that's the current time // The above is the default printing format for a time object (rfc3339)
As I mentioned above in the comment, the default parsing and formatting layout for Go is rfc3339. Where possible, if your team works primarily in Go, I’d recommend using the default formatting,, it’s the default for a reason.
Time durations
My bane in programming is when developers don’t include units in their calculations. Inevitably one developer assumes the variable timeElapsed (an int) represents seconds, it really represents milliseconds. In Go, this isn’t a problem as long as everyone adheres to the standard of the time.Duration type.
Durations are just a specific kind of int64. They represent the elapsed time between two instants as a nanosecond count. the only drawback is that the largest representable duration is ~290 years, which hasn’t been a problem for me yet. There are several constants defined by the time package to represent some common durations.
fiveSeconds := time.Second * 5 sixMinutes := time.Minute * 6 oneDay := time.Hour * 24
Convert between separate timezones and locations
Every time.Time object is associated with a location, which is basically a timezone. 5 o’clock is meaningless if you don’t know which timezone it’s in. Locations are defined by the time.Location type, which, like the time.Time type, is a struct with no exported fields.
Get the timezone from an existing time object
myTime := time.Now() myTimezone := myTime.Location()
Create a new time.Location object
mstLocation, err := time.LoadLocation("MST")
Convert a time from one location to another
loc, err = time.LoadLocation("MST")if err != nil{ log.Fatal(err) } mstTime := t.In(loc)
Custom timezone name
A timezone is basically just a name and an duration offset from UTC. If you want a specific timezone but want to change its name you can do that.
tzName := "CUSTOM-TZ" tzOffset :=60*60*5 // seconds east of UTC loc := time.FixedZone(tzName, tzOffset)
Add, subtract and compare times
Times and durations naturally work well together, and several helper functions are available to do basic time arithmetic and comparisons.
Add time and duration
There are two primary functions for adding time to an existing time. Keep in mind, these functions also work for subtracting time, you just add a negative duration.
time.Add()
myTime := time.Now().UTC() inTenMinutes := myTime.Add(time.Minute * 10) // inTenMinutes is 10 minutes in the future myTime = time.Now().UTC() tenMinutesAgo := myTime.Add(-time.Minute * 10) // tenMinutesAgo is 10 minutes in the past
time.AddDate()
myTime := time.Now().UTC() // adds years, months, and days inOneMonth := myTime.AddDate(0, 1, 0) // inOneMonth is 1 month in the future myTime = time.Now().UTC() twoDaysAgo := myTime.AddDate(0, 0, -2) // twoDaysAgo is 2 days in the past
Get difference between two times
The sub() function gets the difference between two times. Keep in mind, the sub function does not subtract a duration from a time. You, perhaps counterintuitively, need to use the add() function for that.
start := time.Date(2020, 2, 1, 3, 0, 0, 0, time.UTC) end := time.Date(2021, 2, 1, 12, 0, 0, 0, time.UTC) difference := end.Sub(start) fmt.Printf("difference = %v\n", difference)
Compare two times to see which comes after the other
There are two functions that should take care of most of your time comparison needs.
time.After()
first := time.Date(2020, 2, 1, 3, 0, 0, 0, time.UTC) second := time.Date(2021, 2, 1, 12, 0, 0, 0, time.UTC) isFirstAfter := first.After(second)
time.Equal()
first := time.Date(2020, 2, 1, 3, 0, 0, 0, time.UTC) second := time.Date(2021, 2, 1, 12, 0, 0, 0, time.UTC) equal := first.Equal(second) // equal is true if the both times refer to the same instant // two times are equal even if they are in different locations
Intervals, sleeping, and tickers
If you need your program to synchronously sleep, there’s an easy way to do that, time.Sleep(). Keep in mind, this is synchronous, it will block the current goroutine.
Force the current goroutine to sleep
fmt.Println("hello") time.Sleep(time.Second * 2) fmt.Println("world 2 seconds in the future")
Execute code on an interval using tickers
If you need to do something an a fixed interval, the time.Ticker type makes it easy to do so.
func doSomethingWithRateLimit() { ticker := time.NewTicker(time.Second) for range ticker.C { // doSomething() is executed every second forever doSomething() } }
The first tick to come through the ticker channel is after the first duration. If you want an immediate first tick you can read about that here.
Saving memory with TinyDate and TinyTime
A typical time.Time value takes ~24 bytes in memory. Sometimes, you can’t afford to use that much. If you’re in that situation then check out my TinyTime and TinyDate libraries on GitHub. They only use 4 bytes each!
TinyDate Github
TinyTime Github
Thanks for reading, now take a course!
Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.
Start coding now
Questions?
Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!
Subscribe to my newsletter for more coding articles delivered straight to your inbox.
from Qvault https://ift.tt/3tRq9mr
0 notes
qvault · 3 years
Text
Comprehensive Guide to Dates and Times in Go
We just published "Comprehensive Guide to Dates and Times in Go" #Go #Golang #100DaysOfCode
Keeping track of time in code has long been a developer’s nightmare. While no language or package manages time perfectly, I’m of the opinion that Golang does a pretty good job out-of-the-box. This full tutorial is designed to answer ~90% of the questions you’ll have about managing time in Go. Table of Contents Overview – How dates and times are stored in GoGet the current time with…
View On WordPress
0 notes