Posted on Leave a comment

What is __init__ in Python?

When reading over other people’s Python code, many beginners are puzzled by the __init__(self) method. What’s its purpose? This article answers this question once and for all.

What’s the purpose of __init__(self) in Python?

The reserved Python method __init__() is called the constructor of a class. You can call the constructor method to create an object (=instance) from a class and initialize its attributes.

Python __init__ method constructor

While this answers the question, if you’ve got any ambition in becoming a professional Python coder, it’s not enough to know that the __init__ method is the constructor of a class. You also need to know how to use the constructor in your own projects—and how to customize its arguments. A thorough understanding of the constructor serves as a strong foundation for more advanced concepts in object-oriented Python programming. Read on to learn the other half of the equation.

Interactive Example: Before I’ll explain it to you, let’s open your knowledge gap. Consider the following example:

Exercise: Add one argument color to the __init__ method and make the code run without error!

Let’s dive into this simple example in great detail.

How to Use the __init__ Method in Practice? A Simple Example

We’ll use some terms of object-oriented programming in Python to explain our example. Make sure to study the following cheat sheet (you can also download the PDF here). Click the image to get the cheat sheet (opens in a new tab). If you’re already comfortable with basic object-orientation terminologies like classes and instances, simply read on.

You’ve learned that the __init__ method is the constructor method of a class. You call the constructor method to create new instances (or objects). But how exactly does this play out in practice? Before we dive into the correct use, we need to understand the arguments (or parameters) of the constructor method.

The Self Argument

The __init__ constructor requires at least one argument. According to the PEP8 standard, it’s good practice to denote this argument as self. In any case, the self argument points to the newly-created instance itself and it allows you to manipulate the instance attributes of the new instance. In the dog example, you’d use self.color = "blue" to set the newly-created dog’s color attribute to the string "blue".

Let’s have a look at the following basic code example:

class Dog: def __init__(self): self.color = "blue" bello = Dog()
print(bello.color)
# blue
  1. We create a new class Dog with the constructor __init__(self).
  2. We create a new instance of the class Dog named bello. There are two interesting observations: First, we use the class name rather than the constructor name to create the new instance. Python internally calls the __init__ method for us. Second, we don’t pass any argument when calling Dog(). Again, Python implicitly passes a reference to the newly created instance (bello) to the constructor __init__.
  3. We print the color attribute of the newly-created bello instance. The result is the string value "blue" as defined in the constructor.

However, this minimal example is unrealistic. Some dogs are brown, others are black, and only some are blue.

Multiple Constructor Arguments

So how can we create different dogs with different colors? We can easily achieve this by using more arguments, in addition to self, when defining our constructor __init__. Here’s another example where we create two dogs with different colors. Can you spot their colors?

class Dog: def __init__(self, color): self.color = color bello = Dog("blue")
print(bello.color)
# blue alice = Dog("brown")
print(alice.color)
# brown

In contrast to the first example, we now define the constructor __init__(self, color) with two arguments rather than one.

The first is the self argument as before. The second is a custom argument color that is passed through by the caller of the constructor. In our case, we create two Dog instances, bello and alice, by specifying the color argument for both.

Note that the self argument is handled implicitly by the Python programming environment: Python simply passes a reference to the respective Dog instance to the __init__ constructor.

What’s the Difference between the Constructor and the Initializer?

Well, I haven’t used a very accurate terminology in the previous paragraphs. I used the term “constructor” for both the call Dog() and the call __init__(). But only the former call can be denoted as constructor method because only this call actually creates a new instance. At the time, we call the method __init__, the instance has already been created (Python passes it to us via the self argument). That’s why a more precise term for the __init__ method is initializer method. That’s how I’ll denote it in the following to make up for it. 😉

What’s the Meaning of the Underscores in the __init__ Method Name?

I’ve written a whole article about the meaning of the underscore in Python. Check it out if this topic interests you further. The key takeaway, however, is the following:

The double underscore “__” (called “dunder“) is used to make an instance attribute or method private (cannot be accessed from outside the class) — when used as leading dunder. When used as enclosing dunder (e.g. “__init__”) it indicates that it is a special method in Python (called “magic method”).

How to Use __init__ in an Inherited Class?

An inherited class is a class that inherits all attributes and methods from a parent class. Here’s an example:

class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): Dog.__init__(self, color) self.hairs = True bello = CuteDog('brown')
print(bello.hairs)
# True print(bello.color)
# brown

Inheritance is very important in Python. In the example, the parent class is the class Dog you already know from above. The initializer method __init__ defines the color of this dog.

Now, we also create a new class CuteDog that inherits all attributes from the parent class Dog. You can define inheritance by specifying the name of the parent class within the brackets after the child class: CuteDog(Dog).

The interesting thing is that the __init__ method of the child class CuteDog calls the __init__ method of the parent class. This makes sense because the child class has the same attributes as the parent class—and they need to be initialized, too.

The more Pythonic way, however, is to use the super() function that makes it easier for you to access the parent class:

class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): super().__init__(color) self.hairs = True bello = CuteDog('brown')
print(bello.hairs)
# True print(bello.color)
# brown

With the help of the super() function, you can easily reuse the initializer method of the parent class.

Let’s have a look at a few related questions.

Is __ init __ Necessary in Python?

No. You can simply skip the initializer method. As a result, your class won’t have any instance attributes directly after its creation. However, you can add instance attributes dynamically at any future point in time. Here’s an example:

class Dog: None bello = Dog()
bello.color = "blue"
print(bello.color)
# blue

How beautiful! You can even create empty classes and “fill in” the methods and attributes later in Python.

What Does __ init __ Return?

