Feeds
Real Python: Python's Built-in Functions: A Complete Exploration
Python has many built-in functions that you can use directly without importing anything. These functions cover a wide variety of common programming tasks that include performing math operations, working with built-in data types, processing iterables of data, handling input and output in your programs, working with scopes, and more.
In this tutorial, you’ll:
- Get to know Python’s built-in functions
- Learn about common use cases of Python’s built-in functions
- Use these functions to solve practical problems
To get the most out of this tutorial, you’ll need to be familiar with Python programming, including topics like working with built-in data types, functions, classes, decorators, scopes, and the import system.
Get Your Code: Click here to download the free sample code that shows you how to use Python’s built-in functions.
Take the Quiz: Test your knowledge with our interactive “Python's Built-in Functions: A Complete Exploration” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python's Built-in Functions: A Complete ExplorationTake this quiz to test your knowledge of the available built-in functions in Python. By taking this quiz, you'll deepen your understanding of how to use these functions and the common programming problems they cover, from mathematical computations to Python-specific features.
Built-in Functions in PythonPython has several functions available for you to use directly from anywhere in your code. These functions are known as built-in functions and they cover many common programming problems, from mathematical computations to Python-specific features.
Note: Many of Python’s built-in functions are classes with function-style names. Good examples are str, tuple, list, and dict, which are classes that define built-in data types. These classes are listed in the Python documentation as built-in functions and you’ll find them in this tutorial.
In this tutorial, you’ll learn the basics of Python’s built-in functions. By the end, you’ll know what their use cases are and how they work. To kick things off, you’ll start with those built-in functions related to math computations.
Using Math-Related Built-in FunctionsIn Python, you’ll find a few built-in functions that take care of common math operations, like computing the absolute value of a number, calculating powers, and more. Here’s a summary of the math-related built-in functions in Python:
Function Description abs() Calculates the absolute value of a number divmod() Computes the quotient and remainder of integer division max() Finds the largest of the given arguments or items in an iterable min() Finds the smallest of the given arguments or items in an iterable pow() Raises a number to a power round() Rounds a floating-point value sum() Sums the values in an iterableIn the following sections, you’ll learn how these functions work and how to use them in your Python code.
Getting the Absolute Value of a Number: abs()The absolute value or modulus of a real number is its non-negative value. In other words, the absolute value is the number without its sign. For example, the absolute value of -5 is 5, and the absolute value of 5 is also 5.
Note: To learn more about abs(), check out the How to Find an Absolute Value in Python tutorial.
Python’s built-in abs() function allows you to quickly compute the absolute value or modulus of a number:
Python >>> from decimal import Decimal >>> from fractions import Fraction >>> abs(-42) 42 >>> abs(42) 42 >>> abs(-42.42) 42.42 >>> abs(42.42) 42.42 >>> abs(complex("-2+3j")) 3.605551275463989 >>> abs(complex("2+3j")) 3.605551275463989 >>> abs(Fraction("-1/2")) Fraction(1, 2) >>> abs(Fraction("1/2")) Fraction(1, 2) >>> abs(Decimal("-0.5")) Decimal('0.5') >>> abs(Decimal("0.5")) Decimal('0.5') Copied!In these examples, you compute the absolute value of different numeric types using the abs() function. First, you use integer numbers, then floating-point and complex numbers, and finally, fractional and decimal numbers. In all cases, when you call the function with a negative value, the final result removes the sign.
For a practical example, say that you need to compute the total profits and losses of your company from a month’s transactions:
Python >>> transactions = [-200, 300, -100, 500] >>> incomes = sum(income for income in transactions if income > 0) >>> expenses = abs( ... sum(expense for expense in transactions if expense < 0) ... ) >>> print(f"Total incomes: ${incomes}") Total incomes: $800 >>> print(f"Total expenses: ${expenses}") Total expenses: $300 >>> print(f"Total profit: ${incomes - expenses}") Total profit: $500 Copied!In this example, to compute the expenses, you use the abs() function to get the absolute value of the expenses, which results in a positive value.
Finding the Quotient and Remainder in Division: divmod()Python provides a built-in function called divmod() that takes two numbers as arguments and returns a tuple with the quotient and remainder that result from the integer division of the input numbers:
Read the full article at https://realpython.com/python-built-in-functions/ »[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
The Drop is Always Moving: Today DrupalCI and patch testing is turned off on https://drupal.org for good. While it is the end of an era, DrupalCI helped propel us into a strong culture of automated testing. Onwards with the faster and more versatile ...
Today DrupalCI and patch testing is turned off on https://drupal.org for good. While it is the end of an era, DrupalCI helped propel us into a strong culture of automated testing. Onwards with the faster and more versatile @gitlab CI! https://www.drupal.org/about/core/blog/drupalci-and-all-patch-testing-will-be-turned-off-on-july-1-2024
Russell Coker: VoLTE in Australia
In Australia the 3G mobile frequencies are to be reused so they are in the process of shutting down the 3G service. That means that everyone has to use VoLTE (Voice Over LTE) for phone calls (including emergency calls). The shutdown time varies by telco, Kogan Mobile (one of the better services which has good value for money and generally works well) shut down their 3G service in January. Aldi Mobile (another one of the good services which is slightly more expensive but has included free calls to most first-world countries and uses the largest phone network) will shut theirs down at the end of August.
For background there’s a Fosdem talk about OpenSIPS with VoLTE and VoNR [1], it’s more complex than you want to know. Also VoNR (Voice over New Radio) is the standard for 5G voice and it’s different from VoLTE and has a fallback to VoLTE. Another good lecture for background information is the Fosdem talk on VoLTE at the handset end [2].
The PinePhoneProIn October 2023 I tried using my PinePhonePro as my main phone but that only lasted a few days due to problems with calls and poor battery life [3]. Since then I went back to the Huawei Mate 10 Pro that I bought refurbished in June 2019 for $389. So that has been my main phone for 5 years now, giving a cost of $1.50 per week. I had tried using a Huawei Nova 7i running Android without Google Play as an experiment but that had failed, I do many things that need Android apps [4].
I followed the PinePhone wiki to get my PinePhonePro working with VoLTE [5]. That worked fine for me, the only difference from the instructions is that I had to use device /dev/ttyUSB3 and that the modem kept resetting itself during the process and when that happened I had to kill minicom and start again. After changing the setting and saving it the PinePhonePro seemed to work well with VoLTE on a Kogan Mobile SIM (so definitely not using 3G).
One issue I have found is that Plasma Mobile (my preferred FOSS phone GUI) appears to have a library issue that results in polling every 14ms even when the screen is locked [6]. If you have a few processes doing that (which means the most lightly used Plasma system) it really hurts battery use. The maintainer has quite reasonably deferred action on this bug report given the KDE 6 transition. Later on in the Trixie development cycle I hope to get this issue resolved, I don’t expect it to suddenly make battery life good. But it might make battery life acceptable.
I am now idly considering carrying around my PinePhonePro in a powered off state for situations where I might need to do high security operations (root logins to servers or online banking) but for which carrying a laptop isn’t convenient. It will do well for the turn on, do 30 mins of work that needs security, and then turn off scenario.
Huawei Mate 10 Pro and Redmi 9AThe Huawei Mate 10 Pro has been my main phone for 5 years and it has worked well, so it would be ideal if it could do VoLTE as the PinePhonePro isn’t ready yet.
All the web pages I’ve seen about the Mate 10 Pro say that it will either allow upgrading to a VoLTE configuration if run with the right SIM or only support it with the right SIM. I did a test with a Chinese SIM which gave an option of turning on VoLTE but didn’t allow any firmware updates and the VoLTE option went away when I put an Australian SIM in. Some forum comments had led me to believe that it would either permanently enable VoLTE or allow upgrading the firmware to one that enables VoLTE if I used a Chinese SIM but that is not the case. I didn’t expect a high probability of success but I had to give it a go as it’s a nice phone.
I did some tests on a Redmi 9A (a terrible phone that has really bad latency on the UI in spite of having reasonably good hardware). The one I tested on didn’t have VoLTE enabled when I got it, to test that I used the code *#*#4636#*#* in the dialler to get the menu of SIM information and it showed that VoLTE was not provisioned. I then had to update to the latest release of Android for that phone and enter *#*#86583#*#* in the dialler to enable VoLTE, the message displayed after entering that magic number must end in “DISABLE”. I get the impression that the code in question makes the phone not check certain aspects of whether the carrier is good for VoLTE and just do it. So apparently Kogan Mobile somehow gives the Redmi 9A the impression that VoLTE isn’t supported but if the phone just goes ahead and connects it will work. I don’t plan to use a Redmi 9A myself as it’s too slow, but I added it to my collection to offer to anyone else I know who needs a phone with VoLTE and doesn’t use the phone seriously or to someone who needs a known good phone for testing things.
Samsung Galaxy Note 9I got some Samsung Galaxy Note 9 phones to run Droidian as an experiment [7]. But Droidian dropped support for the Note 9 and I couldn’t figure out how to enable VoLTE via Droidian, which was very annoying after I had spent $109 on a test phone and $215 on a phone for real use (I have no plans to try Droidian again at this time). I tried installing LineageOS on one Note 9 [8] which was much easier than expected (especially after previously installing Droidian). But VoLTE wasn’t an option. According to Reddit LineageOS doesn’t support VoLTE on Samsung devices and you can use a “magisk” module or a VoLTE enabler module but those aren’t supported by LineageOS either [9].
I downloaded an original image for the Note 9 from SamsMobile.com [10]. That image booted past the “orange stage” (where if you have problems then your phone is probably permanently useless) but didn’t boot into the OS. A friend helped me out with that and it turned out that the Heimdal flash tool on Linux didn’t do something it needed to do and that Odin on Windows was required. After using Odin everything was fine and I have a Note 9 with VoLTE running the latest Samsung firmware – which is security patch level 1st July 2022!!!
So I have a choice between using a Note 9 for data and SMS while running a current version of Lineage OS with all security fixes or running a Samsung image with no security updates for 2 years which supports phone calls. So based on this I have to recommend Pixel as the phone of choice, it has a decent level of support from Google and long term support from LineageOS. According to the LineageOS web site you can run the current version of Lineage on the original Pixel phone from 2016! Of course getting VoLTE to work on it might be another saga, but it would probably be easier to do with LineageOS on a Pixel than on a Samsung phone.
ConclusionThe operation of the Note 9 for me is decent now apart from the potential security issues. The same goes for selling one of the phones. The PinePhonePro still has potential to become my daily driver at some future time if I and others can optimise power use. Also a complicating factor is that I want to have both Jabber and Matrix be actually instant IM systems not IM with a 5 minute delay, so suspend mode isn’t a good option.
Pixel phones will be a much higher priority when looking at phones to buy in future. The older Pixel phones go for as little as $100 on eBay and can still run the latest LineageOS.
VoLTE seems needlessly complicated.
- [1] https://tinyurl.com/2y4ul68z
- [2] https://tinyurl.com/27sa46fz
- [3] https://etbe.coker.com.au/2023/10/11/pinephone-status/
- [4] https://etbe.coker.com.au/2022/04/20/android-without-play/
- [5] https://wiki.pine64.org/wiki/PinePhone#VoLTE
- [6] https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1073294
- [7] https://etbe.coker.com.au/2024/04/28/note9-droidian/
- [8] https://download.lineageos.org/devices/crownlte/builds
- [9] https://tinyurl.com/2652h7vk
- [10] https://www.sammobile.com/
Related posts:
- Android vs FOSS Phones To achieve my aims regarding Convergence of mobile phone and...
- Is Lebara the Cheapest Mobile Phone company in Australia? My parents have just got a mobile phone with a...
- Changing Phone Prices in Australia 18 months ago when I signed up with Virgin Mobile...
The Drop Times: How AI Enhances Drupal: Smarter and More User-Friendly Websites
Artificial Intelligence (AI) has quickly become a cornerstone of technological innovation. But why is it needed, and how exactly is it changing our lives? To start, imagine a world where machines can predict what you want before you even ask for it. That's the promise of AI, and it's no longer a distant dream.
AI is reshaping industries by automating routine tasks, providing insights through data analysis, and enhancing user experiences with personalization. For instance, in healthcare, AI algorithms can analyze medical records to predict patient outcomes and suggest treatments, drastically improving care quality. In finance, AI-driven systems can detect fraudulent activities in real-time, safeguarding our money and financial data.
Moreover, AI impacts our daily lives more subtly. Think of how Netflix suggests shows you love or how Alexa can answer your questions and control your smart home. These AI-driven features are making life easier and more enjoyable.
Now, let’s introduce AI to Drupal, a powerful content management system (CMS) known for its flexibility and robust features. Integrating AI with Drupal opens new possibilities for web development, making websites smarter and more user-friendly. AI can analyze users' likes and tailor website content to their interests. This means two people visiting the same site might see different content based on their preferences, making their experience more engaging.
Customer support is another area where AI shines. AI chatbots on Drupal sites can answer questions instantly, providing support without making users wait. These chatbots learn from each interaction and improve over time.
AI can also help predict what users will do next. By analyzing user data, AI provides insights into trends and behaviours, helping site administrators make better decisions about content and marketing strategies.
AI is excitingly changing technology, making our lives easier and more efficient. When combined with Drupal, AI takes website development to the next level. From personalizing content and improving search to automating tasks and enhancing customer support, AI makes Drupal sites smarter and more responsive. As AI continues to evolve, it will bring even more improvements, making online experiences better for everyone.
Now, let's delve into the latest Drupal-related news stories and articles covered by The Drop Times:
Check out the article by Alka Elizabeth and Kazima Abbas, sub-editors at The Drop Times, on Drupal Developer Day Burgas. They share insights from the organizers Valery Lourie, Maria Totova-Cholakova, and Hristo Chonov, representing Drupal Bulgaria, as well as speakers Frederik Wouters and Klaus Purer. This year’s event gathered community members to discuss innovative sessions and projects, showcasing how this event is contributing to the future of Drupal.
Additionally, explore the transformative vision behind Drupal Starshot through the insights of Gábor Hojtsy and Pamela Barone with Alka Elizabeth. This ambitious initiative addresses Drupal's past criticisms by enhancing user experience and accessibility with innovative UI improvements and pre-packaged feature sets. Delve into the potential and challenges of Starshot and understand how the leadership team is steering Drupal towards a more user-friendly future.
In his article at The Drop Times, Jay Callicott explores the significance of understanding exponential growth, the transformative power of AI in development, and the critical role of prompt engineering. By harnessing AI tools like the DrupalAI modules, developers can innovate with unprecedented speed and efficiency, navigating the accelerating pace of change in the digital landscape.
Daniel Cothran and Nia Kathoni have introduced a new Drupal module, Views CSV Source, designed to streamline the process of displaying CSV data within Drupal sites. Released on March 5, 2024, and updated on June 25, 2024, this module addresses a common need among Drupal users: the ability to easily display spreadsheet data on a web page without the labour-intensive process of populating a database table. Read more about it here.
Hector Ignacio Iribarne has announced the upcoming Broward Drupal Meetup, scheduled for Wednesday, July 10, 2024, from 7:00 PM to 9:00 PM ET. Organized by Ofer Shaal, Jay Epstein, and Hector Iribarne, this user group meeting will take place online via Zoom. The meetup will focus on discussing Drupal Starshot.
The upcoming Network of European Drupal Associations (NEDA) meeting is scheduled for July 16, 2024, from 2:30 to 4:00 PM (Central European Time—Brussels). This virtual gathering aims to connect members of the Drupal community and local Drupal associations across Europe and beyond. The primary focus is sharing experiences, exploring ways to support each other with knowledge and resources, and discussing common challenges and solutions local associations face.
Don't miss Drupaladas #4 event, "PHPStan in your Projects," scheduled for June 28, 2024, at 12:30 p.m. CEST. This virtual meetup, hosted by Jose Luis Bellido Rojas, will be conducted through a Slack huddle in the #drupal-es channel and features a detailed exploration of PHPStan integration in Drupal projects, led by Alvaro J. Hurtado Villegas.
Drupal Camp Asheville 2024, scheduled for July 12-14, 2024, is just around the corner, with only two and a half weeks left until the event kicks off. As attendees arrive, organizers have arranged a special Thursday night baseball game on the evening of July 11 at the historic McCormick Field.
DrupalJam, held on June 12, 2024, at Fabrique Utrecht, brought together the Drupal community for a day of insightful talks and networking. For those who missed this anniversary edition, the event's highlights are now available on the DrupalJam YouTube channel. The channel has uploaded Dries Buytaert's keynote speech and various insightful sessions for viewers to enjoy. It also features an after-movie capturing the event's atmosphere and memorable moments.
Looking ahead, Drupal Gutenberg v4.0, set for release in August 2024, will feature a major UI refactor specifically tailored for Drupal, moving away from WordPress components. It will introduce single-field editing and make the editor entity agnostic, allowing for editing various content types. The update will also integrate with the Drupal Starshot initiative, enhancing the overall Drupal editing experience.
CKEditor recently announced the release of five new plugins for Drupal users, coinciding with the launch of Drupal 10.3. These updates include the CKEditor 5 Plugin Pack 1.1.0 and CKEditor 5 Premium Features 1.2.9, featuring essential technical fixes and new functionalities to enhance content creation.
We acknowledge that there are more stories to share. However, due to selection constraints, we must pause further exploration for now.
To get timely updates, follow us on LinkedIn, Twitter and Facebook. Also, join us on Drupal Slack at #thedroptimes.
Thank you,
Sincerely,
Kazima Abbas
Sub-editor, The Drop Times
Russell Coker: Links June 2024
Modos Labs have released the design of an e-ink display connected by USB-C [1]. They have provided a lot of background information on e-ink displays which isn’t available elsewhere. Excellent work!
Insightful video by JimmyTheGiant about the destruction of housing estates in the UK [3]. I wonder how much of this was deliberate by the Tories.
Interesting video by Louis Rossmann about the low quality of products and reviews on Amazon [5]. We all know about Enshittification, but it seems that Amazon is getting to the stage of being unusable for some products.
Amusing video by Folding Ideas about Decentraland an attampt at a blockchain based second life type thing which failed as you expect blockchain things to fail [6]. The top comment is a transcription of the actions of the speaker’s pet cat. ;)
- [1] https://github.com/Modos-Labs/Glider?tab=readme-ov-file
- [2] https://tinyurl.com/2yosvptu
- [3] https://www.youtube.com/watch?v=AxCgueTf0W0
- [4] https://www.youtube.com/watch?v=m2KV8MHRJlQ
- [5] https://www.youtube.com/watch?v=y83BS_mK9GE
- [6] https://www.youtube.com/watch?v=EiZhdpLXZ8Q
Related posts:
- Links April 2024 Ron Garret wrote an insightful refutation to 2nd amendment arguments...
- Links October 2023 The Daily Kos has an interesting article about a new...
- Links February 2024 In 2018 Charles Stross wrote an insightful blog post Dude...
Niels Thykier: Debian packaging with style black
When I started working on the language server for debputy, one of several reasons was about automatic applying a formatting style. Such that you would not have to remember to manually reformat the file.
One of the problems with supporting automatic formatting is that no one agrees on the "one true style". To make this concrete, Johannes Schauer Marin Rodrigues did the numbers of which wrap-and-sort option that are most common in https://bugs.debian.org/895570#46. Unsurprising, we end up with 14-15 different styles with various degrees of popularity. To make matters worse, wrap-and-sort does not provide a way to declare "this package uses options -sat".
So that begged the question, how would debputy know which style it should use when it was going to reformat file. After a couple of false-starts, Christian Hofstaedtler mentioned that we could just have a field in debian/control for supporting a "per-package" setting in responds to my concern about adding a new "per-package" config file.
At first, I was not happy with it, because how would you specify all of these options in a field (in a decent manner)? But then I realized that one I do not want all these styles and that I could start simpler. The Python code formatter black is quite successful despite not having a lot of personalized style options. In fact, black makes a statement out of not allowing a lot of different styles.
Combing that, the result was X-Style: black (to be added to the Source stanza of debian/control), which every possible reference to the black tool for how styling would work. Namely, you outsource the style management to the tool (debputy) and then start using your focus on something else than discussing styles.
As with black, this packaging formatting style is going to be opinionated and it will evolve over time. At the starting point, it is similar to wrap-and-sort -sat for the deb822 files (debputy does not reformat other files at the moment). But as mentioned, it will likely evolve and possible diverge from wrap-and-sort over time.
The choice of the starting point was based on the numbers posted by Johannes #895570. It was not my personal favorite but it seemed to have a majority and is also close to the one suggested by salsa pipeline maintainers. The delta being -kb which I had originally but removed in 0.1.34 at request of Otto Kekäläinen after reviewing the numbers from Johannes one more time.
To facilitate this new change, I uploaded debputy/0.1.30 (a while back) to Debian unstable with the following changes:
- Support for the X-Style: black header.
- When a style is defined, the debputy lsp server command will now automatically reformat deb822 files on save (if the editor supports it) or on explicit "reformat file" request from the editor (usually indirectly from the user).
- New subcommand debputy reformat command that will reformat the files, when a style is defined.
- A new pre-commit hook repo to run debputy lint and debputy reformat. These hooks are available from https://salsa.debian.org/debian/debputy-pre-commit-hooks version v0.1 and can be used with the pre-commit tool (from the package of same name).
The obvious omission is a salsa-pipeline feature for this. Otto has put that on to his personal todo list and I am looking forward to that.
Beyond blackAnother thing I dislike about our existing style tooling is that if you run wrap-and-sort without any arguments, you have a higher probability of "trashing" the style of the current package than getting the desired result. Part of this is because wrap-and-sort's defaults are out of sync with the usage (which is basically what https://bugs.debian.org/895570 is about).
But I see another problem. The wrap-and-sort tool explicitly defined options to tweak the style but provided maintainers no way to record their preference in any machine readable way. The net result is that we have tons of diverging styles and that you (as a user of wrap-and-sort) have to manually tell wrap-and-sort which style you want every time you run the tool.
In my opinion that is not playing to the strengths of neither human nor machine. Rather, it is playing to the weaknesses of the human if anything at all.
But the salsa-CI pipeline people also ran into this issue and decided to work around this deficiency. To use wrap-and-sort in the salsa-CI pipeline, you have to set a variable to activate the job and another variable with the actual options you want.
The salsa-CI pipeline is quite machine readable and wrap-and-sort is widely used. I had debputy reformat also check for the salsa-CI variables as a fallback. This fallback also works for the editor mode (debputy lsp server), so you might not even have to run debputy reformat. :)
This was a deliberate trade-off. While I do not want all us to have all these options, I also want Debian packaging to be less painful and have fewer paper cuts. Having debputy go extra lengths to meet wrap-and-sort users where they are came out as the better solution for me.
A nice side-effect of this trade-off is that debputy reformat now a good tool for drive-by contributors. You can safely run debputy reformat on any package and either it will apply the styling or it will back out and inform you that no obvious style was detected. In the latter case, you would have to fallback to manually deducing the style and applying it.
Differences to wrap-and-sortThe debputy reformat has some limitations or known differences to wrap-and-sort. Notably, debputy reformat (nor debputy lsp server) will not invoke wrap-and-sort. Instead, debputy has its own reformatting engine that provides similar features.
One reason for not running wrap-and-sort is that I want debputy reformat to match the style that debputy lsp server will give you. That way, you get consistent style across all debputy commands.
Another reason is that it is important to me that reformatting is safe and does not change semantics. This leads to two regrettable known differences to the wrap-and-sort behavior due to safety in addition to one scope limitation in debputy:
- debputy will ignore requests to sort the stanzas when the "keep first" option is disabled (-b --no-keep-first). This combination is unsafe reformatting. I feel it was a mistake for wrap-and-sort to ever allow this but at least it is no longer the default (-b is now -bk by default). This will be less of a problem in debhelper-compat 15, since the concept of "main package" will disappear and all multi-binary source packages will be required to use debian/package.install rather than debian/install.
- debputy will not reorder the contents of debhelper packaging files such as debian/install. This is also an (theoretical) unsafe thing to do. While the average package will not experience issues with this, there are rare corner cases where the re-ordering can affect the end result. I happen to know this, because I ran into issues when trying to optimize dh_install in a way that assumed the order did not matter. Stuff broke and there is now special-case code in dh_install to back out of that optimization when that happens.
- debputy has a limited list of wrap-and-sort options it understands. Some options may cause debputy to back out and disable reformatting entirely with a remark that it cannot apply that style. If you run into a case of this, feel free to file a feature request to support it. I will not promise to support everything, but if it is safe and trivially doable with the engine already, then I probably will.
As stated, where debputy cannot implement the wrap-and-sort styles fully, then it will currently implement a subset that is safe if that can be identified or back out entirely of the formatting when it cannot. In all cases, debputy will not break the formatting if it is correct. It may just fail at correcting one aspect of the wrap-and-sort style if you happen to get it wrong.
It is also important to remember that the prerequisite for debputy applying any wrap-and-sort style is that you have set the salsa-CI pipeline variables to trigger wrap-and-sort with the salsa-CI pipeline. So there is still a CI check before the merge that will run the wrap-and-sort in its full glory that provides the final safety net for you.
Just give me a styleIn conclusion, if you, like me, are more interested in getting a consistent style rather than discussing what that style should be, now you can get that with X-Style: black. You can also have your custom wrap-and-sort style be picked up automatically for drive-by contributors.
$ apt satisfy 'dh-debputy (>= 0.1.30), python3-lsprotocol' # Add ``X-Style: black`` to ``debian/control`` for "just give me a style" # # OR, if there is a specific ``wrap-and-sort`` style for you then set # SALSA_CI_DISABLE_WRAP_AND_SORT=no plus set relevant options in # SALSA_CI_WRAP_AND_SORT_ARGS in debian/salsa-ci.yml (or .gitlab-ci.yml) $ debputy reformatIt is sadly not yet in the salsa-ci pipeline. Otto is looking into that and hopefully we will have it soon. :)
And if you find yourself often doing archive-wide contributions and is tired of having to reverse engineer package formatting styles, consider using debputy reformat or debputy lsp server. If you use debputy in this way, please consider providing feedback on what would help you.
Guido Günther: Free Software Activities June 2024
A short status update of what happened on my side last month. Was able to test our Cellbroadcast bits, feedbackd became more flexible regarding LEDs, Phosh 0.40 is out, and some more.
Phosh- Phosh 0.40.0
- Fix testing custom quick setting plugins (MR)
- Add icons for dark style toggles (thanks to Sam Hewitt for the help) (MR, MR)
- 0.39.x backports (MR)
- Set default sound-theme (MR)
- Launch apps in transient scope (MR)
- Allow to suspend from lock screen (MR)
- Fix media player button style (MR)
- Don't use plain .so for bindings lib (MR)
- Fling gesture to open/close phosh's panels (MR)
- Fix crash on output removal (MR)
- Don't draw decorations when maximized (MR)
- Allow to stack layer surfaces (MR was a bit older, polished up to land it) (MR)
- Add hwdb support for Juno tablets (based on information by Giovanni Caligaris) (MR)
- Support add generic BT AVRCP profile (with the help of Phil Hands) (MR)
- Released 0.2.1
- Use shared gmobile (MR)
- Add sound theme (MR)
- Add a major mode for systemd-hwdb files (MR)
- Backport phog fix to work with phosh-osk-stub (MR)
- Release git snapshot of phosh-wallpaper for NEW processing (MR)
- Backport phosh fixes for 0.39.0 (MR)
- Phoc: Install examples, they're useful for debugging (MR)
- Make libpam-ccreds work with gcrypt 1.11:
- Upload phosh release 0.40.0~rc1 and 0.40.0
- phog: Add example for autologin (MR)
- Update firefox-esr-mobile-config (thanks to Peter Mack for the input) (MR)
- Tweak meta-phosh:
- Test our current code at NLalert test day: Current branch
- Only apply Qualcom bits to lpg driver (MR)
- Support arbitrary RGB values for multicolor LEDs (MR)
- Allow to use camera flash LEDs as status LEDs (MR)
- End too noisy feedback when switching profile levels (MR)
- Packaging fixes (MR) , MR)
- device-themes: Lower brightness of feedback events as the flash is too bright on OnePlus 6T (MR)
- cli: Inform user when nothing was triggered (MR)
- Released 0.4.0
- Allow to display a Matrix clients access token (MR)
- libcmatrix: Add support handling push notification servers (MR)
- Allow to add push notification servers (draft)) (MR)
- Package docs (MR)
- Fix use-after-free in stackable-box (MR)
If you want to support my work see donations.
Talk Python to Me: #468: Python Trends Episode 2024
eGenix.com: eGenix PyRun - One file Python Runtime 2.5.0 GA
eGenix PyRun™ is our open source, one file, no installation version of Python, making the distribution of a Python interpreter to run Python based scripts and applications to Unix based systems simple and efficient.
eGenix PyRun's executable only needs 4-6MB on disk, but still supports most Python applications and scripts.
Compared to a regular Python installation of typically 100MB on disk, eGenix PyRun is ideal for applications and scripts that need to be distributed to containers, VMs, clusters, client installations, customers or end-users.
It makes "installing" Python on a Unix based system as simple as copying a single file.
eGenix has been using eGenix PyRun as run-time for the Linux version of mxODBC Connect Server product since 2008 with great success and decided to make it available as a stand-alone open-source product.
We provide the source archive to build your own eGenix PyRun on Github, as well as a few binary distributions to get you started on Linux x86_64. In the future, we will set up automated builds for several other platforms.Please see the product page for more details:
>>> eGenix PyRun - One file Python Runtime
NewsThis major release of eGenix PyRun comes with the following enhancements:
Enhancements / Changes- Added support for Python 3.8 - 3.11
- Removed support for Python 3.5-3.7
- Modernized the directory setup and build
- Changed the license to the Apache2 license
- Extracted the code from our internal mono-repo to put on Github
- Relaunched the project on Github
Please visit the eGenix PyRun product page for downloads, instructions on installation and documentation of the product.
Commercial support for this product is available directly from eGenix.com.
Please see the support section of our website for details.
For more information on eGenix PyRun, licensing and download instructions, please write to sales@egenix.com.
Enjoy !
Marc-Andre Lemburg, eGenix.com
EuroPython: How to Maximize Your Experience at EuroPython 2024 🐍✨
EuroPython 2024 is set to be an electrifying event for Python enthusiasts, taking place in the vibrant city of Prague from July 8th to 14th. Whether you&aposre a first-timer or a seasoned attendee, here are some tips to help you squeeze every bit of goodness out of the conference.
Plan Your Schedule in Advance 🗓️Review the EuroPython schedule to spot sessions, workshops, and events that spark your interest. The week is loaded with activities: Monday and Tuesday are for tutorials and free workshops (C API Summit, HumbleData, DjangoGirls and WASM Summit); Wednesday to Friday are full of keynotes and talks, social events, PyLadies events and panel discussions. Finally, the weekend is reserved for the Open Source Sprints.
Mix and match your experience by attending a variety of sessions! From technical talks and tutorials to keynote speeches, there&aposs a smorgasbord of content for all levels. We have talks for beginners and advanced Pythonistas including tracks like Python internals, LLMs, Ethics & Philosophy, Web Technologies, Education & Community, DevOps, and so much more.
Pro tip: Keynote speakers always drop some serious knowledge bombs 😉Engage in Workshops & Summits 🛠️Dive into workshops for a hands-on learning adventure. Whether you&aposre a newbie learning to build websites with Django Girls or exploring data science with HumbleData, there&aposs something for everyone. Discuss the state of the C API at the C API Summit or get the latest on WebAssembly at the WASM Summit.
Some of these events have limited slots, while others are first-come, first-served. Make sure to register on the website https://ep2024.europython.eu/programme and arrive early on the day of the event!
Network Actively 🤝Sessions are packed with information, but they might not cover your particular problem. Don&apost hesitate to ask the speakers about anything they didn&apost cover. Make sure to use Discord to reach out if you cannot find them in the corridors.
All participants should join our Discord server as this is the main communication platform during the conference. The link invite will be sent via email on the following days.
Take advantage of breaks to mingle and tap into the wealth of knowledge around you. And don&apost forget the Pac-Man rule: always leave a spot open so others can easily join the conversation.
Engage in the Hallway & Harness the power of networking!Chat with fellow attendees, speakers, and sponsors during breaks, social events, and open spaces. Networking can lead to new collaborations, job opportunities, and friendships within the Python community. Here are some tips to help you start a conversation
- Look for lanyards with the "speaker" tag and ask them about their topic.
- Approach someone with a simple "Hi, what do you think of the event so far?" or "What sessions have you found interesting?"
- Pay attention to the stickers on people&aposs badges indicating their preferred level of contact: "no contact," "happy to hug," or "handshake only." Always respect these preferences.
Remember it&aposs normal to feel shy, many people do, but the Python community is known for being extra nice :) Don&apost miss out on the chance to connect with others, this is the perfect place to try and reach out.
Visit the Sponsors Hall 🛍️Stroll through the Sponsor&aposs Hall to check out the latest products and services from exhibitors. It&aposs swag central and a goldmine for discovering new tools and technologies to boost your Python projects. A lot of our sponsors are also actively hiring in case you are on the lookout.
If you are attending remotely, Sponsors will have channels where you can chat and find out more. Remember to also keep an eye on the Virtual Swag and Job board on our website for extra gifts.
Attend Social Events 🎉Don&apost miss the social events like the PyLadies lunch and Social Event, Prague Boat Trip, Speakers’ Dinner, and the big Social Event where you are invited to bring your board games and instruments!
These events are perfect for connecting & sharing ideas with like-minded individuals in a relaxed setting. Plus, they are a whole lot of fun! 🎉
Take Care of Yourself 🧘Conferences are a marathon, not a sprint. Stay hydrated, eat well, and get plenty of rest. We will help by serving light lunches, snacks and coffee during the breaks throughout the day. Take breaks to recharge and keep your energy levels high.
Feeling overwhelmed? We have a Quiet Room and a low-stimulation room at the venue so you can wind down.
Explore Prague 🏰Seize the chance to explore the enchanting city of Prague. Dive into the local culture, savour the cuisine, and visit the landmarks. The Prague Congress Centre is conveniently located, making it easy to venture out.
Our volunteers wrote a page with tips and things to do: https://ep2024.europython.eu/explore
We hope it helps you and your companions to have a great time in Prague 😃
Share Your Experience 📢After the conference, share your newfound wisdom with your community. Write a blog post, give a presentation, or organize a meetup to spread the knowledge. It reinforces what you&aposve learned and helps those who couldn&apost attend.
Make sure to tag us on socials @EuroPython or use #EuroPython2024. We will be reposting the coolest community posts during the event!
ConclusionEuroPython 2024 promises to be an enriching experience brimming with learning, networking, and fun. By planning ahead, engaging actively, and taking care of yourself, you&aposll make the most of this incredible event.
See you in Prague! 🌟
For more details, visit the EuroPython 2024 official website.
Golems GABB: Leveraging AI and Machine Learning in Drupal
Dries Buytaert once predicted that AI bots would provide factual information and communicate with emotions and personality, offering more human-like interactions than websites.
Artificial intelligence technologies have recently begun to be actively used in various fields, including web development. But what exactly? Implementing AI into your Drupal-based website opens up vast opportunities to improve your business's efficiency, significantly improve your customers' service quality, and much more. In this article, you will learn how to achieve success by using AI and Machine Learning in Drupal.
Abhijith PA: A lazy local file sharing setup
At home, I have both a laptop and a *desktop PC. Most of my essential things, such as emails, repositories, password managers, contacts, and calendars are synced between the two devices. However, when I need to share some documents and I am lazy enough to go pick a flash drive, my only option is to push them to the Internet and download them on the other system, which is sitting at 20~ meters away. Typically, I do this either through email attachments or a matrix client.
Occasionally, I think about setting up a network storage solution at home. But then I ask myself do I really need one.
In my home network, I already have a Raspberry Pi running as my Wi-Fi router, doing DNS level ad blocking with Dnsmasq and DNS over TLS with stubby. Rpi has a 16GB memory card. I can mount RPi remote directory to both machines.
I use pcmanfm as my file manager. It has the ability (like every other file managers) to mount remote storage over ssh. But one annoying thing is that whenever I open the mount directory, by default it shows the root file system of the remote device even when I explicitly mentioned the path.
Then I discovered sshfs. I wrote the following script, which mount remote directory and open that in pcmanfm.
#!/bin/bash LOCMOUNT="/home/user/Public" sshfs raspberrypi:Public $LOCMOUNT pcmanfm $MOUNTI haven’t enabled any encryption for the memory until now since other than some logs RPi wasn’t writing anything to it. I set up fscrypt on Rpi storage now. And ta-da, a lazy person’s local sharing solution.
*Desktop - Well, technically it’s an old laptop with a broken keyboard and trackpad, connected to a monitor, keyboard and mouse. I don’t feel keeping it on a shelf.
Russ Allbery: Review: Snuff
Review: Snuff, by Terry Pratchett
Series: Discworld #39 Publisher: Harper Copyright: October 2011 Printing: January 2013 ISBN: 0-06-221886-7 Format: Mass market Pages: 470Snuff is the 39th Discworld novel and the 8th (and last) Watch novel. This is not a good place to start reading.
Sam Vines has been talked, cajoled, and coerced into taking a vacation. Since he is now the Duke of Ankh, he has a country estate that he's never visited. Lady Sybil is insistent on remedying this, as is Vetinari. Both of them may have ulterior motives. They may also be colluding.
It does not take long for Vimes to realize that something is amiss in the countryside. It's not that the servants are uncomfortable with him talking to them, the senior servants are annoyed that he talks to the wrong servants, and the maids turn to face the wall at the sight of him. Those are just the strange customs of the aristocracy, for which he has little understanding and even less patience. There's something else going on. The nobility is wary, the town blacksmith is angry about something more than disliking the nobles, and the bartender doesn't want to get involved. Vimes smells something suspicious.
When he's framed for a murder, the suspicions seem justified.
It takes some time before the reader learns what the local nobility are squirming about, so I won't spoil it. What I will say is that Snuff is Pratchett hammering away at one of his favorite targets: prejudice, cruelty, and treating people like things. Vimes, with his uncompromising morality, is one of the first to realize the depth of the problem. It takes most of the rest longer to come around, even Sybil. It's both painful, and painfully accurate, to contemplate how often recognition of other people's worth only comes once they do something that you recognize as valuable.
This is one of the better-plotted Discworld novels. Vimes starts out with nothing but suspicions and stubbornness, and manages to turn Snuff into a mystery novel through dogged persistence. The story is one continuous plot arc with the normal Pratchett color (Young Sam's obsession with types of poo, for example) but without extended digressions. It also has considerably better villains than most Pratchett novels: layers of foot soldiers and plotters, each of which have to be dealt with in a suitable way. Even the concluding action sequences worked for me, which is not always a given in Discworld.
The problem, unfortunately, is that the writing is getting a bit wobbly. Pratchett died of early-onset Alzheimer's in 2015, four years after this book was first published, and this is the first novel where I can see some early effects. It mostly shows up in the dialogue: it's just a bit flabby and a bit repetitive, and the characters, particularly towards the end of the book, start repeating the name of the person they're talking to every other line. Once I saw it, I couldn't unsee it, and it was annoying enough to rob a bit of enjoyment from the end of the book.
That aside, though, this was a solid Discworld novel. Vimes testing his moral certainty against the world and forcing it into a more ethical shape is always rewarding, and here he takes more risks, with better justification, than in most of the Watch novels. We also find out that Vimes has a legacy from the events of Thud!, which has interesting implications that I wish Pratchett had more time to explore.
I think the best part of this book is how it models the process of social change through archetypes: the campaigner who knew the right choice early on, the person who formed their opinion the first time they saw injustice, the person who gets there through a more explicit moral code, the ones who have to be pushed by someone who was a bit faster, the ones who have to be convinced but then work to convince others, and of course the person who is willing to take on the unfair and far-too-heavy burden of being exceptional enough that they can be used as a tool to force other people to acknowledge them as a person. And, since this is Discworld, Vetinari is lurking in the scenery pulling strings, balancing threats, navigating politics, and giving Vimes just enough leeway to try to change the world without abusing his power. I love that the amount of leeway Vimes gets depends on how egregious the offense is, and Vetinari calibrates this quite carefully without ever saying so openly.
Recommended, and as much as I don't want to see this series end, this is not a bad entry for the Watch novels to end on.
Followed in publication order by Raising Steam.
Rating: 8 out of 10
Week 5 recap
Morpht: To PDF or not to PDF? Government sites in Australia
Initial work on Keychain
A month ago, I started working on a new application to manage your passwords in Plasma. And while still at a PoC status, this weekend, it finally started to look like something almost usable, so it sounded like a good occassion to write a small blog post about it.
The current name is “Keychain” or “Plasma Keychain” but this is subject to change and suggestions are more than welcome.
My end goal is to provide a more future proof replacement to the ageing KWallet application. From a technical point of view, this is a fork of the internal of KeepassXC with a Kirigami GUI completely written from scratch. This means it uses the standardized Keepass format to store the passwords in the database which is implemented by many applications including on other platforms like Android and iOS (see the list of Keepass port). And while not yet exposed in the GUI, basing the work on top of KeepassXC enables a lot of interesting features not available in KWallet, like Yubikey and PassKey support, password sharing, export and import for various other password database formats, TOTP support and browser integration…
While also providing vital features for the desktop integration like the Freedesktop Secret Service protocol what we also have in KWallet.
Here are some screenshots of the current state.
This is the main view where viewing, adding, editing and removing entries already work.
This is the database generator page which unfortunately doesn’t work yet.
And this is the UI to open an existing database.
As you can see there is still a lot of work required, so if people are interested to help or to take a look at the current progress, the code is on KDE’s gitlab instance.
Mario Hernandez: Components variations in Storybook
One great way to extend your catalog of components is by creating components variations. Variations, in the context of component-driven development, refers to displaying your content in different ways. Variations of a component reduce the need of building new components as well as duplicate code.
In Storybook, variations are known as Stories. In this post I will be using variations and stories interchangeably.
The image below shows how different card stories or variations, can display the same content in many ways.
Fig. 1: Example of multiple variations of a Card component.
Principles of building componentsSometimes when building a new component, we can't anticipage how the website will evolve with time and therefore we build components the best way possible at the time of building them. As time goes by and requirements change, we realize that we could have done things differently had we known about the requirements changes. Variations of a component give you a chance to alter how something was built without having to change your entire environment of content architecture.
Some time ago I wrote about principles for building components. Rather than repeating myself, take a quick look at the article and comeback when you are done. You will find those principles not only apply to building new components, but also to building variations of components.
Building component variations in StorybookIn Storybook, all variations of a component are referred to as "Stories", hence the name Storybook. A story captures the rendered state of a UI component. Developers write multiple stories per component that describe all the “interesting” states/variations a component can support. Here's a visual that describes the official naming and hierarchy Storybook uses.
Fig. 2: Storybook's official naming convention and hierarchy.
The Card componentFirst off, I am going with the assumption that you already know how Storybook stories are created and that you have a Storybook instance running. If that's not the case, follow these instructions to get your Storybook environment up and running. You will need NodeJS 20+ and NVM installed on your system to follow along.
Next, let's look at the Card variations we will be creating in this post.
Fig. 3: Example of the different card variations we will build in this post.
The image above shows the Card stories or variations we will build. From top-left to right:
- Default or Stacked
- Light CTA
- Small
- No image
- Horizontal
In the interest of time, I have a repo that already includes the base of the Card component so you can focus only on building the variations.
-
Clone the repo which already contains a project to work with and the Card component.
If you already have a working Storybook environment, copy the components directory (src/components), from the newly cloned repo, into your project. -
Switch to the variations branch by running git checkout variations
-
Run the project as instructed in the README in the repo
In this tutorial, we will use two methods for creating variations in Storybook:
- Doing all the work directly in card.stories.jsx to change fields values or hide/show fields, depending on the story requirements.
- Using additional *.yml files to assist with the same fields updates above.
We will be using the first method above for all stories except the Card horizontal. The original Card component was built with Twig, but for the variations we will be working exclusively in card.stories.jsx. The current version of the card story looks like this:
import parse from 'html-react-parser'; import card from './card.twig'; import data from './card.yml'; import './card.css'; const component = { title: 'Molecules/Card', render: (args) => parse(card(args)), }; export const Card = { name: 'Card stacked', args: { ...data }, }; export default component;Let me explain the snippet above as this is the foundation for all the variations we will be creating.
-
First we do a series of imports to collect all the pieces needed to build components and stories:
- import parse: This is a react plugin which allows us to parse the HTML in our stories into React code Storybook can understand.
- import card: It imports all the code and logic inside our component's twig template.
- import data: Pulls in all the data from the component's .yml file so we can use it as React args.
- import './card.css': Imports all CSS styles so Storybook can displayed the styled components and stories. Inside card.css, we already have styles for each of the stories we will be building.
-
Next, we set a new configuration object called component, which will serve as the default instance of the card component. This is an arbitrary name and can be anything that makes sense to you.
Inside the component object we have two properties: title and render.- The title property's value determines the location and name of the component within Storybook's hierarchy. In this example the Card component will be located under the Molecules folder. See Fig.2 above for details about the hierarchy.
- The render property is what handles the rendering of the component by using the card and data objects we imported earlier, and combined together (Twig and YML), they render the full component.
-
Next, we create our first story by defining a new configuration object called Card, in which we pass a name (Card stacked), for the story and the data variable as args.
-
Finally, we export the component object as default, which is a React requirement.
If Storybook is running, you should see the new variation which will display the Card stacked. If you need to run Storybook for the first time, in your command line navigate to the storybook directory and run these commands:
IMPORTANT: You need NodeJS 20+ and NVM installed in your system. nvm install npm install npm run build npm run storybookIf all goes well, Storybook should be running showing the Card stacked story under the Molecules folder.
Preview of Card stackedFig. 4: Example of the Card stacked from which other variations will originate.
Card with light CTA- Inside card.stories.jsx, and directly after the closing of the Card object (around line 17), add the following object to create a new story:
Let's go over the snippet above:
- We start by creating and exporting a new object called CardLightCta. This is a new story. This name is arbitrary but it should be unique for each story.
- Next, we pass the default Card story (...Card), as a spread operator, so the new story inherits all attributes from the original card.
- The name property allows for each story to have a unique name which will appear directly under the component name in Storybook's sidebar (see Fig. 2 at the top for details).
- Finally, we open the args object where we will update some of the fields to achieve the desired variation:
- We pass the ...data object as a spread operator to individually update the fields that need updating.
- Since the only difference between this variation and the original card is that the CTA is light, we need to define the cta object and provide each of its properties with the appropriate values:
- First as a modifier class we pass button--light. This is a predefined modifier class which will turn the CTA white.
- Next, we type the text that will become the CTA's label, Try it now.
- And finally, we pass a URL to the CTA.
Fig. 5: Example of a Card component with a light CTA.
Card smallThis next story or variation is the small version of the card. The difference between this card and the original one is that this one has no CTA, and its size is ...well, small 🙂
Same as before, add the following snippet to card.stories.jsx directly after the closing of the card with light CTA story:
export const CardSmall = { ...Card, name: 'Card small', args: { ...data, modifier: 'card--small', cta: '', }, };This story is very similar to the previous one from the updates needed point of view. As you can see, the only thing we are doing is passing card--small as a modifier class to the entire component, and since we don't need a button or CTA, we are defining the cta object but its value is empty which will suppress it from printing on the page. If you notice in card.twig, we use a conditional that checks if the cta object exists, otherwise don't print any of the markup starting with the footer tag.
Preview of small cardFig. 6: Example of a small card.
Card with no image- You know the drill, inside card.stories.jsx, directly after the closing of the previous story, add the following snippet:
Even more similar to the previous story, this variation only varies from the original story as follows:
- We are passing a modifier class to the component, card--no-image.
- Since we want no image, we define the image object but leave its value empty.
Fig. 6: Example of a card without image.
Card horizontalThe final variation is the Card horizontal. For all previous variations we have done all the changes inside card.stories.jsx, but for this one, we will resource to using an alternative *.yml file. Why you may ask, well, this variation requires a bit more changes and making all those changes inside the stories.jsx file may look a little too busy and not as easy to read the code. That's pretty much the only reason for me to use this method, to keep the code in my stories clean and more readable.
You may have noticed in the project you cloned; inside the card directory we have a file called card-horizontal.yml. This file is almost identical to the original card.yml as far as the fields in it. The only difference is that some of the fields have unique content or no content at all. Let's look at the file before starting.
--- modifier: 'card--horizontal' image: <img src="/card-square.jpg" alt="Palm trees near city buildings" /> title: level: 2 modifier: 'card__title' text: 'Step outside to the outdoors' url: 'https://mariohernandez.io' teaser: 'With spring in full bloom, the weather could not be better to take a walk outside and enjoy the beauty of nature.' cta: ''- The modifier field has a specific CSS class we will pass: card--horizontal. This class will allow us to change the layout of the card to be in horizontal direction.
- The image field uses a different image altogether. The image has been cropped in square aspect ratio for better fitting of this variation.
- Finally, the cta field is empty, meaning we don't want to print a button on this variation.
Maybe I exaggerated when I said that this variation has too many changes, but my point is that in cases when your stories do require a lot of changes, using a different yml file may help you keep your stories.jsx file a lot neater and cleaner.
- The first step is one we haven't done before. Inside card.stories.jsx somewhere around line 5 (after the last import in the file), add the following import:
- Next, the way we've done before, inside card.stories.jsx add the following object directly after the closing of the last story:
- First we imported a new data file called card-horizontal.yml and assigned the object name of dataHorizontal. By doing this, any changes we make inside card-horizontal.yml will be reflected in Storybook.
- Lastly, we repeat the same process as the previous variations but this time, inside the args object, we pass the new object we created in the previous step (...dataHorizontal), rather than ...data.
- That's it. Our story file is nice and clean. Since we handled all the fields updates in card-horizontal.yml, the .jsx file is simply consuming its data to achieve the desired variations.
Fig. 6: Example of a card in horizontal layout.
Now that we have covered both methods for creating variations, know that neither method is better than the other. The decision to use one over the other boils down to personal preferences and sometimes which makes the most sense to simplify the process.
End resultAt the end of this process, your card.stories.jsx should look like this:
import parse from 'html-react-parser'; import card from './card.twig'; import data from './card.yml'; import dataHorizontal from './card-horizontal.yml'; import './card.css'; const component = { title: 'Molecules/Card', render: (args) => parse(card(args)), }; export const Card = { name: 'Card stacked', args: { ...data }, }; export const CardLightCta = { ...Card, name: 'Card light CTA', args: { ...data, cta: { modifier: 'button--light', text: 'Try it now', url: 'https://mariohernandez.io', } }, }; export const CardSmall = { ...Card, name: 'Card small', args: { ...data, modifier: 'card--small', cta: '', }, }; export const CardNoImage = { ...Card, name: 'Card no image', args: { ...data, modifier: 'card--no-image', image: '', }, }; export const CardHorizontal = { ...Card, name: 'Card horizontal', args: { ...dataHorizontal, }, }; export default component; In closingThis only touches the surface of creating stories, but it is refreshing to know that no matter how complex your components may be, when it comes to having Storybook parse them, the React code in your stories is very minimum. Certainly, there are exceptions, but as I complete the migration of our large Drupal project with many components, some of which are pretty large and complex, we still were surprised how little React code was required of us to write because all the heavy lifting is being done by Storybook, with its contrib extensions, as well as Twig itself.
poke @ Savannah: GNU poke 4.2 released
I am happy to announce a new release of GNU poke, version 4.2.
This is a bugfix release in the 4.x series.
See the file NEWS in the distribution tarball for a list of issues
fixed in this release.
The tarball poke-4.2.tar.gz is now available at
https://ftp.gnu.org/gnu/poke/poke-4.2.tar.gz.
> GNU poke (http://www.jemarch.net/poke) is an interactive, extensible
> editor for binary data. Not limited to editing basic entities such
> as bits and bytes, it provides a full-fledged procedural,
> interactive programming language designed to describe data
> structures and to operate on them.
Thanks to the people who contributed with code and/or documentation to
this release.
Happy poking!
Mohammad-Reza Nabipoor