Jump to content

Blogger

Blog Bot
  • Joined

  • Last visited

    Never

Everything posted by Blogger

  1. by: Lee Meyer Fri, 25 Jul 2025 13:48:36 +0000 Do we invent or discover CSS tricks? Michelangelo described his sculpting process as chiseling away superfluous material to reveal the sculpture hidden inside the marble, and Stephen King says his ideas are pre-existing things he locates and uncovers “like fossils in the ground.” Paragraph one is early for me to get pretentious enough to liken myself to those iconic creative forces, but my work on CSS-Tricks feels like “discovering,” not “inventing,” secret synergies between CSS features, which have been eyeing each other from disparate sections of the MDN web docs and patiently waiting for someone to let them dance together in front of the world. Matchmaking for CSS features A strategy for finding unexpected alliances between CSS features to achieve the impossible is recursive thinking, which I bring to the CSS world from my engineering background. When you build recursive logic, you need to find an escape hatch to avoid infinite recursion, and this inception-style mindset helps me identify pairings of CSS features that seem at odds with each other yet work together surprisingly well. Take these examples from my CSS experiments: What if view-timeline took control of the thing that triggers view-timeline? This led to a pairing between view-timeline and position: fixed. These two features are like a bickering yet symbiotic “odd couple” at the heart of my web-slinger.css library for scroll-triggered animations in pure CSS. What if keyframe animations could trigger other keyframe animations? This idea led to a throuple comprised of keyframe animations, style queries, and animation-play-state, which together can simulate collision detection in CSS. What if scroll-state:(scrollable: value) could control which directions are scrollable? That question led to a scrollytelling version of a “Choose Your Own Adventure,” which — wait, I haven’t published that one yet, but when I do, try to look surprised. Accepting there is nothing new under the sun Indeed, Mark Twain thought new ideas don’t exist — he described them as illusions we create by combining ideas that have always existed, turning and overlaying them in a “mental kaleidoscope” to “make new and curious combinations.” It doesn’t mean creating is easy. No more than a safe can be cracked just by knowing the possible digits. This brings back memories of playing Space Quest III as a kid because after you quit the game, it would output smart-aleck command-line messages, one of which was: “Remember, we did it all with ones and zeros.” Perhaps the point of the mock inspirational tone is that we likely will not be able to sculpt like Michelangelo or make a bestselling game, even if we were given the same materials and tools (is this an inspirational piece or what?). However, understanding the limits of what creators do is the foundation for cracking the combination of creativity to open the door to somewhere we haven’t been. And one truth that helps with achieving magic with CSS is that its constraints help breed creativity. Embracing limitations Being asked “Why would you do that in CSS when you could just use JavaScript?” is like if you asked me: “Why would you write a poem when it’s easier to write prose?” Samuel Coleridge defined prose as “words in their best order,” but poetry as “the best words in the best order.” If you think about it, the difference between prose and poetry is that the latter is based on increased constraints, which force us to find unexpected connections between ideas. Similarly, the artist Phil Hansen learned that embracing limitation could drive creativity after he suffered permanent nerve damage in his hand, causing it to jitter, which prevented him from drawing the way he had in the past. His early experiments using this new mindset included limiting himself to creating a work using only 80 cents’ worth of supplies. This dovetails with the quote from Antoine de Saint-Exupéry often cited in web design, which says that perfection is achieved when there is nothing left to take away. Embracing nothingness The interesting thing about web design is how much it blends art and science. In both art and science, we challenge assumptions about whether commonsense relationships of cause and effect truly exist. Contrary to the saying in vernacular that “you can’t prove a negative,” we can. It’s not necessarily harder than proving a positive. So, in keeping with the discussion above of embracing limitations and removing the superfluous until a creation reveals itself, many of my article ideas prove a negative by challenging the assumption that one thing is necessary to produce another. Maybe we don’t need JavaScript to produce a Sudoku solver, a Tinder-style swiper, or a classic scroll-driven animation demo. Maybe we don’t need checkbox hacks to make CSS games. Maybe we don’t need to hack CSS at all to recreate similar effects to what’s possible in browsers that support the CSS if() function. Maybe I can impart web dev wisdom on CSS-Tricks without including CSS at all, by sharing the “source code” of my thought process to help make you a better developer and a better person. Going to extremes Sometimes we can make a well-worn idea new again by taking it to the extreme. Seth Godin coined the term “edgecraft” to describe a technique for generating ideas by pushing a competitive advantage as far to the edge as the market dares us to go. Similarly, sometimes you can take an old CSS feature that people have seen before, but push it further than anyone else to create something unique. For example: CSS-Tricks covered checkbox hacks and radio button hacks back in 2011. But in 2021, I decided to see if I could use hundreds of radio button hacks using HTML generated with Pug to create a working Sudoku app. At one point, I found out that Chrome dev tools can display an infinite spinner of death when you throw too much generated CSS at it, which meant I had to limit myself to a 4×4 Sudoku, but that taught me more about what CSS can do and what it can’t. The :target selector has existed since the 2000s. But in 2024, I took it to the extreme by using HAML to render the thousands of possible states of Tic Tac Toe to create a game with a computer opponent in pure CSS. At one point, CodePen refused to output as much HTML as I had asked it to, but it’s a fun way for newcomers to learn an important CSS feature; more engaging in my opinion than a table of contents demo. Creating CSS outsider art Chris Coyier has written about his distaste for the gatekeeping agenda hidden behind the question of whether CSS is a programming language. If CSS isn’t deemed as “real” programming, that can be used as an excuse to hold CSS experts in less esteem than people who code in imperative languages, which leads to unfair pay and toxic workplace dynamics. But maybe the other side always seems greener due to the envy radiating from the people on that side, because as a full-stack engineer who completed a computer science degree, I always felt left out of the front-end conversations. It didn’t feel right to put “full stack developer” on my résumé when the creation of everything users can see in a web app seemed mysterious to me. And maybe it wasn’t just psychosomatic that CSS made my head hurt compared to other types of coding because research indicates if you do fMRIs on people who are engaged in design tasks, you see that design cognition appears to involve a unique cognitive profile compared to conventional problem-solving, reflected in the areas of the brain that light up on the fMRIs. Studies show that the brain’s structure changes as people get better at different types of jobs. The brain’s structural plasticity is reminiscent of the way different muscles grow more pronounced with different types of exercise, but achieving what some of my colleagues could with CSS when my brain had been trained for decades on imperative logic felt about as approachable as lifting a car over my head. The intimidation I felt from CSS started to change when I learned about the checkbox hack because I could relate to hiding and showing divs based on checkboxes, which was routine in my work in the back of the front-end. My designer workmate challenged me to make a game in one night using just CSS. I came up with a pure text adventure game made out of radio button hacks. Since creative and curious people are more sensitive to novel stimuli, the design experts on my team were enthralled by my primitive demo, not because it was cutting-edge gameplay but because it was something they had never seen before. My engineering background was now an asset rather than a hindrance in the unique outsider perspective I could bring to the world of CSS. I was hooked. The hack I found to rewire my brain to become more CSS-friendly was to find analogies in CSS to the type of problem-solving I was more familiar with from imperative programming: CSS custom properties are like reactive variables in Vue. The :target selector in CSS is like client-side routing in a single-page application. The min() and max() functions in CSS can be used to simulate some of the logical operations we take for granted in imperative programming. So if you are still learning web development and CSS (ultimately, we are all still learning), instead of feeling imposter syndrome, consider that the very thing that makes you feel like an outsider could be what enables you to bring something unique to your usage of CSS. Finding the purpose Excited as I was when my CSS hacking ended up providing the opportunity to publish my experiments on CSS-Tricks, the first comment on the first hack I published on CSS-Tricks was a generic, defeatist “Why would you do that?” criticism. The other comments popped up and turned out to be more supportive, and I said in a previous article that I’ve made my peace with the fact that not everybody will like my articles. However, this is the second article in which I’ve brought up the critical comment from back in 2021. Hmm… Surely it wasn’t the reason I didn’t write another CSS-Tricks article for years. And it’s probably a coincidence that when I returned to CSS-Tricks last year, my first new article was a CSS hack that lends itself to accessibility after the person who left the negative comment about my first article seemed to have a bee in their bonnet about checkbox hacks breaking accessibility, even in fun CSS games not intended for production. Then again, limiting myself to CSS hacking that enables accessibility became a source of inspiration. We can all do with a reminder to at all times empathize with users who require screen readers, even when we are doing wacky experimental stuff, because we need to embrace the limitations not just of CSS but of our audience. I suppose the reason the negative comment continues to rankle with me is that I agree that clarifying the relevance and purpose of a CSS trick is important. And yet, if I’m right in saying a CSS trick is more like something we discover than something we make, then it’s like finding a beautiful feather when we go for a walk. At first, we pick it up just because we can, but if I bring you with me on the journey that led to the discovery, then you can help me decide whether the significance is that the feather we discovered makes a great quill or reveals that a rare species of bird lives in this region. It’s a journey versus destination thing to share the failures that led to compromises and the limitations I came up against when pushing the boundaries of CSS. When I bring you along on the route to the curious item I found, rather than just showing you that item, then after we part ways, you might retrace the steps and try a different fork in the path we followed, which could lead you to discover your own CSS trick. How to Discover a CSS Trick originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
  2. by: Abhishek Prakash Fri, 25 Jul 2025 17:17:39 +0530 I am a strong believer in micro-learning. Sure, we have long courses on huge topics like Linux and Ansible, but we also have courses on relatively smaller topics like SSH and Kubernetes Operators. Now, we have a new micro-course on systemd. Like most of our educational material, this too is a hands-on course. Meaning, you will learn by following the steps on your system. The systemd Playbook: Learn by DoingMaster systemd the practical way—one lab at a time.Linux HandbookTeam LHBThis systemd course is for Pro members only, so if you don't have a Pro membership yet, perhaps it is time to upgrade your membership. We have just launched the "lifetime membership" option. For a single payment, you get the Plus membership of the Learner tier forever. No recurring payment, you pay just once and enjoy forever. First 50 lifetime members get it for just $99 instead of $139. Get Lifetime membership for just $99       This post is for subscribers only Subscribe now Already have an account? Sign in
  3. by: Abhishek Prakash Fri, 25 Jul 2025 16:41:06 +0530 This post is for subscribers only Subscribe now Already have an account? Sign in
  4. by: Geoff Graham Thu, 24 Jul 2025 16:16:30 +0000 Brad Frost introduced the “Atomic Design” concept wayyyy back in 2013. He even wrote a book on it. And we all took notice, because that term has been part of our lexicon ever since. It’s a nice way to divide web designs into separate layers of concern, leaning into biology terms to help scope their context by size: Atoms Molecules Organisms Templates Pages Atoms are part of molecules, which are part of organisms, which make up templates, which become full-blown pages. It’s composable design that’s centered on consistency, reusability, and maintainability. Beautiful. We’ve covered this a bunch over the years. Want to get fully versed in how it works? If so, you’re in luck because Brad and his brother, Ian, are in the process of publishing an entire online course about Atomic Design. It’s in presale for $50 (with discounts for teams). Normally, I like to jump into a course and check it out before sharing it. But this is Brad and all he does is wonderful things. For example: The guy arranged his very own concert! He inspires folks to live creatively and authentically with his Wake Up Excited! podcast. There’s another podcast where he encourages designers and developers to Open Up! about their careers and what drives them. I get to participate in that one! Dude is a solid drummer who records himself playing along to his favorite albums, completely unrehearsed. He’s got a crap ton of tracks he writes and records as well. Oh, and his newsletter is pretty awesome, too. And I’m sure I’m leaving out more things he has floating around the web, but you get the point: he’s incredibly knowledgeable on the topic, is a highly-effective educator and speaker, and most importantly, has an infectious positive posture about him. I know the Atomic Design course will be just as awesome. Preordered! Atomic Design Certification Course originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
  5. by: Abhishek Prakash Thu, 24 Jul 2025 05:03:42 GMT I know readers in the US will find it difficult to believe but it seems that Linux desktop usage are all time high in the United States of America. That's worth a celebration 🥂 Made Linux Great Again? Linux Desktop Usage Hits Record High in the U.S.A small, yet notable bump.It's FOSS NewsSourav Rudra💬 Let's see what else you get in this edition Firefox trying to redeem itself.A RAT making its way into Arch Linux.Intel's Linux distribution being discontinued.And other Linux news, tips, and, of course, memes! SPONSORED PikaPods allows you to quickly deploy your favorite open source software. All future updates are handled automatically by PikaPods while you enjoy using the software. PikaPods also share revenue with the original developers of the software. You get a $5 free credit to try it out and see if you can rely on PikaPods. Try PikaPods with $5 free credits 📰 Linux and Open Source NewsIntel's Clear Linux OS is no more after the silicon giant pulls the plug on it.NVIDIA has teamed up with RISC-V International to bring CUDA to RISC-V CPUs.Firefox has finally added support for WebGPU. You can now try it out on the Firefox 141 release.A malicious actor managed to slip in some malware into the AUR. It was quickly discovered and disabled. One more reason to stick with the official repositories of your distribution. Someone Slipped a RAT into Arch Linux!A sneaky menace made its way into Arch User Repository. Another reminder to not blindly trust packages from AUR, PPA and even from Snapcraft.It's FOSS NewsSourav RudraIs Europe Losing Control of Its Data to Chinese Apps? Case Filed Against TikTok, WeChat and AliExpressnoyb files complaints against TikTok, AliExpress, and WeChat over GDPR violations.It's FOSS NewsSourav Rudra🧠 What We’re Thinking AboutAn Italian YouTuber is facing jailtime over retro-gaming handheld reviews. Those devices come pre-installed with emulators and retro games. Jailtime for Retro Game Console Reviews? Italy’s Copyright Enforcement Sparks DebateItalian YouTuber raided over handheld review, faces possible jail time.It's FOSS NewsSourav Rudra🧮 Linux Tips, Tutorials, and LearningsDon't know if you already use it, but creating templates in LibreOffice saves time in creating new document on a repetition. From invoices to letters, make good use of the template feature. Speaking of templates, you can add the missing 'create new document' option in right-click context menu in Ubuntu and other distros using GNOME desktop. I don't understand why it was removed in the first place. Just GNOME things. I understand that in the age of Snaps and Flatpaks, PPAs don't have the same charm as they used to have before the 2020s. Still, blindly adding PPAs creates havoc for new Ubuntu/Mint users. And that's why I recommend reading this PPA guide I wrote a few years ago. Once you understand how it works, you won't have the repository related error with the updates. PPA in Ubuntu Linux [Definitive Guide]An in-depth article that covers almost all the questions around using PPA in Ubuntu and other Linux distributions.It's FOSSAbhishek Prakash Desktop Linux is mostly neglected by the industry but loved by the community. For the past 13 years, It's FOSS has been helping people use Linux on their personal computers. And we are now facing the existential threat from AI models stealing our content. If you like what we do and would love to support our work, please become It's FOSS Plus member. It costs $24 a year (less than the cost of a burger meal each month) and you get an ad-free reading experience with the satisfaction of helping the desktop Linux community. Join It's FOSS Plus 👷 AI, Homelab and Hardware CornerIf you are unsure of Windsurf's fate, you can opt for one of these alternative editors instead. Unsure About the Future of Windsurf? Try These Alternative Vibe Coding Editors on LinuxWindsurf’s been a bit rocky lately. Time for a change?It's FOSSSourav RudraHere are 17 cool project ideas for your Arduino. 17 Cool Arduino Project Ideas for DIY EnthusiastsArduino is an open-source electronics platform that combines both open source software and hardware to let people make interactive projects with ease. You can get Arduino-compatible single board computers and use them to make something useful. In addition to the hardware, you will also need to know the Arduino languageIt's FOSSAnkush DasI came across this cool NAS plus local AI device for homelab starters on Kickstarter. Out of my budget but hey, we can window shop once in a while, right? Explore ORICO on Kickstarter✨ Project HighlightA new way to game on Linux is here. GeForce Infinity allows Linux gamers to play games using GeForce NOW. NVIDIA’s Cloud Gaming Service GeForce NOW Has an App on LinuxAlthough it is an unofficial app, you can use this app to play GeForce NOW games on Linux with some ease and extra features.It's FOSS NewsSourav RudraHere's a new open source grammar checker which is surely worth a try. It has a great future ahead as it is backed by the makers of WordPress. I Found a New Open Source Grammar Checker Tool And I Like it... Well... Kind ofSometime simple is better. This new open source grammar checker is what we need in this age of data collection and AI.It's FOSSAbhishek Prakash📽️ Videos I am Creating for YouAnd I reviewed the magnificent Pironman 5 Max case. Subscribe to It's FOSS YouTube Channel🧩 Quiz TimeSeeing that a new Debian release is around the corner, can you recall all its codenames? Crossword Quiz on Debian Release CodenamesDebian fan? Test your knowledge of various Debian releases in this fun and interactive crossword.It's FOSSAbhishek Prakash💡 Quick Handy TipFor GNOME apps like Nautilus file manager, Software, and several others, you can use the shortcut CTRL+? (which is CTRL+SHIFT+/) on your keyboard to get a list of available keyboard shortcuts for that app. If the app in focus has some keyboard shortcuts available, it will be opened in a new app window. 🤣 Meme of the WeekThat's how it feels on some Linux subreddits and forums. Thankfully, It's FOSS Community forum is much more welcoming. 🗓️ Tech TriviaWhen Apple released Mac OS 8 on July 26, 1997, it was a huge hit, selling over 1.2 million copies in two weeks. This success significantly boosted the company during a tough time, as it faced financial struggles and strong competition from Microsoft. 🧑‍🤝‍🧑 FOSSverse CornerA long time FOSSer has become active again; it's good to see people return. Back on Linux After Some Time on Windows 11I am glad i am back on Linux mint currently installing stuff that will help me with my company stuffIt's FOSS CommunityMoka_Noctis❤️ With lovePlease share it with your Linux-using friends and encourage them to subscribe (hint: it's here). Share the articles in Linux Subreddits and community forums. Follow us on Google News and stay updated in your News feed. Opt for It's FOSS Plus membership and support us 🙏 Enjoy FOSS 😄
  6. by: Abhishek Prakash Wed, 23 Jul 2025 19:13:51 +0530 Regex (Regular Expressions) is like a super-powered search function with pattern recognition. Think of it as upgrading from "find this exact word" to "find anything that matches this flexible pattern." It's your Swiss Army knife for text manipulation. Core Concepts: Building BlocksLiteral CharactersThe simplest regex - exactly what you type. # Find "cat" in text grep "cat" file.txt Metacharacters: The Special OperatorsThese characters have superpowers - they don't match themselves but control pattern behavior. # These are metacharacters: . ^ $ * + ? { } [ ] \ | ( ) Essential Regex Symbols Reference Symbol Meaning Example Matches . Any single character c.t cat, cut, c@t ^ Start of line ^Hello Lines starting with "Hello" $ End of line bye$ Lines ending with "bye" * Zero or more of preceding ca*t ct, cat, caat, caaat + One or more of preceding ca+t cat, caat, caaat ? Zero or one of preceding colou?r color, colour {n} Exactly n occurrences a{3} aaa {n,} n or more occurrences a{3,} aaa, aaaa, aaaaa {n,m} Between n and m occurrences a{2,4} aa, aaa, aaaa [abc] Any character in brackets [aeiou] Any vowel [^abc] Any character NOT in brackets [^0-9] Any non-digit [a-z] Character range [a-zA-Z] Any letter \ Escape special characters \. Literal dot | OR operator cat|dog cat or dog () Grouping (cat)+ cat, catcat, catcatcat Character Classes: Pre-Built Shortcuts Shorthand Equivalent Meaning \d [0-9] Any digit \D [^0-9] Any non-digit \w [a-zA-Z0-9_] Word character \W [^a-zA-Z0-9_] Non-word character \s [ \t\n\r\f] Whitespace \S [^ \t\n\r\f] Non-whitespace Practical examples to practice regex knowledgeHere are some examples of regex in action. I am using grep command for pattern matching. You can also use sed or awk or even a programming language like Python. 1. Basic email validationThis is the content of emails.txt that contains some invalid email formats too. john.doe@example.com invalid-email mary@company.co.uk test@test admin@server.local not_an_email.com jane+newsletter@gmail.com The goal is to only match the valid email addresses. Focus on the regex pattern inside quotes. grep -E "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" emails.txt Email construction is like building blocks: ^ starts from line beginning, [a-zA-Z0-9._%+-]+ matches username with one or more occurence of letters/numbers/and symbols, @ is literal @, [a-zA-Z0-9.-]+ matches domain name with any occurences of letters/numbers, \. matches literal dot, [a-zA-Z]{2,} matches extension (2+ letters), $ ensures line ends here. This will be the output of the command: john.doe@example.com mary@company.co.uk admin@server.local jane+newsletter@gmail.com 2. Phone number extractionThis is the content of contacts.txt that contains some invalid phone number formats too. The correct format is to have 3 digits for area code, 3 for exchange and 4 for number. This is typical US style of phone number, and they often have phone numbers displayed with separators, too. John Smith: (555) 123-4567 Call me at 555.987.6543 Phone: 555-555-5555 Invalid: 55-555-5555 Emergency: (911) 911-9111 Contact: 5551234567 Here's the regex that filters only the correct phone numbers. The -o ensures that regex only returns the matching part from the line. grep -oE "\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}" contacts.txt Phone patterns as flexible templates: \(? = optional opening parenthesis, \d{3} = exactly 3 digits (area code), \)? = optional closing parenthesis, [-.\s]? = optional separator (dash/dot/space), \d{3} = 3 digits (exchange), another optional separator, \d{4} = 4 digits (number). This will be the output of the command. (555) 123-4567 555.987.6543 555-555-5555 (911) 911-9111 Did you notice the impact of -o option of grep? The putput doesn't contain the entire matching lines, only the part that matches the 3. Extract IP addressThis is our log.txt file that contains some IP addresses. 2024-01-15 10:30:22 192.168.1.100 GET /index.html 2024-01-15 10:31:45 10.0.0.55 POST /api/login Invalid IP: 999.999.999.999 2024-01-15 10:32:10 172.16.254.1 GET /dashboard Not an IP: 192.168.1 2024-01-15 10:33:33 8.8.8.8 DNS lookup This is the regex that will extract the matching pattern: grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" log.txt IP addresses follow dot-separated quartets: ([0-9]{1,3}\.) captures 1-3 digits followed by literal dot, {3} repeats this pattern 3 times, [0-9]{1,3} matches final 1-3 digits. Like building "123.456.789.012" format. 192.168.1.100 10.0.0.55 999.999.999.999 172.16.254.1 8.8.8.8 Yes, I know that 999.999.999.999 is not a valid IP address but the idea here was to match numbers in the pattern and extract them. 4. Password strength checkerHere's a sample file with random passwords of varying length. Password123 weakpass STRONGPASSWORD Strong123Pass 12345678 Abcd1234 short1A VeryLongButNoNumbers This is the regex that you can use with grep: grep -E "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$" passwords.txt Lookaheads act like security checkpoints: ^ starts line, (?=.*[a-z]) = "somewhere ahead find lowercase", (?=.*[A-Z]) = "somewhere ahead find uppercase", (?=.*\d) = "somewhere ahead find digit", .{8,} = match 8+ characters, $ ends line. All conditions must pass. Run it and you should see an output like this: Password123 Strong123Pass Abcd1234 5. URL extractionHere's a sample HTML code and we are going to extract the URLs from it. <html> <body> Visit https://example.com for more info. Check out http://blog.company.net/articles Invalid: ftp://files.server.com Also see https://secure.payment.org/checkout?id=123 Email: mailto:contact@site.com </body> </html> This is the regex you could use. Again, mind the use of -o to extract only the matching part of the lines. grep -oE "https?://[a-zA-Z0-9./?=_%:-]*" webpage.html URL patterns mimic web addresses: https? = "http" with optional "s" (s? means zero or one occurence of s), :// = literal protocol separator, [a-zA-Z0-9./?=_%:-]* = any web-safe characters (domains, paths, parameters). Like grabbing complete web links. https://example.com http://blog.company.net/articles https://secure.payment.org/checkout?id=123 6. Extracting date formatsFrom the various kinds of date formats listed here: Meeting on 12/25/2024 Invalid: 13/45/2024 Project due: 01/15/2025 Bad format: 1/1/24 Conference: 03/30/2024 ISO format: 2024-12-25 Another ISO: 2025-01-15 Wrong: 24-12-2024 Let's extract the ones in MM/DD/YYYY format: grep -oE "(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/[0-9]{4}" dates.txt Date validation uses logical ranges: (0[1-9]|1[0-2]) = months 01-09 OR 10-12, / = literal slash, (0[1-9]|[12][0-9]|3[01]) = days 01 to 09 OR 10 to 29 OR 30 to 31, / again, [0-9]{4} = exactly 4-digit year. Like checking calendar validity. 12/25/2024 01/15/2025 03/30/2024 7. Match and extract credit card numbersSample transaction.txt file with dummy credit card numbers: Payment: 4532-1234-5678-9012 Card: 4532 1234 5678 9012 Compact: 4532123456789012 Invalid: 1234-5678-9012 Another: 5555-4444-3333-2222 Short: 1234567890123 We will only extract the credit card numbers: grep -oE "[0-9]{4}[-\s]?[0-9]{4}[-\s]?[0-9]{4}[-\s]?[0-9]{4}" transactions.txt Credit cards (usually) follow 4-4-4-4 digit blocks: [0-9]{4} = exactly 4 digits, [-\s]? = optional dash or space, repeated 4 times. 4532-1234-5678-9012 4532 1234 5678 9012 4532123456789012 5555-4444-3333-2222 Now don't show me an American Express card ;) 8. HTML tag removalHere's a sample HTML code: <div class="content"> <h1>Welcome to Our Site</h1> <p>This is a <strong>sample</strong> paragraph.</p> <a href="https://example.com">Click here</a> </div> And we remove all the tags in brackets: sed 's/<[^>]*>//g' webpage.html HTML tag elimination uses bracket matching: < = literal opening bracket, [^>]* = any characters EXCEPT closing bracket (zero or more), > = literal closing bracket. Like scissors cutting out everything between angle brackets. Welcome to Our Site This is a sample paragraph. Click here Bonus tips: Mind these for writing better regexIt is always easy to write a regex that may seem to match your pattern but also end up matching a lot more. I cannot cover all such situations, but here are a few common mistakes you should avoid. 1. Forgetting to escape# Wrong: will match any character instead of literal dot grep "192.168.1.1" file.txt # Correct: escape the dots grep "192\.168\.1\.1" file.txt 2. Greedy vs non-greedy# Greedy problem with HTML echo "<b>bold</b> and <i>italic</i>" | grep -oE "<.*>" # Returns: <b>bold</b> and <i>italic</i> # Better approach echo "<b>bold</b> and <i>italic</i>" | grep -oE "<[^>]*>" 3. Case sensitivityThis is more of a grep feature. # May miss uppercase variants grep "email" contacts.txt # Better: case insensitive grep -i "email" contacts.txt 4. Anchor your patternsNo need to search entire files if your pattern is at the beginning. # Slow: searches entire line grep "pattern" hugefile.txt # Fast: anchored search grep "^pattern" hugefile.txt # If pattern is at start 5. Use character classes efficiently# Slower grep -E "[0123456789]" file.txt # Faster grep -E "[0-9]" file.txt # or grep -E "\d" file.txt 6. Testing your regex quicklyThe easiest way to test your regex is to feed it the extact match you are looking for. Once it matches that, you can try feeding it patterns that it should not match. Basically, just echo the pattern to grep. # Quick test with echo echo "test string" | grep -E "your_pattern" You can also use some online regex validator if you want. Final thoughtsTo be quite honest, it is never easy to learn or master regex, especially if you don't use it every day. Still, knowing (most of) the metacharacters helps a great deal. There is a famous joke in the community: "The number of times I used regex is equal to the number of times I had to learn regex" Also remember that a readable regex beats clever regex. Future you will thank present you for clear, documented patterns!
  7. by: Daniel Schwarz Wed, 23 Jul 2025 12:36:48 +0000 Chrome 139 is experimenting with Open UI’s proposed Interest Invoker API, which would be used to create tooltips, hover menus, hover cards, quick actions, and other types of UIs for showing more information with hover interactions. The Interest Invoker API makes these components declarative and hover-triggered, meaning that you create them with HTML, and then the web browser handles the mouseenter and mouseleave events for you, sans JavaScript. You’d use it like this: <a interestfor="target-id">Interest trigger</a> <div id="target-id" popover>Interest target</div> CodePen Embed Fallback It’s not stated anywhere that they must be declared as popovers, but they do bake the right accessibility hints in. I want to spend a little time looking at the pieces of this feature, how they‘re used as currently proposed, and offer a few thoughts based on my experience playing with them. Ready to dive in? The interest trigger The trigger is what the user will hover (or long-press on touchscreen devices) to reveal the interest target. I’d call it an “invoker,” but to avoid confusing it with the Invoker Commands API (which is kind of similar), I’ll stick with “trigger” or “interest trigger” for now. The interest trigger can be: a link (<a>), a button (<button>), or an image map area (<area>). And it should have the interestfor attribute whose value should reference the id of the interest target. Here are examples for each supported element: <!-- Link --> <a interestfor="link">Interest trigger</a> <div id="link" popover>Interest target</div> <!-- Button --> <button interestfor="button">Interest trigger</button> <div id="button" popover>Interest target</div> <!-- Image map --> <img src="" alt="" usemap="#map"> <map name="map"> <area interestfor="area" shape="" coords="" alt=""> </map> <div id="area" popover>Interest target</div> If the interest target is a popover (like it is in the examples above), then the interestfor attribute replaces the popovertarget attribute that’s normally required for declarative popovers. So, instead of this: <!-- Button --> <button popovertarget="button">Interest trigger</button> <div id="button" popover>Interest target</div> …we’re looking at this: <!-- Button --> <button interestfor="button">Interest trigger</button> <div id="button" popover>Interest target</div> The interest target The interest target is what’s revealed when the user hovers (or long-presses) the interest trigger. Again, this should be a popover, and it’s important to use the right type of popover because they have different functional and accessibility behaviors. popover attributes that are valueless, empty, or use the auto keyword can be dismissed lightly, i.e., using the esc key, or by clicking outside of the popover. When opened, these popovers close all hint and other auto popovers (at least, the ones that aren’t nested). <div id="target-id" popover>Interest target</div> <!-- Equivalent to --> <div id="target-id" popover="">Interest target</div> <!-- Equivalent to --> <div id="target-id" popover="auto">Interest target</div> hint popovers (the newest type of popovers) can also be dismissed lightly, but only close other hint popovers when opened: <div id="target-id" popover="hint">Interest target</div> manual popovers do their own thing. They can’t be dismissed lightly, don’t tell other popovers what to do, and we can have more than one of them open at a time. They’re suuuper chill. <div id="target-id" popover="manual">Interest target</div> However, Open UI’s explainer and Chrome’s current implementation suggest that interest targets disappear on mouseleave regardless of the type of popover we’re working with. But redefining popover behavior in this context (or any context) feels wrong to me. If the interest target’s popover attribute is set to manual, for example, shouldn’t it persist after mouseleave? Open UI discusses browsers baking the accessibility in depending on the popover type, which justifies interest invokers building off of popovers, but I think accessibility should depend on the content (unless overwritten using ARIA attributes) rather than the popover type. In short, it seems like interest invokers are designed to be used with popovers but for all the wrong reasons (in my opinion anyway). That said, it’s early days still. Interest invokers are very experimental and it’s certainly possible that I’m overlooking something. They’re otherwise straightforward, which is on-brand for Open UI (look at the Customizable Select, after all). They take commonly-used JavaScript-powered components (such as exclusive accordions, invoker commands, and yes, popovers) and make them possible with declarative HTML. That said, there are some JavaScript events that we can use, too. Let’s take a look at those. Interest invoker JavaScript events While I imagine that you’d only need to listen for the interest and loseinterestevents for certain edge cases, JavaScript events for these new declarative HTML features are fairly standard, and they’re there should you need them: interestTrigger.addEventListener("interest", () => { /* User showed interest */ }); interestTrigger.addEventListener("loseinterest", () => { /* User lost interest */ }); But what does “interest” mean, exactly? That’s worth digging into next. Interest delay (and the CSS of it all) You’ve probably noticed that when you show or lose interest, there’s a short delay in the popover showing or hiding itself. This is extremely annoying at first, but when you actually start to build with interest invokers, you realize how necessary it is. Here’s the demo again, so you can try it out (in Chrome 139 or Canary for now): CodePen Embed Fallback One problem is that if you accidentally mouseleave the interest trigger and the target (which can be very easy to do when the target is too small), then it all disappears. This is even more annoying, but luckily the hide delay allows you some recovery time. Similarly, the show delay offers keyboard and screen reader users the opportunity to skip the interest target, while also preventing it from being triggered accidentally with a mouse pointer. Having said that, if the interest target is unobtrusive, then removing the show delay shouldn’t cause any harm. You could also remove the hide delay for keyboard and screen reader users, who aren’t likely to “lose interest” accidentally. We can do this by setting two new CSS properties, interest-show-delay and interest-hide-delay, to 0. The default is 0.5s and is set on the interest trigger (but not the interest target): /* If unobtrusive */ .unobtrusive[interestfor] { interest-show-delay: 0; } /* If keyboard-focused on a trigger */ [interestfor]:focus-visible { interest-hide-delay: 0; } /* If keyboard-focused within a target of interest, or target of partial interest (these are always keyboard-triggered), the interest trigger that currently has interest or partial interest has the hide delay removed */ body:has(:target-of-interest :focus-visible, :target-of-partial-interest) [interestfor]:where(:has-interest, :has-partial-interest) { interest-hide-delay: 0; } Note: Interest delays are currently buggy, especially with unitless values. Sometimes they work, sometimes they don’t. About those pseudo-selectors, though… Basically, when navigating to an interest trigger using a keyboard or screen reader whose target contains more focusable elements, this is referred to as showing “partial” interest. (I would’ve gone with “potential interest” personally, but I digress.) When this happens, the interest target’s focusable elements actually aren’t focusable (making it easy to skip them, if needed) unless the user hits the option+up/alt+up keyboard shortcut or equivalent screen reader hotkey. There’s even a message that we can customize by targeting :target-of-partial-interest::after: :target-of-partial-interest::after { content: "Press ⌥↑ to activate."; } CodePen Embed Fallback While you probably shouldn’t change the message content (since it displays the correct keyboard shortcut for the user’s device by default), we can style it by selecting this way. The user agent also throws this in: :target-of-partial-interest { interactivity: not-keyboard-focusable; } The not-keyboard-focusable value is new, and prevents the keyboard focus (like tabindex="-1" but for CSS, which is super interesting in its own right). A full breakdown because, frankly, that was a lot: :has-interest: Triggers with “mouse interest” :has-partial-interest: Triggers with “keyboard interest” :target-of-interest: Targets with mouse interest :target-of-partial-interest: Targets with keyboard interest :target-of-partial-interest::after: The message displayed when targets have keyboard interest interest-show-delay: The <time> before which the interest target appears interest-hide-delay: The <time> before which the interest target disappears interest-delay: Shorthand for interest-show-delay and interest-hide-delay It works with anchors, too Nothing really new here as far as what we’ve already discussed, but I find it cool that we can use anchor elements declaratively just like interest invokers: CodePen Embed Fallback Conclusion On the surface, interest invokers are simply hover-triggered popovers, but touchscreen devices have never handled hovering well. In addition, hovering is susceptible to human-error, and we certainly don’t want to force keyboards and screen readers to tab into a minefield of focusables. There’s a lot to consider, and Open UI have done a wonderful job of ensuring that user agents do the lion’s share of it. But there’s still more to consider. For example, how exactly would we open interest targets on touchscreen devices? Long-press + “View more info” from the context menu seems to be the best approach at the moment, but that’s a tough one! And, as we’ve discussed, there’s a lot for us to consider, too, such as those delay timings and how interest invokers should be styled. What should interest triggers and targets look like when they have interest? What about the hotkey instruction? We’re talking about some new concepts here, that might require new UX conventions. Honorable mention: We’re also getting interactivity: not-keyboard-focusable out of this, which could help us to build keyboard-friendlier components with CSS. There’s a lot to love here, and I just know that people are going to create incredible tooltips and hover cards and more with this. A First Look at the Interest Invoker API (for Hover-Triggered Popovers) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
  8. by: Sreenath V Tue, 22 Jul 2025 18:07:20 +0530 This post is for paying subscribers only Subscribe now Already have an account? Sign in
  9. by: Team LHB Tue, 22 Jul 2025 17:59:09 +0530 This post is for paying subscribers only Subscribe now Already have an account? Sign in
  10. by: Team LHB Tue, 22 Jul 2025 17:55:04 +0530 This post is for paying subscribers only Subscribe now Already have an account? Sign in
  11. by: Team LHB Tue, 22 Jul 2025 17:50:55 +0530 This post is for paying subscribers only Subscribe now Already have an account? Sign in
  12. by: Team LHB Tue, 22 Jul 2025 16:43:38 +0530 This post is for paying subscribers only Subscribe now Already have an account? Sign in
  13. by: Abhishek Prakash Tue, 22 Jul 2025 07:05:00 GMT When it comes to grammar checking, Grammarly is the premium tool for it. It's a proprietary tool and it was among the first one to make a mark as a web-based Grammar checking tool. Then there is LanguageTool (partner link). This is the tool that we use here in our team. It is/was open source, made in Germany and offers hosted service for free or for a price (you get additional features). LanguageTool was acquired a couple of years back and since then it's privacy policy has changed as it processes data on US servers, instead of European ones. Recently, I came across a new grammar checker tool, Harper, and I am sharing my experience and my views on this new open source tool. Meet Harper, a local first open source grammar checkerHarper is a new project coming from Automattic developer, Elijah Potter. Automattic is the company behind WordPress, world's most popular Content Management System (CMS). The idea is to have a local first tool that doesn't depend on the cloud for any processing or stores away the data. That's a W right there. Harper is currently available as browser extension and plugin for Obsidian and VS Code. It is a new project and I hope they release more extensions, specially for LibreOffice, in the future. Try HarperI tried the Firefox add-on and tested it while writing this review itself. Features that I likeNow, Firefox already has a built-in spell checker and I believe Chrome and other browsers may also have it. So, do we need a third-party browser extension for this purpose? The short answer is yes. The built-in spell checker in Firefox is limited. It will underline even when you use a brand name. It is essentially a spell checker and hence it just checks for spelling mistakes. It won't warn you if you use "the the" two times in row. It won't warn you even if you write 'an pineapple'. Harper is definitely msarter than the default spellchecker of your web browserHarper does these things and it does that without interacting with a central server. Everything is processed locally. Here's what Harper is capable of: Spell checking (obvious)Spotting repetition (example, double the the)Spotting multiple simultaneous spaces in a sentenceSave words to dictionary (excellent)Correcting the use of a/anCommon misused words like "despite of" which should be "in spite of" or "despite" or "its/it's"Styling issue with comma usageAnother interesting feature is that Harper uses different colors for different type of mistakes. This way it is easier to visualize the mistakes and their types. The option to add strangely spelled words into the local dictionary is an excellent feature. Save special words in your local dictionaryYou can access this local dictionary by accessing the extension settings. And this is where you'll see various settings that you can change. You can even bring your custom dictionary as long as the words are in their own line. You can also choose between American, British, Canadian, and Australian English dialect. Harper extension settings📋As you can see, it seems Harper only supports English language at the time of writing this article.There are also a huge list of rules that detects errors like "along time" and suggest "a long time" as the alternative. The list is huge and that's why there is the option to search for a rule. There is no option to add your own rules though. Fast but how fast, rally?Harper claims to be faster than both Grammarly and LanguageTool. I don't have data to prove it. But I cal show you this video in which I show how quickly Harper gets into action as I type. 0:00 /0:28 1× Since the processing is local, the suggestions are pretty fast actually. Harper is not perfect, of courseFor example, here I deliberately mistyped "video in" as "videoin" and Harper didn't suggest it as one of the possible correct options. And I think it limits itself to suggest maximum three suggestions or the most it can fit in a line. Harper offers limited suggestionsAnother thing is that Harper is not as intelligent as I would want it to be. I am an excellent tester for grammar tools. I make so many mistakes and on so many levels that even the best grammar checkers throw in the towel. That's why I tested Harper against LanguageTool with a sentence with multiple grammatical issues. Harper was primarily so focused on the spelling of Wikimedia and Cloudflare that it forgot to point out other grammatical mistakes. The weird thing is that both Cloudflare and Wikimedia were correctly spelled. Usually, Harper is good at recognizing brand names, except in this case where it made two false positives in a single sentence. On the other hand, LanguageTool did indicate that there are some grammatical mistakes worth looking for. Neither could correct the sentence entirely, as the correct sentence I was aiming for was: Grammarly, LanguageTool, and Cloudflare went to a bar run by Wikimedia but it was closed, so they went to Wikipedia. Yeah! I know. No AI can guess what goes in my mind when I make these typos. It takes real intelligence to deal with such stupidity 😜 At least in Ghost, the CMS I use to publish content on It's FOSS, sometime the suggestions tooltip wouldn't close until I start typing something. It's minor but annoying. ConclusionBoth Grammarly and LanguageTool have evolved to writing assistant with AI features. But here's the thing. Sometime simplicity is the best feature you look for. Not everyone is a professional writer looking for additional features to improve their work. For a casual user, a no-fluff, simple grammar checker is more than sufficient to save them from embarrassing typos and grammatical mistakes in their emails. And Harper is an excellent choice at that. It is definitely better than your browser's built-in spell checker, it is an open source software and it processes your data locally. If you are not dependent on a more professional tool like LanguageTool or Grammarly, you should definitely 'upgrade' to Harper.
  14. by: Chris Coyier Mon, 21 Jul 2025 17:54:20 +0000 Our very own Stephen Shaw was on an episode of Web Dev Challenge on CodeTV: Build the Future of AI-Native UX in 4 Hours. I started watching this on my computer, but then moved to my living room couch to put it on the big screen. Because it deserves it! It honestly feels like “real” TV, as good as any episode of a home renovation show or the like. Only obviously better as it’s straight down the niche of web maker nerds like us. All three teams in the episode were building something that incorporated AI usage directly for the user. In all three cases, using the app started with a user typing in what they wanted into a textbox. That’s what the input for LLMs thrives on. I’m sure in all three cases it was also augmented with additional prompting and whatnot, invisible to the user, but ultimately, you ask something in your own words. LLMs were interacted with via API and the teams then dealt with the responses they got back. We didn’t get to see how they dealt with the responses much, but you get the sense that 1) they can be a bit slow so you have to account for that 2) they are non-deterministic so you need to be prepared for highly unknown responses. The episode was sponsored by Algolia, which provides search functionality at it’s core. Algolia’s APIs are, in stark contrast to the LLM APIs, 1) very fast 2) largely deterministic, meaning you essentially know and can control what you get back. I found this style of application development interesting: using two very different types of APIs, leaning into what each are good at doing. That’s not a new concept, I suppose, but it feels like a fresh new era of specifically this. It’s not AI everywhere all the time for everything! It’s more like use AI sparingly because it’s expensive and slow but extremely good at certain things. I admit I’m using AI more and more these days, but 95% just for coding help. I wouldn’t call it “vibe coding” because I’m very critical of what I get back and tend to work on a codebase where I already essentially know what I’m doing; I just want advice on doing things faster and help with all the rote work. What started as AI helping with line completion has expanded into much more general prompting and “agents” roaming a whole codebase, performing various tasks. I’m not sure when it flipped for me, but this whole agent approach to getting AI help is actually the most comfortable way working with AI and code for me now. I haven’t tried Claude Code yet, mostly because it’s command-line only (right??) and I just don’t live on the command line like that. So I’ve been mostly using Cursor. I tried Windsurf a while back and was impressed by that, but they are going through quite a bit of turmoil lately so I think I’ll stay away from that unless I hear it’s great again or whatever. The agentic tools that you use outside of your code editor itself kind of weird me out. I used Jules the other day for a decently rote task and it did a fine job for me, but was weird to be looking at diffs in a place I couldn’t manually edit them. It almost forces you to vibe code, asking for changes in text rather than making them yourself. There must be some market for this, as Cursor has them now, too. It really is the “simple but ughgkghkgh” tasks for me that AI excels at. Just the other day I was working on an update to this very CodePen blog/podcast/docs site which we have on WordPress. I had switched hosting companies lately, and with that came a loss in how I was doing cache-busting CSS. Basically I needed to edit the header.php file with a cache-busting ?v=xxx string where I <link>ed up the CSS, otherwise shipping updated CSS wouldn’t apply when I changed it. Blech. CodePen deployed sites will not have this problem. So, anyway, I needed a simple build process to do this. I was thinking Gulp, but I asked an AI agent to suggest something. It gave me a variety of decent options, including Gulp. So I picked Gulp and it happily added a build process to handle this. It required maybe 3-4 rounds of discussion to get it perfectly dialed in, but all in all, maybe a 10-minute job. I’d say that was easily a 2-3 hour job if I had to hand-code it all out, and much more if I hadn’t already done exactly this sort of thing many times in my career. I’m definitely starting to think that the more you know what you’re doing, the more value you get out of AI. While we’re at it, I’ll leave you with some AI-ish bookmarks I’ve had sitting around: humanify: “Deobfuscate Javascript code using ChatGPT” Derick Ruiz: LLMs.txt Explained (Basically dump your docs into one big .txt file for LLMs to slurp up on purpose. Weird/funny to me, but I get it. Seems like npm modules should start doing this.) Ryan Law also has What Is llms.txt, and Should You Care About It? Steve Klabnik: I am disappointed in the AI discourse. (If you’re going to argue about something, at least be informed.) Video: Transformers.js: State-of-the-art Machine Learning for the web. AI APIs baked into browsers will be a big deal. More privacy, no network round-trip, offline support, etc.
  15. by: Sreenath V Mon, 21 Jul 2025 19:58:16 +0530 This post is for paying subscribers only Subscribe now Already have an account? Sign in
  16. by: Team LHB Mon, 21 Jul 2025 19:50:16 +0530 This post is for paying subscribers only Subscribe now Already have an account? Sign in
  17. by: Zell Liew Mon, 21 Jul 2025 13:14:17 +0000 Focus trapping is a term that refers to managing focus within an element, such that focus always stays within it: If a user tries to tab out from the last element, we return focus to the first one. If the user tries to Shift + Tab out of the first element, we return focus back to the last one. This whole focus trap thing is used to create accessible modal dialogs since it’s a whole ‘nother trouble to inert everything else — but you don’t need it anymore if you’re building modals with the dialog API (assuming you do it right). Anyway, back to focus trapping. The whole process sounds simple in theory, but it can quite difficult to build in practice, mostly because of the numerous parts to you got to manage. Simple and easy focus trapping with Splendid Labz If you are not averse to using code built by others, you might want to consider this snippet with the code I’ve created in Splendid Labz. The basic idea is: We detect all focusable elements within an element. We manage focus with a keydown event listener. import { getFocusableElements, trapFocus } from '@splendidlabz/utils/dom' const dialog = document.querySelector('dialog') // Get all focusable content const focusables = getFocusableElements(node) // Traps focus within the dialog dialog.addEventListener('keydown', event => { trapFocus({ event, focusables }) }) The above code snippet makes focus trapping extremely easy. But, since you’re reading this, I’m sure you wanna know the details that go within each of these functions. Perhaps you wanna build your own, or learn what’s going on. Either way, both are cool — so let’s dive into it. Selecting all focusable elements I did research when I wrote about this some time ago. It seems like you could only focus an a handful of elements: a button input textarea select details iframe embed object summary dialog audio[controls] video[controls] [contenteditable] [tabindex] So, the first step in getFocusableElements is to search for all focusable elements within a container: export function getFocusableElements(container = document.body ) { return { get all () { const elements = Array.from( container.querySelectorAll( `a, button, input, textarea, select, details, iframe, embed, object, summary, dialog, audio[controls], video[controls], [contenteditable], [tabindex] `, ), ) } } } Next, we want to filter away elements that are disabled, hidden or set with display: none, since they cannot be focused on. We can do this with a simple filter function. export function getFocusableElements(container = document.body ) { return { get all () { // ... return elements.filter(el => { if (el.hasAttribute('disabled')) return false if (el.hasAttribute('hidden')) return false if (window.getComputedStyle(el).display === 'none') return false return true }) } } } Next, since we want to trap keyboard focus, it’s only natural to retrieve a list of keyboard-only focusable elements. We can do that easily too. We only need to remove all tabindex values that are less than 0. export function getFocusableElements(container = document.body ) { return { get all () { /* ... */ }, get keyboardOnly() { return this.all.filter(el => el.tabIndex > -1) } } } Now, remember that there are two things we need to do for focus trapping: If a user tries to tab out from the last element, we return focus to the first one. If the user tries to Shift + Tab out of the first element, we return focus back to the last one. This means we need to be able to find the first focusable item and the last focusable item. Luckily, we can add first and last getters to retrieve these elements easily inside getFocusableElements. In this case, since we’re dealing with keyboard elements, we can grab the first and last items from keyboardOnly: export function getFocusableElements(container = document.body ) { return { // ... get first() { return this.keyboardOnly[0] }, get last() { return this.keyboardOnly[0] }, } } We have everything we need — next is to implement the focus trapping functionality. How to trap focus First, we need to detect a keyboard event. We can do this easily with addEventListener: const container = document.querySelector('.some-element') container.addEventListener('keydown', event => {/* ... */}) We need to check if the user is: Pressing tab (without Shift) Pressing tab (with Shift) Splendid Labz has convenient functions to detect these as well: import { isTab, isShiftTab } from '@splendidlabz/utils/dom' // ... container.addEventListener('keydown', event => { if (isTab(event)) // Handle Tab if (isShiftTab(event)) // Handle Shift Tab /* ... */ }) Of course, in the spirit of learning, let’s figure out how to write the code from scratch: You can use event.key to detect whether the Tab key is being pressed. You can use event.shiftKey to detect if the Shift key is being pressed Combine these two, you will be able to write your own isTab and isShiftTab functions: export function isTab(event) { return !event.shiftKey && event.key === 'Tab' } export function isShiftTab(event) { return event.shiftKey && event.key === 'Tab' } Since we’re only handling the Tab key, we can use an early return statement to skip the handling of other keys. container.addEventListener('keydown', event => { if (event.key !== 'Tab') return if (isTab(event)) // Handle Tab if (isShiftTab(event)) // Handle Shift Tab /* ... */ }) We have almost everything we need now. The only thing is to know where the current focused element is at — so we can decide whether to trap focus or allow the default focus action to proceed. We can do this with document.activeElement. Going back to the steps: Shift focus if user Tab on the last item Shift focus if the user Shift + Tab on the first item Naturally, you can tell that we need to check whether document.activeElement is the first or last focusable item. container.addEventListener('keydown', event => { // ... const focusables = getFocusableElements(container) const first = focusables.first const last = focusables.last if (document.activeElement === last && isTab(event)) { // Shift focus to the first item } if (document.activeElement === first && isShiftTab(event)) { // Shift focus to the last item } }) The final step is to use focus to bring focus to the item. container.addEventListener('keydown', event => { // ... if (document.activeElement === last && isTab(event)) { first.focus() } if (document.activeElement === first && isShiftTab(event)) { last.focus() } }) That’s it! Pretty simple if you go through the sequence step-by-step, isn’t it? Final callout to Splendid Labz As I resolve myself to stop teaching (so much) and begin building applications, I find myself needing many common components, utilities, even styles. Since I have the capability to build things for myself, (plus the fact that I’m super particular when it comes to good DX), I’ve decided to gather these things I find or build into a couple of easy-to-use libraries. Just sharing these with you in hopes that they will help speed up your development workflow. Thanks for reading my shameless plug. All the best for whatever you decide to code! A Primer on Focus Trapping originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
  18. by: Umair Khurshid Mon, 21 Jul 2025 17:00:49 +0530 Modern infrastructure operations depend on automation not only for efficiency, but also for repeatability. Among the many tasks automated in daily workflows, package management is one of the most frequent. For systems based on RPM package formats such as Red Hat Enterprise Linux (RHEL), CentOS, AlmaLinux, Rocky Linux, and older versions of Fedora, Ansible provides a native module that integrates directly with the yum package manager. While newer systems may rely on dnf under the hood, the yum module in Ansible remains fully functional due to backward compatibility. In practice, it continues to be the primary interface for managing packages on RPM-based systems through Ansible playbooks. Let's see some of the usual package management you can do with Yum module in Ainsible. RHCE Ansible EX294 Exam Preparation CourseLearn all the essentials of Ansible with this hands-on tutorial series. It is ideal for RHCE Ansible EX294 exam preparation.Linux HandbookAhmed AlkabaryInstalling and removing packages declarativelyThe most common use of the yum module is to ensure that specific packages are present or absent on a system. Unlike imperative shell tasks that install software unconditionally, Ansible modules operate declaratively. This means administrators specify the desired end state, and Ansible ensures that the system reflects that state. - name: Ensure Apache is installed ansible.builtin.yum: name: httpd state: present This task confirms that the httpd package is installed. If it is already present, no changes are made. If it is missing, it will be installed. Removing package, in our case the Apache package, is also straightforward: - name: Remove Apache if no longer required ansible.builtin.yum: name: httpd state: absent This is how you can install and remove a package cleanly and idempotentlyon the command line just by changing the value of the state parameter. Working with multiple packagesAdministrators frequently need to install or remove multiple packages in one task. The yum module accepts a list as the name argument: - name: Install common utilities ansible.builtin.yum: name: - git - wget - curl state: present This example ensures that Git, wget, and curl are all installed on the target system. The task will only trigger a change if one or more of the listed packages are not already present. Keeping packages up to dateAnother common requirement is to upgrade packages to their latest available version in the configured repository. Here's how you can do it using the yum module: - name: Upgrade nginx to the latest version ansible.builtin.yum: name: nginx state: latest This guarantees that the latest available version of nginx is installed. It is particularly useful in playbooks designed to bring systems to a known and up-to-date state before deployment. Installing RPM files directlyIn addition to repository-based installations, the yum module can also handle local RPM packages. This is useful when installing custom software or vendor packages not found in public repositories. - name: Install a local RPM ansible.builtin.yum: name: /tmp/package-name.rpm state: present If the RPM has unmet dependencies, yum will attempt to resolve them using the system’s configured repositories. It is also possible to disable GPG signature checking when required, such as in development environments or controlled test scenarios: - name: Install without GPG checks ansible.builtin.yum: name: /tmp/unsigned-package.rpm disable_gpg_check: true state: present This should be used cautiously and avoided in production systems. Repository-aware behaviorAnsible separates package management from repository configuration. If custom or third-party repositories are required, the yum_repository module should be used to define them explicitly: - name: Add a third-party repository ansible.builtin.yum_repository: name: example description: Example Repository baseurl: https://repo.example.com/centos/$releasever/os/$basearch/ gpgcheck: true gpgkey: https://repo.example.com/RPM-GPG-KEY-example enabled: true This step is often necessary when deploying systems in air-gapped environments or when using hardened baselines with restricted repository access. Coordinating with services and handlersPackage installation is often tied to service management. A typical pattern is to notify a handler that starts or restarts a service after the package has been installed or upgraded: - name: Install Apache ansible.builtin.yum: name: httpd state: present notify: Restart Apache handlers: - name: Restart Apache ansible.builtin.service: name: httpd state: restarted This mechanism ensures that service restarts only occur when required, reducing unnecessary churn during routine deployments. Platform awareness and compatibilityAlthough many RPM-based systems now rely on dnf internally, the yum module continues to operate correctly. From my experience, you are bound to encounter a legacy CentOS system, often still running CentOS 7 or earlier where yum is the default and only available package manager. For Fedora and RHEL 8+ systems, the dnf binary is usually a drop-in replacement that maintains CLI compatibility, and Ansible handles this transparently. However, if you are seeking full consistency, the dnf module is available as an alternative, with nearly identical syntax and behavior. For most use cases, the choice between yum and dnf is a matter of policy rather than absolute technical necessity. New to Ansible? Learn from our "Learn Ansible Quickly" course. This is a fully practical, hands-on course for learning Ansible Automation. It will get you up and running with Ansible in no time. Ideal for RHCE Ex294 Exam. Ansible Course Wrapping UpWhether used in simple playbooks or integrated into large-scale CI/CD pipelines, the yum module remains an essential component of system provisioning workflows. Its compatibility with RHEL and its derivatives makes it a practical choice for both legacy environments and modern deployments. If you are already familiar with yum commands, adopting the Ansible module is a natural progression. It introduces structure without removing control, and supports fine-grained state management without requiring custom shell logic.
  19. by: Sreenath Mon, 21 Jul 2025 06:38:35 GMT "If there is a media out there, VLC can play it!". I want to say the same thing about Kitty and its versatility. If you didn't know already, Kitty is one of the most comprehensive terminal emulators available in Linux. It offers image support, ligatures, animated cursors, and a whole lot of productivity tweaks. I could write a mini-book if I had to explain each one in full detail. I am not going to do that. Instead, I'll share some of my favorite features and tweaks I use with Kitty. Installing KittySince Kitty is a pretty popular terminal emulator, it is available in the default repository of most of the Linux distributions. In Ubuntu, you can install a slightly older version of Kitty by using the APT command: sudo apt install kittyArch Linux users can install it from the Extra repo: sudo pacman -S kittyFor Fedora, sudo dnf install kittyIf you are any other distro user, or your system repo provides an older version of Kitty, use the official pre-built binary from the Kitty team. curl -L https://sw.kovidgoyal.net/kitty/installer.sh | sh /dev/stdinOr, download binary from the GitHub releases page. Download Kitty1. Generating default configKitty offers a huge configuration possibility, but through its config file. This config file should be kitty.conf located in ~/.config/kitty directory. It is always good to use the default config file and make changes to it rather than creating a config from scratch. Open Kitty and use the keyboard shortcut CTRL+SHIFT+F2. This will open the Kitty config in a new window. If not present already, it will create one for you and open it. For me, it opened in the Vi editor. If this is not needed, you can quit the config using the Vi shortcut :q (without any changes). 0:00 /0:11 1× Open Kitty config file using the shortcut in Kitty. This will open the config file in Vi editor. Then open it in your favorite command line editor or GUI-based text editors. nano ~/.config/kitty/kitty.conf2. Setting a different fontA proper monospace font can increase the terminal aesthetics. Here, we will set the terminal font as JetBrains Mono font. Before proceeding, make sure the font is installed on your system. First, list the set of supported fonts using the command: kitty +list-fontsFrom the list, note the exact name of the font you want to use: List FontsNow, open Kitty config and scroll down to the line that says font-family. Here, remove the comment in front of the item and change the name as follows: font-family "JetBrains Mono"Set a Font💡Kitty supports setting individual font as well, like Bold, Italics, etc.Setting font alone is not sufficient; you should be able to change the font size as well. Fret not! Kitty has an option here. Search for font-size. Uncomment the line and change the value to sufficiently large. Font Size3. Re-setting scrollbackOne of the most essential features in a terminal is a sufficiently long scrollback lines. Many commands like cat, do not use a pager like less to print text. So, if a text has a huge number of lines, more than your scrollback, then the beginning parts of the text will be unreachable. At the same time, setting a huge scrollback line is also not advised. Since the scrollback lines are stored in RAM, more scrollback lines means more hit on the RAM usage. A value of 10000 will be good for most users, and a 2000 is also fine for a GUI-only user. On the Kitty config file, find the line scrollback_lines. By default, the value is 2000. To change, uncomment the line and add a value, say 5000. scrollback_lines 5000Scrollback LinesThe scrollback pager feature in Kitty allows you to open your terminal’s scrollback history in a full-featured pager program (like less or nvim) for easier navigation, search, and copying. By default, this is disabled. You need to enable it by specifying the value in MB. Scrollback Pager History💡Use most instead of less and add colors to your pager system.4. Hiding mouse on typing (for keyboard addicts)For terminal power users, the mouse may feel like a distraction. In Kitty, you can play with the mouse presence in several ways. Hiding the mouse immediately when you start typing is my preference. To get this action, set the mouse_hide_wait variable to a negative value. mouse_hide_wait -3.0If you make this value any positive number, the terminal will wait for that many seconds and then disable the mouse if no mouse action occurred within that time range. Hide Mouse CursorIn the screenshot above, I set the value to 5.0 seconds. So now, no matter you type or not, the mouse will be disabled if you don't touch your mouse for more than 5 seconds. Set it to 0 and the mouse won't hide at all. 5. Setting window sizeKitty remembers the window size from the last session by default, so you don't need to resize it every time. Still, you can set the default window width in Kitty. Window SizeThe remember_window_size yes is self-explanatory. The window size will be remembered with Kitty instances. You can set the initial_window_width/height key to a required size and then disable the remember_window_size so that the new instances always open in the specified size. This is specifically useful in the next section, where we disable the window decoration and thus you can't resize the terminal with mouse anymore. 6. Hiding window decorationsIf you are using tiling window managers like Hyprland, it is good to avoid the title in Kitty. You won't find any serious use for it, because window resizing is done differently in tiling window managers. Search and locate the hide_window_decorations option. Uncomment the line and change its value to yes from the default no. Hide Window Decorations7. Customizing the tabsLike most of the terminal, Kitty offers tabs as well. The difference is that Kitty offers some ways to make the tabs look unique. Tab bar positionYou can use the tab_bar_edge key to specify whether you want the tab list at top or bottom. The default is bottom, and that is fine. Tab bar styleThere are several cool styles available for the tab bar, like fade, slant, separator, powerline, and custom. We will be going with the powerline, which is pleasing and can be quickly made work. Uncomment the line and change the value. tab_bar_style powerlineNow, the powerline offers another key called the tab_powerline_style. This can be set to angled, slanted, round. All these looks cool, but I will be going with round which along with the Catppuccin Starship prompt will look aligned. tab_powerline_style round 0:00 /0:32 1× Tabs in Kitty 8. Changing the shellMost of the Linux distributions come with Bash as the default shell. Many users, on the other hand, love the ZSH shell. The most common way people follow is to change the system shell. But that applies to all the terminals. Here comes the use of shell key. You can set a shell for only the Kitty terminal and the rest of the system will use the default bash shell. For this, first find the command location of your desired shell using the which command: which zshFor me, it is /usr/bin/zsh. Now, search for the shell key in Kitty config. 💡If you are searching for the shell using the editor's find tool, search for shell ., so that you reach the result directly.The default value is . which means the user's default shell is used as Kitty shell. Remove this . and paste the location of your desired shell. shell /usr/bin/zshChange Shell💡You can set a default editor as well using the editor key in Kitty configuration file. The procedure is the same as changing shell.9. Notifying on command finishWith Kitty, you can get a desktop notification when a long-running command finishes up. For this, uncomment the notify_on_cmd_finish key and set its value to invisible or unfocussed. I am going with invisible, since, as per manual, it will: Only send a notification when the window both is unfocused and not visible to the user, for example, because it is in an inactive tab or its OS window is not currently active.notify_on_cmd_finish invisibleIf you are more into detail, set a time limit for the long command. I am going to set 20 seconds as the duration of a long command. notify_on_cmd_finish invisible 20Notify on Command FinishThere is more to explore in this section for you! 10. Changing themesKitty offers a huge number of themes. Run this command: kitten themesThis will download the themes from the repo and display it to you. Scroll down to see them all. Once you find the perfect one for you, press the ENTER key to apply the theme! Also, use the / button to start a search. In the small video below, you can see that I apply Catppuccin theme to Kitty. Applying theme to Kitty Terminal Once you have selected the theme, press enter and it asks whether you want to modify the config or add the theme to ~/.config/kitty/themes. I will press the M key so that the Kitty Config is modified and the theme is set. 11. Animating cursor tailLatest versions of Kitty support setting a cool cursor animation. 📋The values for the keys in this section need to be fine tuned as needed for your satisfaction.To enable it, first search for the key cursor_trail. Uncomment it. I have set a value of 200 for it. Now, set a value for cursor_trail_decay and cursor_trail_start_threshold as shown in the screenshot below. Cursor Trail ValuesNow, reopen Kitty. You can see a cool cursor trail animation when the cursor is moved significantly. 0:00 /0:19 1× Showing Cursor Trail Animation 12. Automatic dark and light theme changeKitty supports automatically changing themes according to the system dark and light mode. 🚧This is supported in Kitty version 0.38+. So, if you are using Ubuntu 24.04 or related system, the default package repo version of Kitty doesn't support this.For this, first open Kitty and run: kitten themesNow, from the list of dark theme, select a dark theme and press enter. Select a dark themeIn the next page, press the D key so that this theme is the default theme for the dark mode. Now, run the kitten themes command again. This time, select a light theme from the list and press enter. In the next screen, press the L key, to make the selected light theme default for light mode. Set light mode themeRun kitten themes one more time and select a theme at random, and in the settings screen, press the N key to make it the default in case of no preference. No preference mode themeThat's it. Now, the Kitty will show the theme based on the current system mode. You can take a look at the ~/.config/kitty folder to make sure that the dark, light, and no-pref mode themes are present as config file. Theme files saved for different modes. 13. Setting a background imageTake the customization to the next level by adding an image as the background for Kitty terminal. Locate the key background_image in the kitty config file. Background Image and LayoutSet its value as path to the image file. Also, change background_image_layout to a required value, as shown in the screenshot above. And you can see that my kitty terminal now has an entirely different look that matches the theme of It's FOSS. Good for the social media videos. Set background image14. Adding a watermark/logoWant to spice up the terminal even more? Let's add a small logo as well! Make sure you have a small image, say 50x50 sized images. This will make things easy. There is a scale option window_logo_scale, but that may require some trial and error. Now, in the Kitty config, locate the key window_logo_path. Uncomment it and change its value to the path of the logo file. Also, fix the position of the logo using the window_logo_position key. Use the window_logo_alpha key to set a fade to the logo. Set Window LogoThat's it! Save the config file and reopen Kitty to view the result. It's FOSS Logo Applied15. Setting mouse actionsYou can define what the mouse buttons do in Kitty using the mouse_map option in the Mouse Actions section. The general syntax is: mouse_map button-name event-type modes actionFor example, the default middle-click to paste from selection action is set in Kitty using: mouse_map middle release ungrabbed paste_from_selectionKitty offers a wide range of customization, and I have mentioned some of the cool ones that I use regularly. There are more power user friendly features, like: Keyboard shortcuts mapping.Using Kittens to extend the functionality, etc.Explore the vast possibilities of Kitty by using it. ConclusionYou saw a glimpse of customized Kitty terminal in our terminal makeover video first. Subscribe to It's FOSS YouTube ChannelWe discussed internally and decided to do a dedicated tutorial on customizing Kitty. And hence this article. I understand that customizing the terminal is not everyone's preference but I like changing things to make them look asthetically pleasing. Kitty is my current favorite, even though I am thinking of using Ghostty. Please let me know in the comments if you like this article or if you notice any issues with the config changes.
  20. By: Janus Atienza Sat, 19 Jul 2025 16:11:31 +0000 Photo by Pixabay from Pexels The Internet of Things or IoT is changing a lot of industries. It connects devices and provides levels of automation that you can’t even begin to imagine. However, as connected devices are increasing, which is projected to reach more than 40 billion by 2030, security remains a major concern. A single vulnerability in an IoT ecosystem can expose sensitive data, disrupt operations, and compromise entire networks. As a result, Linux has become very important in secure IoT deployments, offering flexibility and security features. The Demands of IoT Security IoT devices work in diverse environments with limited computational resources. Unlike traditional computing systems, IoT devices face unique challenges like being lightweight, energy-efficient, and capable of running continuously with minimal maintenance. They are also targets for cyberattacks. In critical apps like medical devices or autonomous vehicles, a breach in an IoT device can lead to data theft, unauthorized access, or even physical harm. To address these challenges, IoT deployments require an OS that is: Secure by design Customizable to specific use cases Capable of receiving regular updates to patch vulnerabilities Linux excels in meeting these demands, becoming the main choice for those building secure IoT ecosystems. Linux: A Foundation for Security Linux’s open-source nature is its greatest strength for IoT security. Unlike other OSs, Linux’s source code is publicly available. As a result, the global community of developers can scrutinize, test, and improve it Due to this transparency, vulnerabilities can be identified and patched quickly. For IoT devices, where a single flaw can cause some major issues, this type of fast response can be very helpful. Linux’s modular architecture also lets devs create minimal, purpose-built systems. By stripping away unnecessary components, devs can reduce the attack surface. Over-the-Air Updates for Long-Term Security IoT devices often work in the field for years. So regular software updates are very important to address newly discovered vulnerabilities. However, updating millions of devices which are there all across the globe is a logistical challenge. This is where IoT device management plays a pivotal role. It lets organizations maintain a secure fleet of devices through efficient over-the-air updates. Linux’s flexibility makes it an ideal platform for implementing OTA update systems, allowing developers to push patches, firmware upgrades, and configuration changes seamlessly. Robust Access Controls and Isolation When we talk about securing IoT devices, it comes down to controlling who or what can access things, and keeping different parts of the system separate. That’s where Linux really does it work. It has some powerful tools, like SELinux and AppArmor, that act like very strict bouncers. These tools allow devs to set up rules about what every process and user on the device is allowed to do. Somehow, if a hacker manages to break into any part of an IoT device, these rules will prevent them from making more damages. Also, Linux supports containerization technologies like Docker or LXC. Cost-Effective and Long-Term Viability For those who are deploying IoT solutions, cost is a very critical consideration. Linux’s open-source nature eliminates licensing fees. As a result, it is a cost-effective choice compared to proprietary operating systems. The affordability also extends to dev tools, as Linux offers several free and open-source software for building, testing, and deploying IoT applications. Also, Linux provides long-term support releases, such as those provided by Ubuntu and Debian. It ensures that IoT devices can receive security updates and maintenance for years. Now, this is very important for industries like healthcare and industrial automation. Challenges in Linux-Based IoT Security While Linux offers many advantages, it is not without challenges. The complexity of configuring secure Linux distributions requires expertise. Plus, misconfigurations can introduce vulnerabilities. The diversity of IoT devices also tell you that not all Linux distributions are equally suited for every use case. By mixing Linux’s strengths with security measures, you can mitigate risks and make sure of the integrity of IoT deployments. So, you should adopt best practices, like: Keep your devices updated and patched regularly to tackle any known security flaws. Put strong network security in place, like firewalls and systems that detect intrusions. Use Linux’s built-in security features, such as SELinux and AppArmor, to enforce tight access controls. Make sure to thoroughly test and audit your IoT devices to pinpoint any potential weaknesses. Endnote You can see that Linux really stands out when it comes to securing IoT deployment. It’s very flexible and packed with strong security features. Itc can also handle growth easily, and has an amazing community backing it up. As it can adapt to so many different types of hardware and works well with new security systems, it’s perfect for powering the next generation of IoT devices. IoT is changing everyday and Linux’s open-source nature and collaborative environment will continue to be a key player in building IoT solutions that are secure, dependable, and innovative. For anyone who is planning to build strong, future-ready IoT systems, choosing Linux is very important. The post Why Linux Is the Backbone of Secure IoT Deployments appeared first on Unixmen.
  21. by: Andy Clarke Fri, 18 Jul 2025 16:12:05 +0000 A while back, our man Geoff Graham treated us to a refresher on the CSS initial-letter property, but how can you style drop and initial caps to reflect a brand’s visual identity and help to tell its stories? Here’s how I do it in CSS by combining ::first-letter and initial-letter with other unexpected properties, including border-image, and clip-path. Patty Meltt is an up-and-coming country music sensation. My brief: Patty Meltt is an up-and-coming country music sensation, and she needed a website to launch her new album. She wanted it to be distinctive-looking and memorable, so she called Stuff & Nonsense. Patty’s not real, but the challenges of designing and developing sites like hers are. First, a drop cap recap. Chris Coyier wrote about drop caps several years ago. They are a decorative letter at the beginning of a paragraph, often spanning several lines of text. It’s a typographic flourish found in illuminated manuscripts and traditional book design, where it adds visual interest and helps guide a reader’s eye to where they should begin. Study manuscripts from the Middle Ages onwards, and you’ll find hand-decorated illuminated capitals. The artists who made these initial letters were fabulously called “illuminators.” These medieval versals went beyond showing someone where to start reading; historiated letters also illustrated the stories, which was especially useful since most people in the Middle Ages couldn’t read. A basic drop cap On the web, drop caps can improve readability and reflect a brand’s visual identity. A brief refresher on properties and values In CSS, drop caps are created using the ::first-letter pseudo-element in combination with initial-letter. As you might expect, ::first-letter targets the very first letter of a block of text, enabling you to style it independently from the rest of a paragraph. The first number sets how many lines tall the letter appears, and the second controls its baseline alignment — that is, which line of text the bottom of the cap sits on. p::first-letter { -webkit-initial-letter: 3 3; initial-letter: 3 3; } Because browser support still varies, it’s common to include both the unprefixed and -webkit- prefixed properties for maximum compatibility. And speaking of browser support, it’s also sensible to wrap the initial-letter property inside an @supports CSS at-rule so we can check for browser support and provide a fallback, if needed: @supports (initial-letter:2) or (-webkit-initial-letter:2) { p::first-letter { -webkit-initial-letter: 3 3; initial-letter: 3 3; } } The initial-letter property automatically calculates the font size to match the number of lines a drop cap spans. On its own, this can make for quite a first impression. However, drop caps really start to come to life when you combine initial-letter with other CSS properties. Tip: Interactive examples from this article are available in my lab. Shadows Text shadows applied to first letters (live demo) When I want to lift a drop cap off the page, I can add a single text-shadow. Shadows can be colourful and don’t have to be black. I created a full live demo you can check out. p::first-letter { /* ... *// text-shadow: 6px 6px 0 #e6d5b3; } But why use just one shadow when two hard-edged shadows will turn a cap into a classic graphic typographic element? p::first-letter { /* ... */ text-shadow: -6px -6px 0 #7d6975, 6px 6px 0 #e6d5b3; } Examples showing unstyled, single text shadow, and two text shadows (live demo) Strokes A text shadow applied to a first letter (live demo) The text-stroke property — shorthand for text-stroke-width and text-stroke-color — adds an outline to the centre of the text shape. It’s a Baseline feature and is now widely available. I can make the cap text transparent or colour it to match the page background. p::first-letter { /* ... */ text-stroke: 5px #e6d5b3; } Backgrounds Solid and gradient backgrounds applied to first letters (live demo) Adding a background is a simple way to start making a cap more decorative. I could start by adding a solid background-color. p::first-letter { /* ... */ background-color: #97838f; } To add a lighting effect, I could apply a conical, linear, or radial gradient background image (here’s a demo): p::first-letter { /* ... */ background-color: #e6d5b3; background-image: linear-gradient(135deg,#c8b9c2 0%, #7d6975 50%); } And even an image URL to use a bitmap or vector image as a background (and here’s that demo): p::first-letter { /* ... */ background-color: #e6d5b3; background-image: url(...); background-size: cover; } Background images and a background clipped to text Things become even more interesting by clipping a bitmap, gradient, or vector background image to the text while setting its colour to transparent. Now, the image will only appear inside the text space (demo). p::first-letter { /* ... */ background-clip: text; color: transparent; } Borders Two examples of borders applied to first letters, one square and one rounded You might think borders are boring, but there’s plenty you can do to make them look interesting. I could start by applying a solid border to surround the cap box (demo). p::first-letter { /* ... */ border: 5px solid #e6d5b3; } Then, I could apply border-radius to slightly round all its corners (demo). p::first-letter { /* ... */ border-radius: 1rem; } Or, I might round individual corners for a more interesting look (demo): p::first-letter { /* ... */ border-top-left-radius: 3rem; border-bottom-right-radius: 3rem; } A border radius applied to the first letter, where the top-left and bottom-right edges are rounded (live demo) And then there’s the border-image property, a powerful, yet often overlooked CSS tool. By slicing, repeating, and outsetting images, you can create intricate borders and decorative drop caps with minimal code. A CSS border image applied to a first letter (live demo) You can insert a bitmap or vector format image, or drop a CSS gradient into the border space: p::first-letter { /* ... */ border-style: solid; border-width: 10px; border-image: conic-gradient(...) 1; } Clipping Clipping first letters The clip-path property lets you define a custom shape that controls which parts of an element are visible and which are hidden. Instead of always showing a rectangular box, you can use clip-path to crop elements into circles, polygons, or even complex shapes defined with SVG paths. It’s an effective way to create visual effects like this right-facing arrow. Clipping the drop cap into an arrow shape isn’t just decorative — it reinforces direction and hierarchy, literally pointing readers to where the story begins. Here’s a demo of the following example. p::first-letter { /* ... */ padding-inline: 1rem 2rem; background-color: #e6d5b3; clip-path: polygon(...); } Or a glossy sticker shape cap, made by combining clip-path with a gradient background image and a text shadow (demo). Transforms Two examples of transforming first letters, one rotated (demo) and one scaled (demo) You can transform a drop cap independently from the rest of a paragraph by rotating, scaling, skewing, or translating it to make it feel more dynamic: p::first-letter { /* ... */ margin-inline-end: 2.5em; transform: skew(20deg, 0deg); } And with a little trial and error to arrive at the correct values, you could even flow the remaining paragraph text around the cap using the shape-outside property (demo): p::first-letter { /* ... */ display: block; float: left; shape-outside: polygon(0 0, 0 200px, 250px 600px); shape-margin: 50px; transform: skew(20deg, 0deg) translateX(-60px); } Drop caps don’t just help guide a reader’s eye to where they should begin; they also set the tone for what follows. A well-designed drop cap adds visual interest at the start of a block of text, drawing attention in a way that feels intentional and designed. Because it’s often the first element the reader sees, caps can carry a lot of visual weight, making them powerful tools for expressing a brand’s identity. Designing for Patty Meltt Patty Meltt wanted a website packed with design details. Every element added to a design is an opportunity to be expressive, and that includes her drop caps. Her biography page is presentable, but we felt a focus on where someone should start reading was lacking. Patty Meltt’s biography without a drop cap From the selection of designs I showed her, she felt the sticker-style cap best suited her brand. To implement it, first, I added a cursive typeface which matches her branding and contrasts with the rest of her typographic design: p::first-letter { font-family: "Lobster Two", sans-serif; font-weight: 700; } I changed the cap colour to match the page background and added a semi-transparent text shadow: p::first-letter { /* ... */ color: #140F0A; text-shadow: 6px 6px 0 rgba(163,148, 117, .8); } Next, I clipped the cap box to a visible area shaped like a sticker: p::first-letter { /* ... */ clip-path: polygon(...); } …before applying two background images — a noise-filled SVG and a radial gradient — that I blended using a background-blend-mode: p::first-letter { /* ... */ background-image: url(img/cap-noise.svg), radial-gradient(circle, #e6d5b3 0%, #cdaa65 100%); background-blend-mode: soft-light, normal; } Patty Meltt’s biography with a stylsh new drop cap (demo) The result is a drop cap that’s as stylish as cut-off jeans and a pair of gator-skinned boots. Conclusion Styling drop caps isn’t just about decoration — it’s about setting a tone, drawing readers in, and using every detail to express a brand’s voice. CSS has the tools to go beyond the default: gradients, textures, borders, and even complex shapes all help transform first letters into statements. So don’t waste the opportunities that drop caps give you. Make ’em sing. Getting Creative With Versal Letters originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
  22. by: Abhishek Prakash Fri, 18 Jul 2025 17:00:30 +0530 The AWK series continues with two more chapters. I have changed my initial plan to completely publish the AWK series in a couple of weeks. Instead, I'll go for two new chapters each week. The good thing is that we also have an upcoming systemd series by our partner educator, and it should be published next week. I hope you like learning from these new series 💪 💡Next Friday (25th July) will be Sysadmin appreciation day. Would be nice to plan something to observe this day. It's our day after all.       This post is for subscribers only Subscribe now Already have an account? Sign in
  23. By: Janus Atienza Fri, 18 Jul 2025 07:42:22 +0000 Today, enterprises require robust, scalable IT infrastructure to maintain competitiveness. As businesses expand, their network demands grow exponentially, necessitating solutions that ensure reliability, security, and efficiency. Managed networks can provide a strategic advantage by offering centralized control, proactive monitoring, and seamless scalability. These services allow organizations to focus on core operations while ensuring their IT backbone remains resilient and adaptable. Read on to learn how managed networks support scalable IT infrastructure in modern enterprises. The Role of Managed Networks in Scalability Managed networks enable enterprises to scale IT infrastructure efficiently in various ways. With managed support, organizations can adapt to growing demands while maintaining reliability and cost efficiency. Here’s the role of managed networks in scalability: Proactive Monitoring and Maintenance One of the primary benefits of managed networks is continuous monitoring. IT teams can detect and resolve issues before they escalate, minimizing downtime. For instance, in Linux/Unix environments, where server uptime is critical, proactive maintenance can ensure optimal performance. Automated tools can also track system health, log anomalies, and apply patches, reducing manual intervention. Hence, for enterprises leveraging Linux/Unix-based systems, investing in managed network support can help optimize performance. These operating systems, known for their stability and security, are widely used in enterprise environments. However, managing large-scale Linux/Unix networks requires specialized expertise, making managed services an invaluable asset. Enhanced Security and Compliance Security remains a top priority for enterprises, especially those handling sensitive data. Managed networks can implement robust security protocols, including firewalls, intrusion detection systems (IDS), and regular vulnerability assessments. Linux/Unix systems can also benefit from these measures, as they’re often targeted due to their prevalence in enterprise and cloud environments. By enforcing strict security policies, managed service providers (MSPs) can ensure compliance with industry regulations, such as GDPR or HIPAA. Linux/Unix Optimization in Managed Networks Managed networks can enhance Linux/Unix performance. With expert management, businesses can achieve faster deployments, seamless scaling, and reduced latency in high-demand environments. Here’s how managed networks can optimize Linux/Unix performance: Customized Configurations for Peak Performance Linux/Unix systems are highly configurable, allowing enterprises to tailor their environments for specific workloads. Managed network providers can optimize kernel parameters, filesystem settings, and network stack configurations to enhance throughput and reduce latency. For instance, adjusting TCP/IP settings in a Linux server can also significantly improve data transfer speeds in high-traffic scenarios. Automation and Scripting Efficiency Automation is a cornerstone of scalable IT infrastructure. Managed networks can leverage scripting tools to automate repetitive tasks such as backups, user management, and software updates. In Unix-based systems, cron jobs and shell scripts can streamline operations, ensuring consistency across distributed environments. Cost Efficiency and Resource Management Managed networks can drive cost optimization through various solutions, reducing overhead while ensuring scalable, secure networks that grow with enterprise demands. Here’s how modern enterprises can ensure cost efficiency and proper resource management: Reducing Operational Overhead Maintaining dedicated in-house IT teams for enterprise-scale network management requires significant recruitment, training, and retention investments. Managed networks can eliminate these costs by providing on-demand expertise and pay-as-you-go service models. Additionally, businesses can avoid the financial burden of maintaining full-time Linux/Unix specialists while gaining access to enterprise-grade infrastructure management. This operational efficiency allows organizations to reallocate resources toward core business initiatives while maintaining optimal network performance. Scalable Cloud Integration Modern enterprises can increasingly deploy hybrid and multi-cloud architectures combining Linux/Unix servers with leading platforms. Managed network providers can streamline these complex integrations through automated provisioning, cross-platform monitoring, and unified security policies. Their expertise in Kubernetes orchestration, serverless computing, and virtualized environments can ensure seamless workload portability and elastic scaling. This can eliminate cloud vendor lock-in while optimizing performance across distributed infrastructures. Future-Proofing IT Infrastructure Managed networks can empower enterprises to stay ahead of technological evolution by deploying adaptive, forward-looking solutions. These include: Adapting to Emerging Technologies Modern enterprises can face exponential technological evolution with AI workloads, IoT ecosystems, and edge computing architectures. Managed networks can provide the infrastructure agility needed to adopt these innovations seamlessly. For Linux/Unix environments, this translates to optimized support for cutting-edge protocols like MQTT, real-time data processing through Apache Kafka, and distributed computing frameworks like Hadoop while maintaining system stability and performance benchmarks. Disaster Recovery and Business Continuity Enterprise operations demand bulletproof continuity plans to mitigate risks from cyberattacks, hardware failures, or natural disasters. Managed networks can deliver comprehensive protection through automated encrypted backups, geo-redundant failover clusters, and hot-swappable network configurations. Linux/Unix systems can particularly benefit from enterprise-grade tools for backups, high-availability clusters, and snapshot-based recovery. These can ensure sub-15-minute RTOs and zero data loss scenarios. Final Thoughts Managed networks are indispensable for modern enterprises seeking scalable, secure, and efficient IT infrastructure. By keeping the information mentioned above in mind, businesses can optimize Linux/Unix environments, reduce operational costs, and future-proof their networks. As technology advances, enterprises that adopt managed network solutions will maintain a competitive edge in an increasingly digital world. The post How Managed Networks Support Scalable IT Infrastructure In Modern Enterprises appeared first on Unixmen.
  24. by: Abhishek Prakash Fri, 18 Jul 2025 10:47:19 +0530 AWK isn't just a text processor - it's your personal calculator and string manipulation wizard rolled into one. You have already experienced AWK's mathematical capabilities. Now explore the string functions. AWK offers a bunch of built-in functions to deal with strings. Here's a quick look at them: Function Purpose Syntax Example Result length(s) String length length(string) length("hello") 5 substr(s,p,n) Extract substring substr(string, pos, len) substr("hello", 2, 3) "ell" index(s,t) Find substring position index(string, target) index("hello", "ll") 3 split(s,a,fs) Split into array split(string, array, sep) split("a,b,c", arr, ",") 3 (returns count) sub(r,s,t) Replace first match sub(regex, replacement, target) sub(/o/, "0", "hello") "hell0" gsub(r,s,t) Replace all matches gsub(regex, replacement, target) gsub(/l/, "1", "hello") "he110" match(s,r) Find regex position match(string, regex) match("hello", /ll/) 3 sprintf(f,...) Format string sprintf(format, args...) sprintf("%.2f", 3.14159) "3.14" tolower(s) Convert to lowercase tolower(string) tolower("HELLO") "hello" toupper(s) Convert to uppercase toupper(string) toupper("hello") "HELLO" AWK's string functions let you clean, transform, and analyze text data with precision. Let's create a few sample test files. user_data.txt: john.smith@company.com John Smith Active mary.johnson@company.com Mary Johnson Inactive bob.wilson@COMPANY.COM Bob Wilson Active alice.brown@company.com Alice Brown Pending charlie.davis@external.org Charlie Davis Active sara.miller@company.com Sara Miller Active And log_entries.txt: 2024-06-29 ERROR Database connection failed for user admin 2024-06-29 WARNING High memory usage detected on web01 2024-06-29 INFO Backup completed successfully 2024-06-29 ERROR Invalid login attempt from 192.168.1.100 2024-06-29 DEBUG Session cleanup started 2024-06-29 WARNING Disk space low on /var partition Length and Substring FunctionsLet's find out users who have long email addresses in the user_data.txt file: awk '{ email_length = length($1) printf "%-25s: %d characters", $1, email_length if (email_length > 23) printf " (long email)" printf "\n" }' user_data.txt The length() function gives the length of the string here and then a simple comparison does the job. john.smith@company.com : 22 characters mary.johnson@company.com : 24 characters (long email) bob.wilson@COMPANY.COM : 22 characters alice.brown@company.com : 23 characters charlie.davis@external.org: 26 characters (long email) sara.miller@company.com : 23 characters The length() functionNotice how the email address with 26 characters doesn't fit in the specified field of 25? Now let's take it to the next level by extracting the user and domain names from each email address. This will test the use of substr function. awk '{ at_position = index($1, "@") if (at_position > 0) { domain = substr($1, at_position + 1) username = substr($1, 1, at_position - 1) printf "User: %-15s Domain: %s\n", username, domain } }' user_data.txt So what I did here was to use index() to find the @ symbol and substr() to split email into username and domain parts. User: john.smith Domain: company.com User: mary.johnson Domain: company.com User: bob.wilson Domain: COMPANY.COM User: alice.brown Domain: company.com User: charlie.davis Domain: external.org User: sara.miller Domain: company.com The substr() functionCase Conversion FunctionsLet's standardize email domains to lowercase by using the tolower function: awk '{ printf "%-25s -> %s\n", $1, tolower($1) }' user_data.txt It will convert email address to lowercase for consistent email formatting. john.smith@company.com -> john.smith@company.com mary.johnson@company.com -> mary.johnson@company.com bob.wilson@COMPANY.COM -> bob.wilson@company.com alice.brown@company.com -> alice.brown@company.com charlie.davis@external.org -> charlie.davis@external.org sara.miller@company.com -> sara.miller@company.com Convert email address to lowercaseLet's take it a bit further by creating display names from email addresses. Extract the user name first and then separate them at the dot (.). Also make the first letters in uppercases. awk '{ at_position = index($1, "@") username = substr($1, 1, at_position - 1) # Convert to proper case display_name = toupper(substr(username, 1, 1)) substr(username, 2) gsub(/\./, " ", display_name) # Replace dots with spaces printf "Email: %-25s Display: %s\n", $1, display_name }' user_data.txt Worth noticing is substr(username, 2) which doesn't have length specified and thus it takes everything from position 2 till the end. I also used the global gsub although there is no such need in the sample data bit if a username had multiple names separated by dot, it would be handled properly. More on it in the next section. Email: john.smith@company.com Display: John smith Email: mary.johnson@company.com Display: Mary johnson Email: bob.wilson@COMPANY.COM Display: Bob wilson Email: alice.brown@company.com Display: Alice brown Email: charlie.davis@external.org Display: Charlie davis Email: sara.miller@company.com Display: Sara miller Extract the name from the email address and convert to proper cases.Pattern Replacement with sub Clean up log entries by removing timestamps. Use the subtitue function sub() to remove the date pattern from the beginning of each log line. awk '{ # Remove date at beginning sub(/^[0-9-]+ /, "", $0) print "Clean log:", $0 }' log_entries.txt The regex basically looks one more occurrence of a number or dash at the beginning followed by a space and replaces it with ... nothing. And thus remvoving that part completely. Clean log: ERROR Database connection failed for user admin Clean log: WARNING High memory usage detected on web01 Clean log: INFO Backup completed successfully Clean log: ERROR Invalid login attempt from 192.168.1.100 Clean log: DEBUG Session cleanup started Clean log: WARNING Disk space low on /var partition The sub() functionLet's make our output more readable by adding color emojis. awk '{ sub(/ERROR/, "🔴 ERROR", $0) sub(/WARNING/, "🟡 WARNING", $0) sub(/INFO/, "🔵 INFO", $0) sub(/DEBUG/, "🟢 DEBUG", $0) print $0 }' log_entries.txt It looks better, right? 2024-06-29 🔴 ERROR Database connection failed for user admin 2024-06-29 🟡 WARNING High memory usage detected on web01 2024-06-29 🔵 INFO Backup completed successfully 2024-06-29 🔴 ERROR Invalid login attempt from 192.168.1.100 2024-06-29 🟢 DEBUG Session cleanup started 2024-06-29 🟡 WARNING Disk space low on /var partition Colored emojisgsub is used to replace globally, for all the matches, not just the first one like sub. sub vs gsubBoth sub() and gsub() work on replacing a pattern. The major difference being that gsub will replace all the matches while sub only replaces the first match. Here's a simple expression that uses sub: echo "2024-07-17" | awk '{ x = $0; sub("-", ":", x); print x }'It outputs: 2024:07-17Expression that uses sub() functionAnd if I use gsub: echo "2024-07-17" | awk '{ x = $0; gsub("-", ":", x); print x }'The date is properly formatted with all - replaced with : 2024:07:17Expression using the gsub() function💡 Did you notice I used the entire expression in one line? It could also have been written like this: echo "2024-07-17" | awk '{ x = $0 gsub("-", ":", x) print x }'But when you write an AWK expression in one line, you need to separate the commands with a semi-colon ;. In multiline AWK expression, the commands are separated by newline character. Multi-line awk commandsString SplittingLet's use the server_metrics.txt file from the previous chapter: web01 75.5 4096 85.2 45 web02 82.1 2048 78.9 62 db01 68.9 8192 92.3 38 db02 91.2 4096 88.7 71 cache01 45.3 1024 65.4 22 backup01 88.8 2048 91.1 55Now, we parse server names into components. What kind of servers are they (web or db) and what numbers do they have: awk '{ # Split hostname into parts n = split($1, parts, /[0-9]+/) if (n >= 2) { server_type = parts[1] # Extract number gsub(/[^0-9]/, "", $1) server_num = $1 printf "Type: %-8s Number: %s\n", server_type, server_num } }' server_metrics.txt The split() function separates server type from number in hostname patterns like "web01", "db02". Type: web Number: 01 Type: web Number: 02 Type: db Number: 01 Type: db Number: 02 Type: cache Number: 01 Type: backup Number: 01 The split() functionString FormattingCreate a server status report: awk '{ status = "OK" if ($2 > 85) status = "HIGH CPU" if ($4 > 90) status = "HIGH I/O" if ($5 > 70) status = "HOT" printf "%-12s | CPU:%5.1f%% | RAM:%4dMB | I/O:%5.1f | %3d°C | %s\n", $1, $2, $3, $4, $5, status }' server_metrics.txt It creates a formatted status dashboard with aligned columns and status indicators. I let you figure out the code on your own as a practice exercise. 🪧 Time to recallIn this chapter, you learned the following: String functions: Manipulate text with length, substr, index, splitCase conversion: Standardize data with toupper and tolowerPattern replacement: Clean and transform text with sub and gsubThese functions transform AWK from a simple text processor into a complete data analysis and reporting tool. Practice ExercisesTry these exercises with the sample files I've provided: 1. Extract just the domain names from all email addresses 2. Clean email addresses by converting to lowercase and removing extra spaces 3. Calculate the percentage of disk space used across all partitions with the following data: /dev/sda1 50G 35G 12G 75% / /dev/sda2 100G 80G 15G 85% /home /dev/sda3 20G 8G 11G 45% /var /dev/sdb1 500G 300G 175G 65% /data In the next chapter, you'll learn about arrays - AWK's most powerful feature for advanced data analysis and grouping!
  25. by: Abhishek Prakash Fri, 18 Jul 2025 10:45:01 +0530 AWK handles numbers like a built-in calculator. I would say like a scientific calculator, as it has several built-in mathematical functions. You can perform mathematical operations directly on your data fields without any special setup. Let me create some sample files for you to work with: sales_report.txt: Product Price Quantity Discount_Percent Laptop 1299.99 5 10 Desktop 899.50 3 15 Tablet 599.00 8 5 Monitor 349.99 12 20 Keyboard 99.99 15 0 Mouse 49.99 25 12 server_metrics.txt with fields hostname, cpu_percent, memory_mb, disk_io, temp_celsius: web01 75.5 4096 85.2 45 web02 82.1 2048 78.9 62 db01 68.9 8192 92.3 38 db02 91.2 4096 88.7 71 cache01 45.3 1024 65.4 22 backup01 88.8 2048 91.1 55 🚧I'll be using printf command a lot to format the output in the examples in this chapter. While I explain them a little, it would be much better if you made yourself familiar with printf command in bash.Bash printf Command Examples [Better Than Echo]You may print simple outputs with echo command but that’s not enough for complicated formatted outputs.Linux HandbookAbhishek PrakashBasic Arithmetic OperationsTo refresh your memory, here are the basic arithmetic operators in AWK: Operation Operator Example Result Description Addition + 5 + 3 8 Add two numbers Subtraction - 10 - 4 6 Subtract second from first Multiplication * 6 * 7 42 Multiply two numbers Division / 15 / 3 5 Divide first by second Modulo % 10 % 3 1 Remainder after division Exponentiation ^ or ** 2 ^ 3 8 Raise to power You already know that the order of execution matters in arithmetic. So, let's clear that as well. Priority Operations Example 1 () Parentheses (2 + 3) * 4 = 20 2 ^ ** Exponentiation 2 + 3 ^ 2 = 11 3 - Unary minus -5 * 2 = -10 4 * / % Multiply/Divide/Modulo 6 / 2 * 3 = 9 5 + - Add/Subtract 5 - 2 + 1 = 4 With the basics aside, let's do some calculations. Calculate total revenue and discounted pricingCalculate total revenue for each product in the sales_report.txt. awk 'NR > 1 {total = $2 * $3; print $1, "generates $" total}' sales_report.txt It multiplies price (second field $2) by quantity (third field $3) to show total revenue per product, skipping the header line with NR > 1 (line number greater than 1). Laptop generates $6499.95 Desktop generates $2698.5 Tablet generates $4792 Monitor generates $4199.88 Keyboard generates $1499.85 Mouse generates $1249.75 Total revenue and discounted pricingNow, let's apply discounts to calculate final prices: awk 'NR > 1 { discount_amount = ($2 * $4) / 100 final_price = $2 - discount_amount printf "%-10s: $%.2f (was $%.2f, saved $%.2f)\n", $1, final_price, $2, discount_amount }' sales_report.txt The long expression above calculates the discount amount and final price, showing original price and savings with formatted output. The complicated part here could be to understand the formatting I used with printf. This is why I suggested reading about it at the beginning of this tutorial. Quickly, %-10s sets the width to 10 with left alignment (-), %.2f sets the floating point to two decimal points. Laptop : $1169.99 (was $1299.99, saved $130.00) Desktop : $764.58 (was $899.50, saved $134.93) Tablet : $569.05 (was $599.00, saved $29.95) Monitor : $279.99 (was $349.99, saved $70.00) Keyboard : $99.99 (was $99.99, saved $0.00) Mouse : $43.99 (was $49.99, saved $6.00) Calculate final pricesCalculate server temperature in FahrenheitLet's take it to the next level with temperature converter. awk '{ fahrenheit = ($5 * 9/5) + 32 printf "%-10s: %.1f°C = %.1f°F", $1, $5, fahrenheit if (fahrenheit > 140) printf " (HOT!)" printf "\n" }' server_metrics.txt The expression above converts Celsius to Fahrenheit using the conversion formula and flags hot servers in our sample text file server_metrics.txt: web01 : 45.0°C = 113.0°F web02 : 62.0°C = 143.6°F (HOT!) db01 : 38.0°C = 100.4°F db02 : 71.0°C = 159.8°F (HOT!) cache01 : 22.0°C = 71.6°F backup01 : 55.0°C = 131.0°F Calculate server temperature in FahrenheitAdvanced Mathematical FunctionsAWK provides built-in mathematical functions for more complex calculations and you'll see some of them in this section. Function Purpose Example Result sqrt(x) Square root sqrt(16) 4 sin(x) Sine (radians) sin(1.57) 1 (90°) cos(x) Cosine (radians) cos(0) 1 (0°) atan2(y,x) Arc tangent of y/x atan2(1,1) 0.785 (45°) exp(x) e^x (exponential) exp(1) 2.718 log(x) Natural logarithm log(2.718) 1 int(x) Integer part int(3.14) 3 rand() Random 0 to 1 rand() 0.423 (varies) srand(x) Set random seed srand(42) Sets seed to 42 Calculate the square root for performance metricsLet's create performance index from the server metrics file. It will use the sqrt function: awk '{ performance_index = sqrt($2 * $4) printf "%-10s: Performance Index = %.1f\n", $1, performance_index }' server_metrics.txt It creates a composite performance metric using square root of CPU and disk I/O product. web01 : Performance Index = 80.1 web02 : Performance Index = 80.6 db01 : Performance Index = 79.8 db02 : Performance Index = 89.8 cache01 : Performance Index = 54.4 backup01 : Performance Index = 90.0 Calculate Square Root for Performance MetricsRandom number generationLet's generate random server maintenance schedules: awk '{ maintenance_day = int(rand() * 30) + 1 maintenance_hour = int(rand() * 24) printf "%-10s: Schedule maintenance on day %d at %02d:00\n", $1, maintenance_day, maintenance_hour }' server_metrics.txt Remember rand() generates a random number between 0 and 1. So, I multiplied with 30 (for days of months) and 24 (hours of day) and only tool the integer part with int(). Thus we have a script that assigns random maintenance windows within a 30-day period. web01 : Schedule maintenance on day 15 at 08:00 web02 : Schedule maintenance on day 3 at 14:00 db01 : Schedule maintenance on day 22 at 02:00 db02 : Schedule maintenance on day 8 at 19:00 cache01 : Schedule maintenance on day 11 at 05:00 backup01 : Schedule maintenance on day 27 at 16:00 Random number generation⚠️ rand() is not so random in subsequent runs. Run the script a few times. Do you notice something weird? The output stays the same. What's the big deal? Well, you would expect rand() to generate random values in each run and thus giving a random result each time, right? But that doesn't happen here. You see, rand() will generate a random number between 0 and 1 only for the first run. All the subsequent runs will produce the same random numbers. To make it generate radom numbers in each run, set up seed with srand(). 🪧 Time to recallYou now have essential mathematical capabilities: Arithmetic operations: Perform calculations directly on data fieldsMathematical functions: Use sqrt, int, rand for complex calculationsPractice Exercises1. Create a formatted sales report with sales_report.txt in table format with aligned columns showing product, price, quantity, discount, and final revenue. The final output should look like this: | Laptop | 1299.99 | 5 | 10.00% | 5849.95 | | Desktop | 899.50 | 3 | 15.00% | 2293.73 | | Tablet | 599.00 | 8 | 5.00% | 4552.40 | | Monitor | 349.99 | 12 | 20.00% | 3359.90 | | Keyboard | 99.99 | 15 | 0.00% | 1499.85 | | Mouse | 49.99 | 25 | 12.00% | 1099.78 | 2. Calculate the average price of all products in the sales report 3. Convert all temperatures to Kelvin (K = C + 273.15) 4. Find which server has the highest CPU usage and by how much In the next chapter, you'll learn about dealing with string manipulation in AWK.

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.