The __init__ method itself returns nothing. Technically, Python first uses the constructor method Dog() before it uses __init__ to initialize all attributes. Hence, only the constructor returns the newly-created instance.

Can __init__ Return a Value?

No. The only return value that doesn’t cause a runtime error is None. All other return values cause an error. See the following code example:

class Dog: def __init__(self, color): self.color = color return 0 bello = Dog("blue")
# TypeError: __init__() should return None, not 'int'

So never use any return value in the __init__ method and you’re good to go.

Where to Go from Here?

Thanks for reading through the whole article. You’ve learned that the __init__ name is reserved for the Python initializer method that is called within the constructor.

The article requires a thorough understanding of the Python basics. Investing time to learn and study those is vital for your success as a professional coder.

To help people grow their skills in an automated, personalized way, I’ve created a free Python email course “Coffee Break Python” that grows your skill level in a seemingless way. Day after day after day…

Join tens of thousands of Python coders (100% free)!

Posted on Leave a comment

Python One Line While Loop [A Simple Tutorial]

Python is powerful — you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a while loop in a single line of code? This article explores this mission-critical question in all detail.

How to Write a While Loop in a Single Line of Python Code?

There are three ways of writing a one-liner while loop:

  • Method 1: If the loop body consists of one statement, write this statement into the same line: while True: print('hi'). This prints the string 'hi' to the shell for as long as you don’t interfere or your operating system forcefully terminates the execution.
  • Method 2: If the loop body consists of multiple statements, use the semicolon to separate them: while True: print('hi'), print('bye'). This runs the statements one after the other within the while loop.
  • Method 3: If the loop body consists nested compound statements, replace the inner compound structures with the ternary operator: while True: print('hi') if condition else print('bye').

Exercise: Run the code. What do you observe? Try to fix the infinite loop!

Next, you’ll dive deep into each of these methods and become a better coder in the process.

Before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

But enough promo, let’s dive into the first method—the profane…

Method 1: Single-Statement While Loop One-Liner

Just writing the while loop into a single line of code is the most direct way of accomplishing the task. Say, you want to write the following infinite while loop in a single line of code:

while True: print('hi') '''
hi
hi
... '''

You can easily get this done by writing the command in a single line of code:

# Method 1: Single-Line While Loop
while True: print('hi')

While this answer seems straightforward, the interesting question is: can we write a more complex while loop that has a longer loop body in a single line?

Related Article: If you’re interested in compressing whole algorithms into a single line of code, check out this article with 10 Python one-liners that fit into a single tweet.

Let’s explore an alternative Python trick that’s very popular among Python masters:

Method 2: Multi-Statement While Loop One-Liner

As it turns out, you can also use the semicolon to separate multiple independent statements and express them in a single line. The statement expression1; expression2 reads “first execute expression1, then execute expression2.

Here’s an example how you can run a while loop until a counter variable c reaches the threshold c == 10:

c = 0
while c < 10: print(c); c = c + 1 '''
0
1
2
3
4
5
6
7
8
9 '''

This way, you can easily compress “flat” loop bodies in a single line of Python code.

But what if the loop body is not flat but nested in a hierarchical manner—how to express those nested while loops in a single line?

Method 3: Nested Compound Statements While Loop One-Liner

You often want to use compound statements in Python that are statements that require an indented block such as if statements or while loops.

In the previous methods, you’ve seen simple while loop one-liners with one loop body statement, as well as multiple semicolon-separated loop body statements.

Problem: But what if you want to use a compound statement within a simple while loop—in a single line of code?

Example: The following statement works just fine:

# YES:
if expression: print('hi')

You can also add multiple statements like this:

# YES:
if expression: print('hi'); print('ho')

But you cannot use nested compound statements in a while loop one-liner:

# NO:
while expression1: if expression2: print('hi')

Python throws an error does not work because both the while and if statements are compound.

Nested Compound Statements Error

However, there’s an easy fix to make this work. You can replace the if expression2: print('hi') part with a ternary operator and use an expression rather than a compound statement:

# Method 3: One-Line While Loop + Ternary Operator
while True: print('yes') if True else print('no')

You can also use nested ternary operators to account for possibly nested if blocks:

Python Ternary Elif

Related Video: One-Line For Loop

You can find out more about the single-line for loop in my detailed article here.

Where to Go From Here

Knowing small Python one-liner tricks such as the list comprehension and single-line for loops is vital for your success in the Python language. Every expert coder knows them by heart—after all, this is what makes them very productive.

If you want to learn the language Python by heart, join my free Python email course. It’s 100% based on free Python cheat sheets and Python lessons. It’s fun, easy, and you can leave anytime.

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

Form Builder – Dike

CRUD Form generator tool

Smooth responsive interface to build form. It has tools menu and options to add, edit, delete and reorder form fields.

Preview, generate and download

Two-step CRUD form generation. 1. Choose tools and build the CRUD form. 2. Preview form and generate code to distribute.

Easy customization

Code is sleek, too short for easy understanding and customization. Source code with optimum comments. Easy to understand, integrate and maintain.

AJAX based CRUD

AJAX via CRUD action handling is easier to use for the end users. Easy for the developer to customize.

Unified CRUD handlers

Form can be regenerated number of times. No matter about what are the form fields or how many are there. It has unified CRUD handlers for any form.

Posted on Leave a comment

Python One Line For Loop Lambda

Problem: Given a collection. You want to create a new list based on all values in this collection. The code should run in a single line of code. How do you accomplish this? Do you need a lambda function?

Python One Line For Loop Lambda

Example: Given an array a = [1, 2, 3, 4]. You need to create a second array b with all values of a—while adding +1 to each value. Here’s your multi-liner:

