Categories
Programming

Use Kotlin’s “with()” function to access object properties with less code

Kotlin borrows an old Pascal trick! Picture of Blaise Pascal and Kotlin logo.

Suppose we have this Kotlin class:

// Kotlin

class ProgrammingLanguage(
    var name: String,
    var creator: String,
    var yearFirstAppeared: Int,
    var remarks: String,
    var isInTiobeTop20: Boolean) {
    
    fun display() {
        println("${name} was created by ${creator} in ${yearFirstAppeared}.")
        println("${remarks}")
        if (isInTiobeTop20) {
            println("This language is in the TIOBE Top 20.")
        }
        println()
    }
}

Creating an instance is pretty straightforward:

// Kotlin

val currentLanguage = ProgrammingLanguage(
    "Pascal", 
    "Nikalus Wirth", 
    1970, 
    "My first compiled and structured language. Also my first exposure to pointers.",
    false)

When you run the code currentLanguage.display(), you get:

Pascal was created by Nikalus Wirth in 1970. My first compiled and structured language. Also my first exposure to pointers.

Suppose you want to change all the properties of currentLanguage and then display the result. If you’re used to programming in other object-oriented programming languages, you’d probably do it like this:

// Kotlin

currentLanguage.name = "Miranda"
currentLanguage.creator = "David Turner"
currentLanguage.yearFirstAppeared = 1985
currentLanguage.remarks = "This was my intro to functional programming. It’s gone now, but its influence lives on in Haskell."
currentLanguage.isInTiobeTop20 = false
currentLanguage.display()

For the curious, here’s the output:

Miranda was created by David Turner in 1985. This was my intro to functional programming. It’s gone now, but its influence lives on in Haskell.

Now, that’s a lot of currentLanguage. You could argue that IDEs free us from a lot of repetitive typing, but it still leaves us with a lot of reading. There should be a way to make the code more concise, and luckily, the Kotlin standard library provides the with() function.

The with() function

One of the first programming languages I learned is Pascal. I cut my teeth on Apple Pascal on my Apple //e and a version of Waterloo Pascal for the ICON computers that the Ontario Ministry of Education seeded in Toronto schools.

Pascal has the with statement, which made it easier to access the various properties of a record (Pascal’s version of a struct) or in later, object-oriented versions of Pascal, an object.

Kotlin borrowed this trick and implemented it as a standard library function. Here’s an example, where I change currentLanguage so that it contains information about BASIC:

// Kotlin

with(currentLanguage) {
    name = "BASIC"
    creator = "John Kemeny and Thomas Kurtz"
    yearFirstAppeared = 1964
    remarks = "My first programming language. It came built-in on a lot of ‘home computers’ in the 1980s."
    isInTiobeTop20 = false
}

This time, when you run the code currentLanguage.display(), you get…

BASIC was created by John Kemeny and Thomas Kurtz in 1964. My first programming language. It came built-in on a lot of ‘home computers’ in the 1980s.

…and the code is also a little easier to read without all those repetitions of currentLanguage.

with() is part of the Kotlin standard library. It has an all-too-brief writeup in the official docs, and as a standard library function, you can see its code.

Categories
Programming

Don’t use Kotlin’s “for” loop when you can use its “repeat()” function

Suppose you wanted to print the string “Hello there!” three times. In any language that borrows its syntax from C, you’d probably use the classic for loop, as shown below:

// C99
for (int i = 0; i < 3; i++) {
    printf("Hello there!\n");
}

// JavaScript
for (let i = 0; i < 3; i++) {
    console.log("Hello there!");
}

With Kotlin’s for loop, you have a couple of options:

// Kotlin

// Here’s one way you can do it:
for (index in 0 until 3) {
    println("Hello there!")
}

// Here’s another way:
for (i in 1..3) {
    println("Hello there!")
}

If you’re used to programming in a C-style language, you’ll probably reach for a for loop when you need to perform a task a given number of times. The Kotlin language designers noticed this and came up with something more concise: the repeat() function:

repeat(3) {
    println("Hello there!")
}

As you can see, using repeat() give you a shorter, easier to read line than for. And in most cases, shorter and easier to read is better.

Do you need to know the current iteration index? Here’s how you’d get that value:

fun main() {
    repeat(3) { iteration ->
    	println("Hello there from iteration $iteration!")
    }
}

Remember, you can use whatever variable name you want for that index, as long as it’s a valid name:

fun main() {
    repeat(3) { thingy ->
    	println("Hello there from iteration $thingy!")
    }
}

Note that repeat() is for performing a task a known number of times, without exceptions. It’s a function that takes a closure, not a loop structure. This means that the break and continue statements won’t work:

// This WILL NOT compile!

fun main() {
    repeat(3) { iteration ->

        // 🚨🚨🚨 You can’t do this 🚨🚨🚨
        if (iteration == 1) {
            break
        }

        // 🚨🚨🚨 You can’t do this, either 🚨🚨🚨
        if (iteration == 2) {
            continue
        }

        // “break” and “continue” work only
        // inside a loop, and repeat()
        // *isn’t* a loop...
        // ...it’s a *function*!

    	println("Hello there from iteration $iteration!")
    }
}

For the curious, here’s the source code for repeat():

@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0 until times) {
        action(index)
    }
}

To summarize: If you need to perform a task n times in Kotlin — and only n times — use repeat instead() of for!

Categories
Artificial Intelligence Meetups Programming What I’m Up To

ChatGPT’s name suggestions for Tampa Bay’s new hands-on AI coding meetup

Yesterday, I posted an article titled Would you be interested in a hands-on A.I. coding meetup?. It got over a thousand impressions on LinkedIn alone, so I’m already taking the first steps into making it real, with the help of ChatGPT…

profile imageI need names for a meetup group in Tampa Bay where the main topic of discussion is AI.
ChatGPT icon PNG and SVG Vector Free DownloadHere are a few name suggestions for your AI meetup group in Tampa Bay:

1. Tampa Bay AI Alliance
2. AI Minds of the Bay
3. The Bay Area AI Hub
4. The AI Network of Tampa
5. Tampa AI Innovators
6. The AI Roundtable of Tampa Bay
7. AI Futurists of Tampa
8.The AI Think Tank of Tampa Bay
9. The Bay Area AI Society
10. Tampa’s AI Connection.

I hope these names give you some inspiration for your group.
profile imageCan you suggest more?
ChatGPT icon PNG and SVG Vector Free DownloadOf course! Here are some more name suggestions for your AI meetup group in Tampa Bay:

11. The AI Nexus of Tampa Bay
12. The Tampa Bay AI Enthusiasts
13. AI Mavericks of the Bay
14. The Bay’s AI Pioneers
15. The Tampa AI Frontier
16. The AI Collective of Tampa Bay
17. The AI Vanguard of Tampa
18. The Tampa Bay AI Community
19. The AI Innovations of Tampa Bay
20. The AI Synergy of Tampa Bay.

These names aim to emphasize the cutting-edge and innovative nature of AI and the community aspect of your meetup group.
profile imageCan you suggest names that suggest that hands-on coding is involved?
ChatGPT icon PNG and SVG Vector Free DownloadSure, here are some name suggestions that emphasize the hands-on coding aspect of your AI meetup group in Tampa Bay:

1. Code AI Tampa
2. The Bay Area AI Coders
3. AI Builders of Tampa
4. The Tampa AI Code Lab
5. The AI Developers of Tampa Bay
6. The Bay’s AI Code Sprint
7. Tampa AI Coders Collective
8. The AI Code Academy of Tampa Bay
9. The Tampa Bay AI Hackers
10. The AI Coding Crew of Tampa.

These names suggest a focus on hands-on coding and emphasize the practical and technical aspect of AI development.
profile imageHow about names for hands-on coding meetups in Tampa that sometimes include AI?
ChatGPT icon PNG and SVG Vector Free DownloadHere are some name suggestions for hands-on coding meetups in Tampa that sometimes include AI topics:

1. Tampa Code & AI
2. The Bay’s Code & AI Mixer
3. The AI & Code Connection of Tampa
4. The Tampa Code & AI Summit
5. The Bay Area Code & AI Hub
6. The Code & AI Network of Tampa
7. The AI & Code Innovators of Tampa
8. The Tampa Code & AI Symposium
9. The Bay’s Code & AI Innovations
10. The Code & AI Minds of Tampa.

These names suggest a broader focus on hands-on coding, with a secondary emphasis on AI topics and how the two intersect.
profile imageI need more names.
ChatGPT icon PNG and SVG Vector Free DownloadHere are some additional name suggestions for hands-on coding meetups in Tampa that sometimes include AI topics:

1. Code to AI Tampa Bay
2. The Bay’s AI and Code Collaborative
3. Tampa Bay Coders and AI Enthusiasts
4. The Code & AI Exchange of Tampa Bay
5. The Tampa Bay AI-Coded Meetup
6. The Bay Area Code-AI Group
7. The Tampa AI & Coding Collective
8. The Code-AI Circuit of Tampa Bay
9. The Tampa Bay AI-Driven Coders
10. The Bay Area AI-Coded Community.

These names aim to convey the fusion of AI and coding, with a focus on practical skills and collaborative learning opportunities.
profile imageMore names like that, but also take advantage that the Tampa Bay area is also known as “Suncoast”.
ChatGPT icon PNG and SVG Vector Free DownloadSure! Here are some name suggestions that incorporate the “Suncoast” reference and emphasize the fusion of AI and coding:

1. Suncoast AI Coders
2. Tampa Bay Suncoast AI
3. The Suncoast AI & Code Society
4. The AI Suncoast Coders of Tampa Bay
5. The Suncoast AI-Coding Collective
6. The Tampa Bay Suncoast AI-Coders
7. The Suncoast AI & Code Connection
8. The AI-Coded Suncoast Community of Tampa Bay
9. Suncoast AI Hackers of Tampa
10. The Tampa Bay Suncoast AI Circuit.

These names play off the “Suncoast” moniker to emphasize the local nature of the group while highlighting the fusion of AI and coding.

Categories
Conferences Programming What I’m Up To

I’m going to PyCon US 2023!

The US edition of the Python Conference — better known an PyCon US — takes place in Salt Lake City in April, and I’m going to be there minding Okta’s Auth0 booth!

I was at PyCon’s grand return to in-person conferencing last year, where I got to learn a little more about Python, meet a lot of the Python community’s nice folks, catch up with old friends and make new ones, and even jam onstage at Anaconda’s opening night party!

This is going to be a special PyCon, as it’ll be the conference’s 20th anniversary. It’s something worth celebrating, as Python has faced some challenges in that time. When PyCon started in 2003, it had been overshadowed by Perl and PHP. Soon afterward, it was eclipsed by Ruby, thanks to Ruby on Rails. But over the past 10 years, thanks to its simplicity, power, and vast collections of libraries — especially those for data science and machine learning — Python has experienced a renaissance. This gathering of the Python community should be a celebration of Python’s journey, and an interesting future ahead with ChatGPT and other upcoming AIs of its ilk.

Drop by the Auth0/Okta booth and say “hi,” or just simply start a conversation with me wherever you see me at PyCon. As always, I’ll be very easy to find. I’m the one with the accordion!

When does PyCon US 2023 happen? It depends on which parts you want to attend:

  • The main conference, which has the keynotes, general sessions, talk tracks, expo hall (where I’ll be spending most of my time), and so on, takes place from Friday, April 21 through Sunday, April 23 inclusive.
  • The opening reception happens on the evening before the main conference: Thursday, April 20.
  • The sponsor presentations and summits take place before the main conference, on Wednesday, April 19 and Thursday, April 20.
  • The job fair happens on Sunday, April 23.
  • And finally, the sprints — where you can contribute to Python itself or one of its libraries — happen from Monday, April 24 through Thursday, April 27.

How much does it code to attend PyCon? It depends on how you plan to attend.

  • As an individual — that is, on your own, with your own money, and without the support of a corporation: US$400.
  • As a corporate attendee — that is, your cost is being covered by a corporation: US$750.
  • As a student — that is, you’re currently in high school, college, university, or some other educational institution where you spend the majority of your time, as opposed to full-time work: US$100.
  • As an online attendee: US$100.

You can find out more at PyCon’s Registration Information page.

Categories
Mobile Programming

How to sort import statements in Android Studio

When you do native Android development, you use import statements. A lot of import statements. Even the “Hello World”-ish template app that Android Studio generates when you select Empty Compose Activity contains 11 import statements:

Worse still, you end up adding more import statements over time, as you add more code. It’s easy to end up with a screenful or more of import statements, which makes them more difficult to manage.

How I used to sort imports in Android Studio

I used to keep import statements organized by occasionally rearranging them into alphabetical order by hand. This soon became annoying, so I automated the process with a simple Jupyter Notebook. Using this Notebook, I’d copy the import statements…

…and then paste them into a variable, which would then be processed with a Python one-liner:

# Python
print('\n'.join(sorted(import_lines.splitlines())))

Here’s screenshot showing how I last used my import-organizing Jupyter Notebook:

After running it, I’d copy the one-liner’s output and paste it back into my Android code. Problem solved!

How to sort imports in Android Studio

I’ve only recently found out about the Optimize Imports option in Android Studio (and many other JetBrains IDEs), and it does a better job that my Jupyter Notebook, which simply puts the imports in alphabetical order. It also:

  • Deletes duplicate import lines (I should update my script to do the same), and
  • consolidates imports when possible.

Categories
Mobile Programming

Learn how to add Auth0 login/logout to Android apps

“Add login/logout to Android apps,” featuring the screens from the demo app for the tutorial.

Android is the most popular operating system in the world and runs on more devices than any other OS. With 3 billion users and 70% of the mobile OS market share, you want to write apps for Android! And sooner or later, you’ll need to write an Android app that requires the user to log in and log out.

This video and written tutorial — starring and written by Yours Truly — shows you how to do it with Auth0 by Okta.

Here’s the video…

…here’s the article…

Screenshot from the article “Get Started with Android Authentication Using Kotlin”.
Tap to go to the article.

…and here’s the Github repository containing both the starter and the completed projects for the tutorial.

I hope you find them helpful, and if you have any questions, feel free to email me or ask in the comments!

Categories
Artificial Intelligence Programming

Watch these videos if you want to learn about neural networks

If the recent popularity of ChatGPT and other recent AI advancements has got you interested in neural networks, how they work, and how you might implement one, these three video series should help you get started.

Note that while you might get some basic insights into neural networks by simply watching the videos, the real benefit comes from doing the exercises shown in the video and experimenting with the math and programming they feature.

Neural networks from a general point of view

If you’re new to neural networks, you’ll want to start with the Neural Networks video series from Grant Sanderson, whose YouTube channel, 3Blue1Brown, is a great place to learn math and algorithms.

  • Number of videos in the playlist: 4
  • Total length: 1 hour, 4 minutes
  • Published: October – November 2017
  • Math difficulty: 1 out of 5 in the first video, up to about 3 out of 5 in the last two. You can’t do neural networks without linear algebra and differential calculus, but this series works hard at making them as easy to understand as possible.
  • Programming difficulty: 0 out of 5. This is all about the general principles behind neural networks and doesn’t cover any programming at all.

Neural networks from a math point of view

Ever wish you had a math teacher who can make complex topics easier to understand with fun explanations and ukulele music breaks? You do now — Josh Starmer, host of the StatQuest YouTube channel, is that math teacher, and his Neural Networks / Deep Learning video series looks deep into the math behind neural networks.

  • Number of videos in the playlist: 20
  • Total length: 5 hours, 28 minutes
  • Published: August 2020 – January 2023
  • Math difficulty: 0 out of 5 in the intro video, working its way up to 3 out of 5 as the series progresses. Once again, linear algebra and differential calculus are involved, but like 3Blue1Brown’s Grant Sanderson, Josh Starmer does a lot to make math concepts easier to understand.
  • Programming difficulty: 0 out of 5, until the last three videos, which cover using Python and the PyTorch library. If you’re comfortable with OOP, you’ll do fine.

Neural networks from a Python programmer’s point of view

Are you a Python programmer? Would you like to learn neural networks from the co-founder of OpenAI and the former director of artificial intelligence for Tesla? Then Andrej Karpathy’s Neural Networks: Zero to Hero video series is for you. He says that all you need to understand his video is a “basic knowledge of Python and a vague recollection of calculus from high school,” but you should keep in mind that this is someone who eats, sleeps, and breathes neural networks and Python. I’m currently working my way through these videos, and if I can follow them, chances are that you can too.

  • Number of videos in the playlist: 20
  • Total length: 12 hours, 23 minutes
  • Published: August 2022 – January 2023
  • Math difficulty: 3 out of 5, as there’s what Karpathy calls “high school calculus.” If you took first-year calculus in university and remember the basics of differential calculus — including the bit where dy/dx doesn’t mean you can simply cancel out the d’s — you’ll be fine.
  • Programming difficulty: 3.5 out of 5. You’ve got to be comfortable with OOP, lambda functions, and recursion for most of the videos, and in the final video, Let’s Build GPT, you should be familiar with PyTorch. You should also have Jupyter Notebook or one of its variants set up.