a = [1, 2, 3, 4]
b = []
for x in a: b.append(x+1)
print(b)
# [2, 3, 4, 5]

How do you accomplish this in a single line of code?

Answer: No, you don’t need a lambda function. What you’re looking for is a feature called list comprehension. Here’s the one-liner expression that accomplishes this without the lambda function:

b = [x+1 for x in a]
print(b)
# [2, 3, 4, 5]

You can try this example yourself in our interactive code shell:

Let’s dive into some background information in case you wonder how list comprehensions work. Based on your question, I also suspect that you don’t completely understand lambda functions either, so I’ll also add another section about lambda functions. Finally, you’ll also learn about a third alternative method to solve this exact problem by using the lambda function in combination with Python’s built-in map() function!

So, stay with me—you’ll become a better coder in the process! 🙂

List Comprehension 101

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

Have a look at the following interactive code snippet—can you figure out what’s printed to the shell? Go ahead and click “Run” to see what happens in the code:

I’ll explain both ways of generating a new list in the following.

Example: Say you want to filter out all customers from your database who earn more than $1,000,000. This is what a newbie not knowing list comprehension would do:

# (name, $-income)
customers = [("John", 240000), ("Alice", 120000), ("Ann", 1100000), ("Zach", 44000)] # your high-value customers earning <$1M
whales = []
for customer, income in customers: if income>1000000: whales.append(customer)
print(whales)
# ['Ann']

This snippet needs four lines just to create a list of high-value customers (whales)!

Instead, a much better way of doing the same thing is to use list comprehension:

whales = [x for x,y in customers if y>1000000]
print(whales)
# ['Ann']

List comprehension is dead simple when you know the formula.

“A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.”

Official Python Documentation

Here is the formula for list comprehension. That’s the one thing you should take home from this tutorial.

Formula: List comprehension consists of two parts.

‘[‘ + expression + context + ‘]’

List Comprehension

The first part is the expression. In the example above it was the variable x. But you can also use a more complex expression such as x.upper(). Use any variable in your expression that you have defined in the context within a loop statement. See this example:

whales = [x.upper() for x,y in customers if y>1000000]
print(whales)
# ['ANN']

The second part is the context. The context consists of an arbitrary number of for and if clauses. The single goal of the context is to define (or restrict) the sequence of elements on which we want to apply the expression. That’s why you sometimes see complex restrictions such as this:

small_fishes = [x + str(y) for x,y in customers if y<1000000 if x!='John']
# (John is not a small fish...)
print(small_fishes)
# ['Alice120000', 'Zach44000']

Albrecht, one of the loyal readers of my “Coffee Break Python” email course, pointed out that you can break the formula further down using the following blueprint:

lst = [<expression> for <item> in <collection> if <expression>] 

A detailed tutorial on the topic is available for free at this tutorial on the Finxter blog.

Lambda Function 101

A lambda function is an anonymous function in Python. It starts with the keyword lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y, z: x+y+z would calculate the sum of the three argument values x+y+z.

Here’s a practical example where lambda functions are used to generate an incrementor function:

Exercise: Add another parameter to the lambda function!

Watch the video or read the article to learn about lambda functions in Python:

Puzzle. Here’s a small code puzzle to test your skills:

def make_incrementor(n): return lambda x: x + n
f = make_incrementor(42)
print(f(0))
print(f(1))

To test your understanding, you can solve this exact code puzzle with the topic “lambda functions in Python” at my Finxter code puzzle app.

Find the detailed article on lambda functions here.

Alternative Method 3: map() + lambda + list()

Interestingly, there’s a third way of solving the above problem by using the map() function (and the lambda function):

# Method 3: map() + lambda + list()
a = [1, 2, 3, 4]
b = list(map(lambda x: x+1, a))
print(b)
# [2, 3, 4, 5]

You can learn about the map() function in my video tutorial here:

However, it would be better if you avoided the map function—it’s not readable and less efficient than list comprehension.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Hybrid Blazor apps in the Mobile Blazor Bindings July update

Eilon Lipton

Eilon

I’m excited to announce we are releasing the Mobile Blazor Bindings July update! This release adds support for building Hybrid Blazor apps, which contain both native and web UI.

Hybrid apps are a composition of native and web UI in a single app. With Mobile Blazor Bindings this means you can write the native UI of your app using Blazor, and also create web UI in your app using Blazor. A major advantage of hybrid apps is that the HTML part of the app can reuse content, layout, and styles that are used in a regular web app, while enabling rich native UI to be composed alongside it. You can reuse code, designs, and knowledge, while still taking full advantage of each platform’s unique features. This feature supports Android, iOS, Windows (WPF), and macOS. And it’s all Blazor, C#, .NET, and Visual Studio. Woohoo!

You can mix and match native and web UI in whatever structure makes sense for your app. Here’s a simple example:

Blazor Hybrid app in iOS Simulator

These are the major new features in the 0.4 Preview 4 release:

  • New Hybrid Apps feature enables mixing Blazor native UI components with Blazor web UI components in the same page. This one is HUGE!
  • Hybrid Apps are hosted in a new BlazorWebView component that uses a browser component to contain the web part of the app. No remote or local web server; all your code runs in the app’s process.
  • New blazorhybrid project template that supports Android, iOS, Windows (WPF), and macOS for creating hybrid apps
  • Updated dependencies: Xamarin.Forms 4.7, Xamarin.Essentials 1.5, and other libraries.
  • .NET Core 3.1 SDK is required to use the new preview

How does it work?

In hybrid apps all the code (both for the native UI parts and the web UI parts) runs as .NET code on the device. There is no local or remote web server and no WebAssembly (WASM). The .NET code for the entire app runs in a single process. The native UI components run as the device’s standard UI components (button, label, etc.) and the web UI components are hosted in a browser view (such as WebKit, Chromium, and Edge WebView2). The components can share state using standard .NET patterns, such as event handlers, dependency injection, or anything else you are already using in your apps today.

Get started

To get started building a Blazor Hybrid app with Experimental Mobile Blazor Bindings preview 4, install the .NET Core 3.1 SDK and then run the following command:

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.4.74-preview

And then create your first project by running this command:

dotnet new blazorhybrid -o MyHybridApp

Now open it in Visual Studio and run it on Android, iOS, Windows, or macOS. That’s it! You can find additional docs and tutorials on https://docs.microsoft.com/mobile-blazor-bindings/.

Blazor Hybrid code sample

Here’s the code for an app similar to what was seen at the top of this post. It has native UI and web UI sharing the same app state, running together in the same app process (no web server or HTTP). The native UI uses the new <BlazorWebView> component to specify which web component to load and where to locate static web assets. Blazor does all the work.

This is the main native UI page /Main.razor:

@inject CounterState CounterState <ContentView> <StackLayout> <StackLayout Margin="new Thickness(20)"> <Label Text="@($"You pressed {CounterState.CurrentCount} times")" FontSize="30" /> <Button Text="Increment from native" OnClick="@CounterState.IncrementCount" Padding="10" /> </StackLayout> <BlazorWebView ContentRoot="WebUI/wwwroot" VerticalOptions="LayoutOptions.FillAndExpand"> <FirstBlazorHybridApp.WebUI.App /> </BlazorWebView> </StackLayout>
</ContentView> @code { // initialization code
}

And this is the embedded HTML UI page /WebUI/App.razor:

@inject CounterState CounterState <div style="text-align: center; background-color: lightblue;"> <div> <span style="font-size: 30px; font-weight: bold;"> You pressed @CounterState.CurrentCount times </span> </div> <div> <button style="margin: 20px;" @onclick="ClickMe">Increment from HTML</button> </div>
</div> @code
{ private void ClickMe() { CounterState.IncrementCount(); } // initialization code
}

Upgrade an existing project

To update an existing Mobile Blazor Bindings project please refer to the Migrate Mobile Blazor Bindings From Preview 3 to Preview 4 topic for full details.

More information

Check out last month’s ASP.NET Community Standup where I talked a bit about these new features and did a demo of Blazor hybrid apps (starts at 30:35):

For more information please check out:

Thank you to contributors

This release had several major contributions from Jan-Willem Spuij. Jan-Willem had already built his own BlazorWebView component and kindly helped us get this functionality into the Mobile Blazor Bindings project with many great improvements. Thank you Jan-Willem!

What’s next? Let us know what you want!

This project relies on your feedback to help shape the future of Blazor for native and hybrid scenarios. Please share your thoughts on this blog post or at the GitHub repo so we can keep the discussion going.

Posted on Leave a comment

INDEPENDENT WORK: CHOICE, NECESSITY, AND THE GIG ECONOMY

McKinsey Authors: James Manyika | San FranciscoSusan Lund | WashingtonJacques Bughin | BrusselsKelsey Robinson | San FranciscoJan Mischke | ZurichDeepa Mahajan | San Francisco

Download Link (PDF)

Anyone who has ever felt trapped in a cubicle, annoyed by a micromanaging boss, or fed up with office politics has probably dreamed of leaving it all behind and going it alone.

The powerful opening line from the 148 page report (published in 2014) sets the tone of the report and shows one of the underlying reasons the freelancer market has grown double-digits since then.

In this article, I’ll summarize the most important points and statistics of the report. I’ll also give some quotes. You can see the original document here. The report is based on 8000 participants of a McKinsey survey.

Statistics

The report states the following statistics (highlights by me):

  • 20 to 30 percent of the working-age population in the United States and the EU-15, or up to 162 million individuals, engage in independent work
  • At least 15 percent of workers use online platforms such as Uber and Upwork (in 2015)
  • 30 percent are “free agents,” who actively choose independent work and derive their primary income from it.
  • Approximately 40 percent are “casual earners,” who use independent work for supplemental income and do so by choice
  • “Reluctants,” who make their primary living from independent work but would prefer traditional jobs, make up 14 percent.
  • The “financially strapped,” who do supplemental independent work out of necessity, account for 16 percent.

Quotes

Interesting Nuggets

Posted on Leave a comment

Image Editor: Move Scale Skew Rotate and Spin with CSS Transform

Last modified on July 22nd, 2020.

Are you interested in creating an image editor tool? If so, this article will help you to get started with it.

An image editor will have a range of tools. It can be very basic with only tools like resize, rotate and crop. Or it can be super extensive like a Photoshop.

Rotate is a basic and essential tool that is part of any image editor. Let us start with something easy and basic like rotate then add some more essential tools.

I will be using CSS transform property as the core and add JavaScript to enrich the tool.

This can become a basic starter toolkit that can be expanded to a full fledged image editor in the future.

Following is a preview of the things to come.

What is inside?

  1. How to edit an image?
  2. A quick glance on CSS transform and image editing
  3. Examples and demo on image editing
  4. Conditions and exceptions on applying transform property
  5. Importance of respecting system preferences

How to edit an image?

Do not underestimate the power of CSS. Gone or those days, where CSS just applies decoration on top of HTML and beautifies the document. CSS3 and beyond, with the combined support of HTML5, advancements in the browser support has change CSS to a powerful UI tool.

It complements well with the JavaScript. When we combine it together, we can create wonders. The divide between thin-client and thick-client has vanished. The CSS is a very good beginner’s tool to start with simple image editor features.

When you work on image editing capabilities with CSS, you must consider browser compatibility. Some browsers will not render as you code. So, we have to be carefully choosing the properties.

I have used CSS keyframesrules to set the core properties.

In an older article, we have see several animation effects with CSS and Javascript.

In this article, you can find the example code of the below items with a demo.

  • Rotation and spin
  • Skew
  • Scale
  • Translation

A quick glance on CSS transform and image editing

CSS transform property can be used to do basic image editing. It supports functions like rotation, skew, scale and translate.

The key functions are rotate()skew()scale(), translate().

The transform functions have classification based on the axis of animation. For example rotateX(), rotateY() and more. This can be used for image animation.

We can apply the transform functions in a combination way for a single UI element’s selector. When we use many transform function, the animation effects happen in a right to left order.

Examples and demo on image editing

Scaling an image

The scaling is a transform function that allows us to scale up or down the element’s dimension. The scaling transform output varies based on the function used and its parameters.

The scale() function can have single or dual parameters. With a single parameter, it applies uniform scaling in both x, y-axis. When we supply separate values for the x, y-axis, then the scaling range will vary.

With three params the scale3d() function allows scaling in x,y,z axis.

We can also apply scaling with respect to single axis by using scaleX(), scaleY() or scaleZ().

The above demo has a slider to scale up and down an image.

Below code has the UI elements to apply scaling transform on an image element. It has a pallet with an image element and animation tools.

image-scale/index.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../assets/css/phppot-style.css" type="text/css" rel="stylesheet" />
<link href="./assets/css/style.css" type="text/css" rel="stylesheet" />
<link href="../vendor/jquery/ui/jquery-ui.min.css" type="text/css" rel="stylesheet" />
<script src='../vendor/jquery/jquery-3.3.1.js' type='text/javascript'></script>
<script src='../vendor/jquery/ui/jquery-ui.min.js' type='text/javascript'></script>
</head> <body> <div class="phppot-container"> <div class="container"> <div class="image-demo-box"> <div id="slider"> <div id="scale-handle" class="ui-slider-handle"></div> </div> <img src='../sweet.jpg' id='image' /> </div> </div> </div> <script src='./assets/js/scale.js'></script>
</body>
</html>

This jQuery script initiates UI slider by setting the min max ranges. The slider handle will show the scaling factor.

On dragging the slider, the script applies scaling transform on the image element. The slider’s step property defines the scaling multiples.

On dragging the slider handle, the script will populate the scaling factor in the handle.

image-scale/assets/js/scale.js

$(document).ready(function() { var scaleX = 2; var handle = $("#scale-handle"); $("#slider").slider({ min : 1, max : 2.5, value: scaleX, step: 0.1, create : function() { handle.text(scaleX+"x"); scale(scaleX); }, slide : function(event, ui) { scaleX = ui.value; handle.text(scaleX + "x"); scale(scaleX); } });
}); function scale(scaleX) { $('#image').css('transform', 'scale(' + scaleX + ')');
}

Translating image element

Like other transform functionality, the translate() function performs 2D, 3D translation.

The translate() function with one or two params results in 2D translation. The two params are to move the image in the x, y-axis of a 2D plane. With single param, the translate() will happen in a horizontal direction.

The translateX() and translateY() are for implementing translation in a particular direction.

The translate3d() with x, y, z factors allows creating 3D animation.

In this demo, there are two sliders in horizontal and vertical directions. On dragging the handle of these sliders, it moves the image on the 2D plane shown above.

This HTML shows the template elements to set the image-translate demo.

image-translate/index.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../assets/css/phppot-style.css" type="text/css" rel="stylesheet" />
<link href="./assets/css/style.css" type="text/css" rel="stylesheet" />
<link href="../vendor/jquery/ui/jquery-ui.min.css" type="text/css" rel="stylesheet" />
<script src='../vendor/jquery/jquery-3.3.1.js' type='text/javascript'></script>
<script src='../vendor/jquery/ui/jquery-ui.min.js' type='text/javascript'></script>
</head> <body> <div class="phppot-container"> <div class="container"> <div class="image-demo-box"> <div id="slider"> <div id="translate-x" class="ui-slider-handle"></div> </div> <div id="v-slider"> <div id="translate-y" class="ui-slider-handle"></div> </div> <img src='../sweet.jpg' id='image' /> </div> </div> </div> <script src='./assets/js/translate.js'></script>
</body>
</html>

This script sets the horizontal and vertical translation slider properties. The horizontal slider has the range between o -160. And, the vertical translation ranges between  0 to 50.

image-translate/assets/js/translate.js

$(document).ready(function() { var translateX; var handle = $("#translate-x"); $("#slider").slider({ range : "min", min : 0, max : 160, create : function() { handle.text($(this).slider("value") + " px"); }, slide : function(event, ui) { translateX = ui.value; handle.text(translateX + " px"); translate(translateX); } }); var translateY; var vhandle = $("#translate-y"); $("#v-slider").slider({ range : "min", min : 0, max : 50, orientation : "vertical", create : function() { vhandle.text($(this).slider("value") + " px"); }, slide : function(event, ui) { translateY = ui.value; vhandle.text(translateY + " px"); translatey(translateY); } }); }); function translate(translateX) { $('#image').css('transform', 'translateX(' + translateX + 'px)');
} function translatey(translateY) { $('#image').css('transform', 'translateY(' + translateY + 'px)');
}

Tools for rotating an image

Ah yes, we have reached the rotate tool. This is a core feature in any image editor. Rotation spins the image or other UI elements based on the angle specified.

With a negative degree, the animation will happen in counter-clockwise rotation.

Like scale and translate, rotate function also has classification based on the axis. Those are,

  • rotate(angle)
  • rotate3d(x, y, z, angle)
  • rotateX(angle)
  • rotateY(angle)
  • rotateZ(angle)

The rotate3d() function needs the angle and the x, y, z co-ordinates of the rotation axis.

A spin will make the image rotate from 0 to 360 degrees. You can stop spinning or refresh the image orientation back to its original.

image-rorate/index.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../assets/css/phppot-style.css" type="text/css" rel="stylesheet" />
<link href="./assets/css/style.css" type="text/css" rel="stylesheet" />
<link href="../vendor/jquery/ui/jquery-ui.min.css" type="text/css" rel="stylesheet" />
<script src='../vendor/jquery/jquery-3.3.1.js' type='text/javascript'></script>
<script src='../vendor/jquery/ui/jquery-ui.min.js' type='text/javascript'></script>
</head> <body> <div class="phppot-container"> <div class="container"> <input type='text' id='txtInputAngle' class="degree" value="10" /> <input type='button' id='btnRotate' value='Rotate' /> <input type='button' id='btnSpin' value='Spin' data-state='off' /> <input type='button' id='btnRefresh' value='Refresh' /> <div class="image-demo-box"> <div id="slider"> <div id="rotation-angle" class="ui-slider-handle"></div> </div> <img src='../sweet.jpg' id='image' /> </div> </div> </div> <script src='./assets/js/rotate.js'></script>
</body>
</html> 

I have used CSS keyframes to allow continuous spinning. Below CSS shows the styles used for the image rotation demo.

image-rorate/assets/css/style.css

.image-demo-box { border: #CCC 1px solid; text-align: center; margin: 15px 0px; } input[type=button] { width: 65px; margin-right: 8px; outline: none; background: #f6f5f6;
} input.degree
{ width: 50px;
} #image { margin: 50px auto; border: #f6f5f6 10px solid; width: 200px;
}
.rotate { animation: rotation 8s infinite linear;
} div#slider { border-bottom: 1px solid #c5c5c5;
} #slider .ui-slider-range { background: #c5c5c5; } #rotation-angle { width: 50px; padding: 3px 5px 1px 5px; font-size: 0.8em; text-align: center; border-radius: 2px; outline: none; } .ui-slider-handle.ui-corner-all.ui-state-default { border: 1px solid #c5c5c5; background: #f6f6f6; font-weight: normal; color: #454545;
} @keyframes rotation { from { transform: rotate(0deg); } to { transform: rotate(359deg); }
}

When you click the rotation tool, a jQuery script rotates the image based on the specified angle.

It changes the images’ transform property using jQuery $.css() function.

The rotation slider ranges from 0 to 360 degrees. I have added the rotation script below. It shows how to turn on a jQuery UI slider to rotate an image element.

image-rorate/assets/js/rotate.js

$(document).ready(function() { var rotationAngle; var handle = $("#rotation-angle"); $("#slider").slider({ range : "min", min : 0, max : 360, create : function() { handle.text($(this).slider("value") + " deg"); }, slide : function(event, ui) { $('#image').removeClass('rotate'); rotationAngle = ui.value; handle.text(rotationAngle + " deg"); rotate(rotationAngle); } }); $('#btnSpin').on('click', function() { if ($(this).data('state') == 'off') { spin($(this)); } else { stopSpin($(this)); } }); $('#btnRotate').on('click', function() { $('#image').removeClass('rotate'); rotationAngle = $('#txtInputAngle').val(); rotate(rotationAngle); }); $('#btnRefresh').on('click', function() { $('#image').removeClass('rotate'); rotate(0); });
}); function spin(buttonElement) { $('#image').addClass('rotate'); $("#image").css("animation-play-state", "running"); $(buttonElement).data('state', 'on'); $(buttonElement).val('Stop');
} function stopSpin(buttonElement) { $("#image").css("animation-play-state", "paused"); $(buttonElement).data('state', 'off'); $(buttonElement).val('Spin');
} function rotate(rotationAngle) { if ($('#btnSpin').data('state') == 'on') { stopSpin($('#btnSpin')); } $('#image').css('transform', 'rotate(' + rotationAngle + 'deg)');
}

Apply skew transform

By changing each point of the element in a fixed direction will skew the element. This change will tilt or skews the elements layout based on the specified angle.

The skew transform functions skewX(), skewY(), skewZ() tilting element boxes along with the X, Y, Z axis.

image-skew/index.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../assets/css/phppot-style.css" type="text/css" rel="stylesheet" />
<link href="./assets/css/style.css" type="text/css" rel="stylesheet" />
<link href="../vendor/jquery/ui/jquery-ui.min.css" type="text/css" rel="stylesheet" />
<script src='../vendor/jquery/jquery-3.3.1.js' type='text/javascript'></script>
<script src='../vendor/jquery/ui/jquery-ui.min.js' type='text/javascript'></script>
</head> <body> <div class="phppot-container"> <div class="container"> <div class="image-demo-box"> <div id="slider"> <div id="skew-angle" class="ui-slider-handle"></div> </div> <img src='../sweet.jpg' id='image' /> </div> </div> </div> <script src='./assets/js/skew.js'></script>
</body>
</html>

image-skew/assets/js/skew.js

$(document).ready(function() { var skewAngle; var handle = $("#skew-angle"); $("#slider").slider({ range : "min", min : 0, max : 40, create : function() { handle.text($(this).slider("value") + " deg"); }, slide : function(event, ui) { skewAngle = ui.value; handle.text(skewAngle + " deg"); skew(skewAngle); } }); });
function skew(skewAngle) { $('#image').css('transform', 'skew(' + skewAngle + 'deg)'); }

Conditions and exceptions on applying transform property

The CSS transform property will not work with some UI elements.

For example, table column element <col>, table column group element <col-group>, and more. Those are non-transformable elements.

What are transformable elements?

Most of the UI elements enclosed with the CSS box model are transformable. The following image shows the HTML element layout enclosed by a CSS box model.

CSS Box Model

Also, renderable graphical elements, clipPath elements are also known as a transformable element.

Importance of respecting system preferences

The system preferences will affect the motion of elements. If your system preferences is set to reduce animation is on, it will omit the animation effect of the above demo.

To respect this settings we have to add a CSS media rule to set the
prefers-reduced-motion. The possible values are no-preferences and reduce.

This media rule with reduce option provides a CSS block to suppress animation.

@media (prefers-reduced-motion: reduce) { .rotate { transform: none; }
}

In the above examples, I have used the media rule to respect the user’s system preferences. You can test this with the demo by enabling the reduced-motion.

System Preferences to Reduce Animation

Conclusion

We have seen the CSS transform based image editing. This is just a beginning only. This can serve as a bootstrap for building a full fledged image editor.

With CSS transform, we have added JavaScript and enriched the tool. We have also added various motion effects.

I have added most of the template files and the jQuery scripts above. But you can find the complete bundle with the downloadable source code here below.

Download

↑ Back to Top

Posted on Leave a comment

NumPy argpatition()

numpy.argpartition(a, kth, axis=-1, kind='introselect', order=None)

The NumPy argpatition function performs an indirect partition along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order.

Arguments Type Description
c array_like or poly1d object The input polynomials to be multiplied
kth integer or sequence of integers Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once.
axis integer or None (Optional.) Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.
kind {'introselect'} (Optional.) Selection algorithm. Default is 'introselect'.
order string or list of strings (Optional.) When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

The following table shows the return value of the function:

Type Description
Return Value index_array : ndarray, int Array of indices that partition a along the specified axis. If a is one-dimensional, a[index_array] yields a partitioned a. More generally, np.take_along_axis(a, index_array, axis=a) always yields the partitioned a, irrespective of dimensionality.

Related: See partition for notes on the different selection algorithms.

Let’s dive into some examples to show how the function is used in practice:

Examples

One-dimensional array:

import numpy as np x = np.array([3, 4, 2, 1]) print(x[np.argpartition(x, 3)])
# [2 1 3 4] print(x[np.argpartition(x, (1, 3))])
# [1 2 3 4]

Multi-dimensional array:

import numpy as np x = np.array([3, 4, 2, 1]) print(x[np.argpartition(x, 3)])
# [2 1 3 4] print(x[np.argpartition(x, (1, 3))])
# [1 2 3 4] x = [3, 4, 2, 1]
print(np.array(x)[np.argpartition(x, 3)])
# [2 1 3 4]

Any master coder has a “hands-on” mentality with a bias towards action. Try it yourself—play with the function in the following interactive code shell:

Exercise: Change the parameters of your polynomials and print them without the comparisons. Do you understand where they come from?

Master NumPy—and become a data science pro:

Coffee Break NumPy

Related Video

Posted on Leave a comment

ASP.NET Core Updates in .NET 5 Preview 7

Avatar

Sourabh

.NET 5 Preview 7 is now available and is ready for evaluation. Here’s what’s new in this release:

  • Blazor WebAssembly apps now target .NET 5
  • Updated debugging requirements for Blazor WebAssembly
  • Blazor accessibility improvements
  • Blazor performance improvements
  • Certificate authentication performance improvements
  • Sending HTTP/2 PING frames
  • Support for additional endpoints types in the Kestrel sockets transport
  • Custom header decoding in Kestrel
  • Other minor improvements

Get started

To get started with ASP.NET Core in .NET 5 Preview 7 install the .NET 5 SDK.

You need to use Visual Studio 2019 16.7 Preview 5 or newer to use .NET 5 Preview 7. .NET 5 is also supported with the latest preview of Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 5 Preview 6 to .NET 5 Preview 7:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-preview.7.*.
  • Update all Microsoft.Extensions.* package references to 5.0.0-preview.7.*.
  • Update System.Net.Http.Json package references to 5.0.0-preview.7.*.

See the full list of breaking changes in ASP.NET Core for .NET 5.

Upgrade existing Blazor WebAssembly projects

To upgrade an existing Blazor WebAssembly project, update the following properties:

From

<TargetFramework>netstandard2.1</TargetFramework>
<RazorLangVersoin>3.0</RazorLangVersion>

To

<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<UseBlazorWebAssembly>true</UseBlazorWebAssembly>

Also, remove any package references to Microsoft.AspNetCore.Components.WebAssembly.Build, as it is no longer needed.

What’s new?

Blazor WebAssembly apps now target .NET 5

Blazor WebAssembly 3.2 apps have access only to the .NET Standard 2.1 API set. With this release, Blazor WebAssembly projects now target .NET 5 (net5.0) and have access to a much wider set of APIs. Implementing Blazor WebAssembly support for the APIs in .NET 5 is a work in progress, so some APIs may throw a PlatformNotSupportedException at runtime. We’d love to hear from you if you’re blocked by the lack of support for specific APIs.

Updated debugging requirements for Blazor WebAssembly

To enable debugging of Blazor WebAssembly apps in Visual Studio Code, you previously needed to install the JavaScript Debugger (Nightly) extension. This is no longer required as the JavaScript debugger extension is now shipped as part of VS Code. If you’ve previously installed the JavaScript Debugger (Nightly) extension you can now uninstall it. Enabling the preview version of the JavaScript debugger through the Visual Studio Code settings is still required.

Blazor accessibility improvements

The built-in Blazor input components that derive from InputBase now render aria-invalid automatically when the validation fails.

Blazor performance improvements

One of the major areas of investment for Blazor WebAssembly in .NET 5 is improving runtime performance. This is a multifaceted effort. Below are some of the high-level areas being optimized:

  • .NET runtime execution
  • JSON serialization
  • JavaScript interop
  • Blazor component rendering

Improving Blazor WebAssembly runtime performance for .NET 5 in an ongoing effort. This release contains some initial performance improvements, and we expect to share more details on the results of this performance work for future .NET 5 updates.

Certificate authentication performance improvements

We have added caching to certificate authentication in ASP.NET Core. Caching certificate validation significantly improves the performance of certificate authentication. Our benchmarks show a 400% improvement in requests per second once caching was enabled.

You don’t need to make any changes to your app to take advantage of performance improvements; caching is on by default. There are options to tune or disable caching if you wish.

Find out more about certificate authentication in ASP.NET Core in the docs.

Sending HTTP/2 PING frames

HTTP/2 has a mechanism for sending PING frames as a way of ensuring whether an idle connection is still functional. This is especially useful to have when working with long-lived streams that are often idle but only intermittently see activity (for example, gRPC streams). We have added the ability to send periodic PING frames in Kestrel by setting limits on KestrelServerOptions.

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(options => { options.Limits.Http2.KeepAlivePingInterval = TimeSpan.FromSeconds(10); options.Limits.Http2.KeepAlivePingTimeout = TimeSpan.FromSeconds(1); }); webBuilder.UseStartup<Startup>(); });

Support for additional endpoints types in the Kestrel sockets transport

Building upon new API introduced in System.Net.Sockets, the sockets transport (default) in Kestrel now allows you to bind to both existing file handles and unix domain sockets. Support for binding to existing file handles enables using the existing Systemd integration without requiring you to use the libuv transport.

Custom header decoding in Kestrel

We added the ability to specify which System.Text.Encoding to use to interpret incoming headers based on the header name instead of defaulting to UTF-8. You can set the RequestHeaderEncodingSelector property on KestrelServerOptions to specify which encoding to use.

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(options => { options.RequestHeaderEncodingSelector = encoding => { switch (encoding) { case "Host": return System.Text.Encoding.Latin1; default: return System.Text.Encoding.UTF8; } }; }); webBuilder.UseStartup<Startup>(); });

Other improvements

  • For preview 7, we’ve started applying nullable annotations to ASP.NET Core assemblies. We intend on annotating most of the common public API surface of the framework during the 5.0 release.
  • CompareAttribute can now be applied to properties on Razor Page model.
  • Parameters and properties bound from the body are considered required by default.
  • We’ve started applying nullable annotations to ASP.NET Core assemblies. We intend to annotate most of the common public API surface of the framework during the .NET 5 release.
  • Authorization when using endpoint routing now receives the HttpContext rather than the endpoint instance. This allows the authorization middleware to access the RouteData and other properties of the HttpContext that were not accessible though the Endpoint class. The endpoint can be fetched from the context using context.GetEndpoint().
  • The default format for System.Diagnostics.Activity now defaults to the W3C format. This makes distributed tracing support in ASP.NET Core interoperable with more frameworks by default.
  • CompareAttribute can now be applied to properties on a Razor Page model.
  • FromBodyAttribute now supports configuring an option that allows these parameters or properties to be considered optional:

    C#
    public IActionResult Post([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] MyModel model) { ... }

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

Python One Line For Loop With If

This tutorial will teach you how to write one-line for loops in Python using the popular expert feature of list comprehension. After you’ve learned the basics of list comprehension, you’ll learn how to restrict list comprehensions so that you can write custom filters quickly and effectively.

Are you ready? Let’s roll up your sleeves and learn about list comprehension in Python!

List Comprehension Basics

The following section is based on my detailed article List Comprehension [Ultimate Guide]. Read the shorter version here or the longer version on the website—you decide!

This overview graphic shows how to use list comprehension statement to create Python lists programmatically:

List Comprehension

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

Have a look at the following interactive code snippet—can you figure out what’s printed to the shell? Go ahead and click “Run” to see what happens in the code:

Exercise: Run the code snippet and compare your guessed result with the actual one. Were you correct?

Now, that you know about the basics of list comprehension (expression + context!), let’s dive into a more advanced example where list comprehension is used for filtering by adding an if clause to the context part.

List Comprehension for Filtering (using If Clauses)

You can also modify the list comprehension statement by restricting the context with another if statement:

Problem: Say, we want to create a list of squared numbers—but you only consider even and ignore odd numbers.

Example: The multi-liner way would be the following.

squares = [] for i in range(10): if i%2==0: squares.append(i**2) print(squares)
# [0, 4, 16, 36, 64]

You create an empty list squares and successively add another square number starting from 0**2 and ending in 8**2—but only considering the even numbers 0, 2, 4, 6, 8. Thus, the result is the list [0, 4, 16, 36, 64].

Again, you can use list comprehension [i**2 for i in range(10) if i%2==0] with a restrictive if clause (in bold) in the context part to compress this in a single line of Python code:

print([i**2 for i in range(10) if i%2==0])
# [0, 4, 16, 36, 64]

This line accomplishes the same output with much less bits.

Related Article: Python One Line For Loop

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!