text
stringlengths
60
353k
source
stringclasses
2 values
# Requirements We do not write code for the sake of writing code: we develop software to _help people perform tasks_. These people can be "anyone on Earth" for widely-used software such as GitHub, "people who do a specific job" for internal applications, or even a single person whose life can be helped with software. In order to know _what_ software to develop, we must know what user needs: their _requirements_. ## Objectives After this lecture, you should be able to: - Define what user requirements are - Formalize requirements into _personas_ and _user stories_ - Develop software based on formalized requirements - Understand _implicit_ vs _explicit_ requirements ## What are requirements? A requirement is something users need. For instance, a user might want to move from one place to another. They could then use a car. But perhaps the user has other requirements such as not wanting or being able to drive, in which case a train could satisfy their requirements. Users may also have more specific requirements, such as specifically wanting a low-carbon means of transportation, and having to travel between places that are far from public transport, in which case an electric car powered with low-carbon electricity could be a solution. Requirements are _not_ about implementation details. A specific kind of electric motor no a specific kind of steel for the car doors are not user requirements. However, users may have needs that lead to such choices being made by the system designers. Sometimes you may encounter a division between "functional" and "non-functional" requirements, with the latter also being known as "quality attributes". "Functional" requirements are those that directly relate to features, whereas "non-functional" ones include accessibility, security, performance, and so on. The distinction is not always clear, but it is sometimes made anyway. Defining requirements typically starts by discussing with users. This is easier if the software has a small and well-defined set of users, such as software specifically made for one person to do their job in a company. It is harder if the software has a large and ill-defined set of users, such as a search engine or an app to listen to music. It is important, when listening to what users say, to keep track of what they _need_ rather than what they _want_. What users claim they want is heavily influenced by what they already know and use. For instance, someone used to traveling by horse who needs to go across a mountain might ask for a "flying horse", when in fact their need is crossing the mountain, and thus a train with a tunnel or a plane would satisfy their requirements. Similarly, before the modern smart phone, users would have asked for old-style phones purely because they did not even know a smart phone was feasible, even if now they actually like their smart phone more than they liked their old phone. What users want can be ambiguous, especially when there are many users. If you select cells with "100" and "200" in a spreadsheet program such as Microsoft Excel and expand the selection, what should happen? Should Excel fill the new cells with "300", "400", and so on? Should it repeat "100" and "200" ? What if you expand a selection containing the lone cell "Room 120" ? Should it be repeated or should it become "Room 121", "Room 122", and so on? There is no perfect answer to these questions, as any answer will leave some users unsatisfied, but a developer must make a choice. Not listening to users' requirements can be costly, as Microsoft found out with Windows 8. Windows 8's user interface was a major reinvention of the Windows interface, using a "start screen" rather than a menu, with full-screen apps that could be tiled rather than moved. It was a radical departure from the Windows that users knew, and it was a commercial failure. Microsoft had to bring back the start menu, and abandoned the concept of tiled full-screen apps. However, Apple later did something similar for a new version of their iPad operating system, and it worked quite well there, perhaps because users have different expectations on desktops and tablets. ## How can we formalize requirements? Once you've discussed with plenty of users and gotten many ideas on what requirements users have, how do you consolidate this feedback into actionable items? This is what formalizing requirements is about, and we will discuss formalizing _who_ with "personas" and _what_ with "user stories". Who is the software for? Sometimes the answer to that question is obvious because it is intended for a small and specific set of users, but most large pieces of software are intended for many people. In fact, large pieces of software typically have way too many users for any kind of personalized process to scale. Instead, you can use _personas_ to represent groups of users. A persona is an _abstract_ person that represents a group of similar users. For instance, in a music app, one persona might be Alice, a student, who uses the app in her commute on public transport. Alice is not a real person, and she does not need specific features such as a hair color or a nationality. Instead, Alice is an abstract representation of many people who could use the app and all have similar features from the app's point of view, namely that they use the app on public transport while commuting to their school, university, or other similar place. Alice's requirements might lead to features such as downloading podcasts in advance at home, and listening with the screen turned off. Another persona for the same app might be Bob, a pensioner, who uses the app while cooking and cleaning. Bob is not a real person either, but instead represents a group of potential users who aren't so familiar with the latest technology and want to use the app while performing tasks at home. While one can create personas for many potential groups of users, not all of them will make the cut. Still for the music app example, another persona could be Carol, a "hacker" who wants to listen to pirated music. Carol would need features such as loading existing music tracks into the app and bypassing copyright protection. Is the app intended for people like Carol? That's up to the developers to decide. One last word about personas: avoid over-abstracting. Personas are useful because they represent real people in ways that are helpful to development. If your personas end up sounding like "John, a user who uses the app" or "Jane, a person who has a phone", they will not be useful. Similarly, if you already know who exactly is in a group of users, there is no need to abstract it. "Sam, a sysadmin" is not a useful persona if your app has exactly one sysadmin: use the real person instead. --- #### Exercise What personas could a video chat app have? <details> <summary>Example solutions (click to expand)</summary> <p> Anne, a manager who frequently talks to her team while working remotely. Basil, a pensioner who wants to video chat his grandkids to stay in touch. Carlos, a doctor who needs to talk to patients as part of a telemedicine setup. </p> </details> --- What can users do? After defining who the software is for, one must decide what features to build. _User stories_ are a useful tool to formalize features based on requirements, including who wants the feature, what the feature is, and what the context is. Context is key because the same feature could be implemented in wildly different ways based on context. For instance, "sending emails with information" is a feature a software system might have. If the context is that users want to archive information, the emails should include very detailed information, but their arrival time matters little. If the context is that users want a notification as soon as something happens, the emails should be sent immediately, and great care should be taken to avoid ending up in a spam filter. If the context is that users want to share data with their friends who don't use the software, the emails should have a crisp design that contains only the relevant information so they can be easily forwarded. There are many formats for user stories; in this course, we will use the three-part one "_as a ... I want to ... so that ..._". This format includes the user who wants the feature, which could be a persona or a specific role, the feature itself, and some context explaining why that user wants that feature. For instance, "As a student, I want to watch course recordings, so that I can catch up after an illness". This user story lets developers build a feature that is actually useful to the person: it would not be useful to this student, for instance, to build a course recording feature that is an archive accessible once the course has ended, since presumably the student will not be ill for the entire course duration. Going back to our music app example, consider the following user story: "As Alice, I want to download podcasts in advance, so that I can save mobile data". This implies the app should download the entire podcast in advance, but Alice still does have mobile data, she just doesn't want to use too much of it. A similar story with a different context could be "As a commuter by car, I want to download podcasts in advance, so that I can use the app without mobile data". This is a different user story leading to a different feature: now the app cannot use mobile data at all, because the commuter simply does not have data at some points of their commute. To evaluate user stories, remember the "INVEST" acronym: - *I*ndependent: the story should be self-contained - *N*egotiable: the story is not a strict contract but can evolve - *V*aluable: the story should bring clear value to someone - *E*stimable: the developers should be able to estimate how long the story will take to implement - *S*mall: the story should be of reasonable size, not a huge "catch-all" story - *T*estable: the developers should be able to tell what acceptance criteria the story has based on its text, so they can test their implementation Stories that are too hard to understand and especially too vague will fail the "INVEST" test. #### Exercise What user stories could a video chat app have? <details> <summary>Example solutions (click to expand)</summary> <p> As Anne, I want to see my calendar within the app, so that I can schedule meetings without conflicting with my other engagements. As Basil, I want to launch a meeting from a message my grandkids send me, so that I do not need to spend time configuring the app. As a privacy enthusiast, I want my video chats to be encrypted end-to-end, so that my data cannot be leaked if the app servers get hacked. </p> </details> #### Exercise Which of the following are good user stories and why? 1. As a user, I want to log in quickly, so that I don't lose time 2. As a Google account owner, I want to log in with my Gmail address 3. As a movie buff, I want to view recommended movies at the top on a dark gray background with horizontal scroll 4. As an occasional reader, I want to see where I stopped last time, so that I can continue reading 5. As a developer, I want to improve the log in screen, so that users can log in with Google accounts <details> <summary>Solutions (click to expand)</summary> <p> 1 is too vague, 2 is acceptable since the reason is implicit and obvious, 3 is way too specific, 4 is great, and 5 is terrible as it relates to developers not users. </p> </details> ## How can we develop from requirements? You've listened to users, you abstracted them into personas and their requirements into user stories, and you developed an application based on that. You're convinced your personas would love your app, and your implementation answers the needs defined by the user stories. After spending a fair bit of time and money, you now have an app that you can demo to real users... and they don't like it. It's not at all what they envisioned. What went wrong? What you've just done, asking users for their opinion on the app, is _validation_: checking if what you specified is what users want. This is different from _verification_, which is checking if your app correctly does what you specified. One key to successful software is to do validation early and often, rather than leaving it until the end. If what you're building isn't what users want, you should know as soon as possible, instead of wasting resources building something nobody will use. To do this validation, you will need to build software in a way that can be described by users, using a _common language_ with them and _integrating_ them into the process so they can give an opinion. We will see two ways to do this. First, you need a _common language_ with your users, as summarized by Eric Evans in his 2003 book "Domain-Driven Design". Consider making some candy: you could ask people in advance whether they want some candy containing NaCl, $C_{24}$ $H_{36}$ $O_{18}$, $C_{36}$ $H_{50}$ $O_{25}$, $C_{125}$ $H_{188}$ $O_{80}$, and so on. This is a precise definition that you could give to chemists, who would then implement it. However, it's unlikely an average person will understand until your chemists actually build it. Instead, you could ask people if they want candy with "salted caramel". This is less precise, as one can imagine different kinds of salted caramel, but much more understandable by the end users. You don't need to create salted caramel biscuits for people to tell you whether they like the idea or not, and a discussion about your proposed candy will be much more fruitful using the term "salted caramel" than using any chemical formula. In his book, Evans suggests a few specific terms that can be taught to users, such as "entity" for objects that have an identity tied to a specific property, "value object" for objects that are data aggregates without a separate identity, and so on. The point is not which exact terms you use, but the idea that you should design software in a way that can be easily described to users. Consider what a user might call a "login service", which identifies users by what they know as "email addresses". A programmer used to the technical side of things might call this a `PrincipalFactory`, since "principals" is one way to call a user identity, and a "factory" is an object that creates objects. The identifiers could be technically called "IDs". However, asking a user "What should happen when the ID is not found? Should the principal returned by the factory be `null`?" will yield puzzled looks. Most users do not know any of these terms. Instead, if the object in the code is named `LoginService`, and takes in objects of type `Email` to identify users, the programmer can now ask the user "What should happen when the email is not found? Should the login process fail?" and get a useful answer. Part of using the _right_ vocabulary to discuss with people is also using _specific_ vocabulary. Consider the term "person". If you ask people at a university what a "person" is, they will mumble some vague answer about people having a name and a face, because they do not deal with general "people" in their jobs. Instead, they deal with specific kinds of people. For instance, people in the financial service deal with "employees" and "contractors", and could happily teach you exactly what those concepts are, how they differ, what kind of attributes they have, what operations are performed on their data, and so on. Evans calls this a "bounded context": within a specific business domain, specific words have specific meanings, and those must be reflected in the design. Imagine trying to get a financial auditor, a cafeteria employee, and a professor to agree on what a "person" is, and to discuss the entire application using a definition of "person" that includes all possible attributes. It would take forever, and everyone would be quite bored. Instead, you can talk to each person separately, represent these concepts separately in code, and have operations to link them together via a common identity, such as one function `get_employee(email)`, one function `get_student(email)`, and so on. Once you have a common language, you can also write test scenarios in a way users can understand. This is _behavior-driven development_, which can be done by hand or with the help of tools such as [Cucumber](https://cucumber.io/) or [Behave](https://behave.readthedocs.io/). The idea is to write test scenarios as three steps: "_given ... when ... then ..._", which contain an initial state, an action, and a result. For instance, here is a Behave example from their documentation: ``` Scenario Outline: Blenders Given I put <thing> in a blender, when I switch the blender on then it should transform into <other thing> Examples: Amphibians | thing | other thing | | Red Tree Frog | mush | Examples: Consumer Electronics | thing | other thing | | iPhone | toxic waste | | Galaxy Nexus | toxic waste | ``` Using this text, one can write functions for "putting a thing in a blender", "switching on the blender", and "checking what is in the blender", and Behave will run the functions for the provided arguments. Users don't have to look at the functions themselves, only at the text, and they can then state whether this is what they expected. Perhaps only blue tree frogs, not red ones, need to turn into mush. Or perhaps the test scenario is precisely what they need, and developers should go implement the actual feature. The overall workflow is as follows: 1. Discuss with users to get their requirements 2. Translate these requirements into user stories 3. Define test scenarios based on these user stories 4. Get feedback on these scenarios from users 5. Repeat as many times as needed until users are happy, at which point implementation can begin #### Exercise What language would you use to discuss a course registration system at a university (or any other system you use frequently), and what test scenarios could you define? <details> <summary>Example solutions (click to expand)</summary> <p> A course registration system could have students, which are entities identified by a university e-mail who have a list of courses and grades associated with the courses, and lecturers, which are associated with the courses they teach and can edit said courses. Courses themselves might have a name, a code, a description, and a number of credits. Some testing scenarios might be "given that a user is already enrolled in a course, when the user tries to enroll again, then that has no effect", or "given that a lecturer is in charge of a course, when the lecturer sets grades for a student in the course, then that student's grade is updated". </p> </details> ## What implicit requirements do audiences have? Software engineers design systems for all kinds of people, from all parts of the world, with all kinds of needs. Often some people have requirements that are _implicit_, yet are just as required as the requirements they will explicitly tell you about. Concretely, we will see _localization_, _internationalization_, and _accessibility_. Sometimes these are shortened to "l10n", "i18n", and "a11y", each having kept their start and end letter, with the remaining letters being reduced to their number. For instance, there are 10 letters between "l" and "n" in "localization", thus "l10n". _Localization_ is all about translations. Users expect all text in programs to be in their language, even if they don't explicitly think about it. Instead of `print("Hello " + user)`, for instance, your code should use a constant that can be changed per language. It is tempting to have a `HELLO_TEXT` constant with the value `"Hello "` for English, but this does not work for all languages because text might also come after the user name, not only before. The code could thus use a function that takes care of wrapping the user name with the right text: `print(hello_text(user))`. Localization may seem simple, but it also involves double-checking assumptions in your user interface and your logic. For instance, a button that can hold the text "Log in" may not be wide enough when the text is the French "Connexion" instead. A text field that is wide enough for each of the words in "Danube steamship company captain" might overflow with the German "Donaudampfschifffahrtsgesellschaftkapitän". Your functions that provide localized text may need more information than you expect. English nouns have no grammatical gender, so all nouns can use the same text, but French has two, German has three, and Swahili has [eighteen](https://en.wikipedia.org/wiki/Swahili_grammar#Noun_classes)! English nouns have one "singular" and one "plural" form, and so do many languages such as French, but this is not universal; Slovenian, for instance, has one ending for 1, one for 2, one for 3 and 4, and one for 5 and more. Translations can have bugs just like software can. For instance, the game Champions World Class Soccer's German translation infamously has a bug in which "shootout" is not, as it should, translated to "schiessen", but instead to "scheissen", which has an entirely different meaning despite being one letter swap apart. Another case of German issues is [in the game Grandia HD](https://www.nintendolife.com/news/2019/08/random_amazingly_grandia_hds_translation_gaffe_is_only_the_second_funniest_german_localisation_mistake): missing an attack displays the text "fräulein", which is indeed "miss" but in an entirely different context. Localization is not something you can do alone unless you are translating to your native language, since nobody knows all features of all languages. Just like other parts of software, localization needs testing, in this case by native speakers. _Internationalization_ is all about cultural elements other than language. Consider the following illustration: <p align="center"><img alt="Illustration of (from left to right) a dirty t-shirt, a washing machine, a clean t-shirt" src="images/washing.svg" width="50%" /></p> What do you see? Since you're reading English text, you might think this is an illustration of a t-shirt going from dirty to clean through a washing machine. But someone whose native language is read right to left, such as Arabic, might see the complete opposite: a t-shirt going from clean to dirty through the machine. This is rather unfortunate, but it is the way human communication works: people have implicit expectations that are sometimes at odds. Software thus needs to adapt. Another example is putting "Vincent van Gogh" in a list of people sorted by last name. Is Vincent under "G" for "Gogh" or under "V" for "van Gogh"? That depends on who you ask: Dutch people expect the former, Belgians the latter. Software needs to adapt, otherwise at least one of these two groups will be confused. Using the culture-specific format for dates is another example: "10/01" mean very different dates to an American and to someone from the rest of the world. One important part of localization is people's names. Many software systems out there are built with odd assumptions about people's names, such as "they are composed entirely of letters", or "family names have at least 3 letters", or simply "family names are something everyone has". In general, [programmers believe many falsehoods about names](https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/), which leads to a lot of pain for people who have names that do not comply to those falsehoods, such as people with hyphens or apostrophes in their names, people whose names are one or two letters long, people from cultures that do not have a concept of family names, and so on. Remember that _a person's name is never invalid_. Like localization, internationalization is not something you can do alone. Even if you come from the region you are targeting, that region is likely to contain many people from many cultures. Internationalization needs testing. _Accessibility_ is a property software has when it can be used by everyone, even people who cannot hear, cannot see, do not have hands, and so on. Accessibility features include closed captions, text-to-speech, dictation, one-handed keyboards, and so on. User interface frameworks typically have accessibility features documented along with their other features. These are not only useful to people who have permanent disabilities, but also to people who are temporarily unable to use some part of their body. For instance, closed captions are convenient for people in crowded trains who forgot their headphones. Text-to-speech is convenient for people who are doing something else while using an app on their phone. Features designed for people without hands are convenient for parents holding their baby. Accessibility is not only a good thing to do from a moral standpoint: it is often legally required, especially in software for government agencies. It is also good even from a selfish point of view: a more accessible app has more potential customers. ## Are all requirements ethical? We've talked about requirements from users under the assumption that you should do whatever users need. But is that always the case? Sometimes, requirements conflict with your ethics as an engineer, and such conflicts should not be brushed aside. Just because "a computer is doing it" does not mean the task is acceptable or that it will be performed without any biases. The computer might be unbiased, but it is executing code written by a human being, which replicates that human's assumptions and biases, as well as all kinds of issues in the underlying data. For instance, there have been many variants of "algorithms to predict if someone will be a criminal", using features such as people's faces. If someone were to go through a classroom and tell every student "you're a criminal" or "you're not a criminal", one would reasonably be upset and suspect all kinds of bad reasons for these decisions. The same must go for a computer: there is no magical "unbiased", "objective" algorithm, and as a software engineer you should always be conscious of ethics. ## Summary In this lecture, you learned: - Defining and formalizing user needs with requirements, personas, and user stories - Developing based on requirements through domain-driven design and behavior-driven development - Understanding implicit requirements such as localization, internationalization, accessibility, and ethics You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Performance Producing correct results is not the only goal of software. Results must be produced in reasonable time, otherwise users may not wait for a response and give up. Providing a timely response is made harder by the interactions between software components and between software and hardware, as well as the inherent conflicts between different definitions of performance. As a software engineer, you will need to find out what kind of performance matters for your code, measure the performance of your code, define clear and useful performance goals, and ensure the code meets these goals. You will need to keep performance in mind when designing and writing code, and to debug the performance issues that cause your software to not meet its goals. ## Objectives After this lecture, you should be able to: - Contrast different metrics and scales for performance - Create benchmarks that help you achieve performance objectives - Profile code to find performance bottlenecks - Optimize code by choosing the right algorithms and tradeoffs for a given scenario ## What is performance? There are two key metrics for performance: _throughput_, the number of requests served per unit of time, and _latency_, the time taken to serve one request. In theory, we would like latency to be constant per request and throughput constant over time, but in practice, this is usually never the case. Some requests fundamentally require more work than others, such ordering a pizza with 10 toppings compared to a pizza with only cheese and tomatoes. Some requests go through different code paths because engineers made tradeoffs, such as ordering a gluten-free pizza taking more time because instead of maintaining a separate gluten-free kitchen, the restaurant has to clean its only kitchen. Some requests compete with other requests for resources, such as ordering a pizza right after a large table has placed an order in a restaurant with only one pizza oven. Latency thus has many sub-metrics in common use: mean, median, 99th percentile, and even latency just for the first request, i.e., the time the system takes to start. Which of these metrics you target depends on your use case, and has to be defined in collaboration with the customer. High percentiles such as the 99th percentile make sense for large systems in which many components are involved in any request, as [Google describes](https://research.google/pubs/pub40801/) in their "Tail at Scale" paper. Some systems actually care about the "100th percentile", i.e., the _worst-case execution time_, because performance can be a safety goal. For instance, when an airplane pilot issues a command, the plane must reply quickly. It would be catastrophic for the plane to execute the command minutes after the pilot has issued it, even if the execution is semantically correct. For such systems, worst-case execution time is typically over-estimated through manual or automated analysis. Some systems also need no variability at all, i.e., _constant-time_ execution. This is typically used for cryptographic operations, whose timing must not reveal any information about secret keys or passwords. In a system that serves one request at a time, throughput is the inverse of mean latency. In a system that serves multiple requests at a time, there is no such correlation. For instance, one core of a dual-core CPU might process a request in 10 seconds while another core has served 3 requests in that time, thus the throughput was 4 requests per 10 seconds but the latency varied per request. We used "time" as an abstract concept above, but in practice you will use concrete units such as minutes, seconds, or even as low as nanoseconds. Typically, you will care about the _bottleneck_ of the system: the part that takes the most time. There is little point in discussing other parts of the system since their performance is not key. For instance, if it takes 90 seconds to cook a pizza, it is not particularly useful to save 0.5 seconds when adding cheese to the pizza, or to save 10 nanoseconds in the software that sends the order to the kitchen. If you're not sure of how long a nanosecond is, check out [Grace Hopper's thought-provoking illustration](https://www.youtube.com/watch?v=gYqF6-h9Cvg) (the video has manually-transcribed subtitles you can enable). Grace Hopper was a pioneer in programming languages. With her team, she designed COBOL, the first language that could execute English-like commands. As she [recalled](https://www.amazon.com/Grace-Hopper-Admiral-Computer-Contemporary/dp/089490194X) it, "_I had a running compiler and nobody would touch it. They told me computers could only do arithmetic_". Thankfully, she ignored the naysayers, or we wouldn't be programming in high-level languages today! _Amdahl's law_ states that the speedup achieved by optimizing one component is at most that component's share of overall execution time. For instance, if a function takes 2% of total execution time, it is not possible to speed up the system more than 2% by optimizing that function, even if the function itself is made orders of magnitude faster. As you can tell, the word "performance" hides a lot of details, and "improving performance" is usually too abstract a goal. Optimizing a system requires clear goals defined in terms of specific workloads and metrics, and an understanding of which parts of the system currently take the most time. Performance objectives for services used by customers are typically defined in terms of _Service Level Indicators_, which are measures such as "median request latency", _Service Level Objectives_, which define goals for these measures such as "under 50ms", and _Service Level Agreements_, which add consequences to objectives such as "or we reimburse 20% of the customer's spending that month". Picking useful objectives is a key first step. "As fast as possible" is usually not useful since it requires too many tradeoffs, as [pizza chain Domino's found out](https://www.nytimes.com/1993/12/22/business/domino-s-ends-fast-pizza-pledge-after-big-award-to-crash-victim.html) after their promise of reimbursing late pizzas led to an increase in car crashes for their drivers. Systems should be fast enough, not perfect. What "enough" is depends on the context. Some software systems have specific performance requirements. Other times the performance requirements are implicit, making them harder to define. For instance, in 2006 Google [found](http://glinden.blogspot.com/2006/11/marissa-mayer-at-web-20.html) that traffic dropped 20% if their search results took 0.9s to show instead of 0.4s. In 2017, Akamai [found](https://www.akamai.com/uk/en/about/news/press/2017-press/akamai-releases-spring-2017-state-of-online-retail-performance-report.jsp) that even a 100ms increase in page load time could lead to a 7% drop in sales. In general, if users feel that an interface is "too slow", they won't like it, and if they have another choice they may use it instead. ## How can one measure performance? The process of measuring performance is called _benchmarking_, and it is a form of testing for performance. Like tests, benchmarks are usually automated, and come with issues such as how to isolate a specific component rather than always benchmark the entire system. Benchmarks for individual functions are typically called _microbenchmarks_, while benchmarks for entire systems are "end to end". In theory, benchmarking is a simple process: start a timer, perform an action, stop the timer. But in practice, there are many tricky parts. How precise is the timer? What's the timer's resolution? How variable is the operation? How many measurements should be taken for the results to be valid? Should outliers be discarded? What's the best API on each OS to time actions? How to avoid "warm up" effects? And caching effects? Are compiler optimizations invalidating the benchmark by changing the code? You should never write your own benchmarking code. (Unless you become an expert in benchmarking, at which point you will know you can break this rule.) Instead, use an existing benchmarking framework, such as JMH for Java, BenchmarkDotNet for .NET, or pytest-benchmark for Python. In practice, to benchmark some code, you first need to define the workload you will use, i.e., the inputs, and the metric(s) you care about. Then you need a _baseline_ for your benchmark. Absolute performance numbers are rarely useful, instead one usually compares to some other numbers, such as the performance of the previous version of the software. For low-level code or when benchmarking operations that take very little time, you may also need to set up your system in specific ways, such as configuring the CPU to not vary its frequency. It is very easy to accidentally write benchmark code that is meaningless in a non-obvious way. Always ask your colleagues to review your benchmark code, and provide the code whenever you provide the results. Try small variations of the code to see if you get small variations in the benchmark results. If you have any, reproduce previous results to ensure that your overall setup works. Beware of the "small input problem": it is easy to miss poorly-performing algorithms by only benchmarking with small inputs. For instance, if an operation on strings is in `O(n^3)` of the string length and you only use a string of size 10, that is 1000 operations, which is instantaneous on any modern CPU. And yet the algorithm is likely not great, since `O(n^3)` is usually not an optimal solution. Make sure you are actually measuring what you want to measure, rather than intermediate measurements that may or may not be representative of the full thing. For instance, [researchers found](https://dl.acm.org/doi/abs/10.1145/3519939.3523440) that some garbage collectors for Java had optimized for the time spent in the garbage collector at the expense of the time taken to run an app overall. By trying to minimize GC time at all costs, some GCs actually increased the overall running time. Finally, remember that it is not useful to benchmark and improve code that is already fast enough. While microbenchmarking can be addictive, you should spend your time on tasks that have impact to end users. Speeding up an operation from 100ms to 80ms can feel great, but if users only care about the task taking less than 200ms, they would probably have preferred you spend time on adding features or fixing bugs. ## How can one debug performance? Just like benchmarking is the performance equivalent of testing, _profiling_ is the performance equivalent of debugging. The goal of profiling is to find out how much time each operation in a system takes. There are two main kinds of profilers: _instrumenting_ profilers that add code to the system to record the time before and after each operation, and _sampling_ profilers that periodically stop the program to take a sample of what operation is running at that time. A sampling profiler is less precise, as it could miss some operations entirely if the program happens to never be running them when the profiler samples, but it also has far less overhead than an instrumenting profiler. It's important to keep in mind that the culprit of poor performance is usually a handful of big bottlenecks in the system that can be found and fixed with a profiler. The average function in any given codebase is fast enough compared to those bottlenecks, and thus it is important to profile before optimizing to ensure an engineer's time is well spent. For instance, a hobbyist once managed to [cut loading times by 70%](https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/) in an online game by finding the bottlenecks and fixing them. Both of them were `O(n^2)` algorithms that could be fixed to be `O(n)` instead. There are plenty of profilers for each platform, and some IDEs come with their own. For instance, Java has VisualVM. ## How can one improve performance? The typical workflow is as follows: 1. Double-check that the code is actually correct and that it is slower than what users need (otherwise there is no point in continuing) 2. Identify the bottleneck by profiling 3. Remove any unnecessary operations 4. Make some tradeoffs, if necessary 5. Go to step 1 Identifying the problem always requires measurements. Intuition is often wrong when it comes to performance. See online questions such as ["Why is printing "B" dramatically slower than printing "#"?"](https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing) or ["Why does changing 0.1f to 0 slow down performance by 10x?"](https://stackoverflow.com/questions/9314534/why-does-changing-0-1f-to-0-slow-down-performance-by-10x). Once a problem is found, the first task is to remove any unnecessary operations the code is doing, such as algorithms that can be replaced by more efficient ones without losing anything other than development time. For instance, a piece of code may use a `List` when a `Set` would make more sense because the code mostly checks for membership. Or a piece of code may be copying data when it could use a reference to the original data instead, especially if the data can be made immutable. This is also the time to look for existing faster libraries or runtimes, such as [PyPy](https://www.pypy.org/) for Python, that are usually less flexible but are often enough. If necessary, after fixing obvious culprits that do not need complex tradeoffs, one must make serious tradeoffs. Unfortunately, in practice, performance tradeoffs occur on many axes: latency, throughput, code readability and maintainability, and sub-axes such as specific kinds of latency. ### Separating common cases One common tradeoff is to increase code size to reduce latency by adding specialized code for common requests. Think of how public transport is more efficient than individual cars, but only works for specific routes. Public transport cannot entirely replace cars, but for many trips it can make a huge difference. If common requests can be handled more efficiently than in the general case, it is often worthwhile to do so. ### Caching It is usually straightforward to reduce latency by increasing memory consumption through _caching_, i.e., remembering past results. In fact, the reason why modern CPUs are so fast is because they have multiple levels of caches on top of main memory, which is slow. Beware, however: caching introduces potential correctness issues, as the cache may last too long, or return obsolete data that should have been overwritten with the results of a newer query. ### Speculation and lazy loading You go to an online shop, find a product, and scroll down. "Customers who viewed this item also viewed..." and the shop shows you similar items you might want to buy, even before you make further searches. This is _speculation_: potentially lowering latency and increasing throughput if the predictions are successful, at the cost of increasing resource use and possibly doing useless work if the predictions are wrong. The opposite of speculation is _lazy loading_: only loading data when it is absolutely needed, and delaying any loading until then. For instance, search engines do not give you a page with every single result on the entire Internet for your query, because you will most likely find what you were looking for among the first results. Instead, the next results are only loaded if you need them. Lazy loading reduces the resource use for requests that end up not being necessary, but requires more work for requests that are actually necessary yet were not executed early. ### Streaming and batching Instead of downloading an entire movie before watching it, you can _stream_ it: your device will load the movie in small chunks, and while you're watching the first few chunks the next ones can be downloaded in the background. This massively decreases latency, but it also decreases throughput since there are more requests and responses for the same amount of overall data. The opposite of streaming is _batching_: instead of making many requests, make a few big ones. For instance, the postal service does not come pick up your letters every few minutes, since most trips would be a waste; instead, they come once or twice a day to pick up all of the letters at once. This increases throughput, at the expense of increasing latency. ## Summary In this lecture, you learned: - Defining performance: latency, throughput, variability, and objectives - Benchmarking and profiling: measuring and understanding performance and bottlenecks - Tradeoffs to improve performance: common cases, caching, speculation vs lazy loading, and streaming vs batching You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Debugging > **Prerequisite**: You are _strongly_ encouraged, though not strictly required, to use an IDE for the exercises about debugging in this lecture. > Alternatively, you can use Java's built-in command-line debugger, `jdb`, but it is far less convenient than a graphical user interface. Writing code is only one part of software engineering; you will often spend more time _reading_ code than writing code. This may be to understand a piece of code so you can extend it, or _debug_ existing code by finding and fixing bugs. These tasks are a lot easier if you write code with readability and debuggability in mind, and if you know how to use debugging tools. ## Objectives After this lecture, you should be able to: - Develop _readable_ code - Use a _debugger_ to understand and debug code - Isolate the _root cause_ of a bug - Develop _debuggable_ code ## What makes code readable? Take a look at [planets.py](exercises/lecture/planets.py) in the in-lecture exercise folder. Do you find it easy to read and understand? Probably not. Did you spot the fact that sorting doesn't work because the code uses a function that returns the sorted list, but does not use its return value, rather than an in-place sort? It's a lot harder to spot that bug when you have to use so much brain power just to read the code. Unfortunately, hard-to-read code doesn't only happen in exercises within course lecture notes. Consider the following snipped from the ScalaTest framework: ```scala package org.scalatest.tools object Runner { def doRunRunRunDaDoRunRun(...): Unit } ``` What does this method do? The method name isn't going to help you. It's a reference to [a song from 1963](https://en.wikipedia.org/wiki/Da_Doo_Ron_Ron). Sure, it's a funny reference, but wouldn't you rather be reading a name that told you what the method does? Worse, [the method has 21 parameters](https://github.com/scalatest/scalatest/blob/282da2aff8f439906fe5e7d9c3112c84019545e7/jvm/core/src/main/scala/org/scalatest/tools/Runner.scala#L1044-L1066). You can of course understand what the method does if you spend enough time on it, but should you have to? Let's talk about five components of code readability: naming, documentation, comments, formatting, and consistency. ### Names First, an example of _naming_ without even using code: measurement errors. If you measure the presence of something that's absent, that's a `type I error`. If you measure the absence of something that's present, that's a `type II error`. These kinds of errors happen all the time in, for instance, tests to detect viruses. However, it's easy to forget which is type `I` and which is type `II`. And even if you remember, a typo duplicating a character can completely change the meaning of a sentence. Instead, you can use `false positive` and `false negative`. These names are easier to understand, easier to remember, and more resilient to spelling mistakes. Names in code can also make the difference between code that's easy to understand and code that's hard to even mentally parse. A variable named `isUserOnline` in Java is fine... as long as it really is for an "is the user online?" boolean variable, that is. If it's an integer, it's a lot more confusing. And if you're writing Python instead, it's also a problem since Python uses underscores to separate words, a.k.a. "snake case", so it should be `is_user_online`. A variable named `can_overwrite_the_data` is quite a long name, which isn't a problem by itself, but it's redundant: of course we're overwriting "data", the name is too vague. Names are not only about variable, method, or class names. Consider the following method call: ```java split("abc", "a", true, true) ``` What does this method do? Good question. What if the call looked like this instead, with constants or enums? ```java split("abc", "a", SplitOptions.REMOVE_EMPTY_ENTRIES, CaseOptions.IGNORE_CASE) ``` This is the same method call, but we've given names instead of values, and now the meaning is clearer. These constants are only a workaround for Java's lack of named parameters, though. In Scala, and other languages like C#, you could call the method like this: ```scala split("abc", separator = "a", removeEmptyEntries = true, ignoreCase = true) ``` The code is now much more readable thanks to explicit names, without having to write extra code. A cautionary tale in good intentions with naming is _Hungarian notation_. Charles Simonyi, a Microsoft engineer from Hungary, had the good idea to start his variable names with the precise data type the variables contained, such as `xPosition` for a position on the X axis, or `cmDistance` for a distance in centimeters. This meant anyone could easily spot the mistake in a like such as `distanceTotal += speedLeft / timeLeft`, since dividing speed by time does not make a distance. This became known as "Hungarian notation", because in Simonyi's native Hungary, names are spelled with the family name first, e.g., "Simonyi Károly". Unfortunately, another group within Microsoft did not quite understand what Simonyi's goal was, and instead thought it was about the variable type. So they wrote variable names such as `cValue` for a `char` variable, `lIndex` for a `long` index, and so on, which makes the names harder to read without adding any more information than is already in the type. This became known as "Systems Hungarian", because the group was in the operating systems division, and unfortunately Systems Hungarian made its way throughout the "Win32" Windows APIs, which were the main APIs for Windows until recently. Lots of Windows APIs got hard-to-read names because of a misunderstanding! Once again, naming is not the only way to solve this issue, only one way to solve it. In the F# programming language, you can declare variables with units, such as `let distance = 30<cm>`, and the compiler will check that comparisons and computations make sense given the units. --- #### Exercise The following names all look somewhat reasonable, why are they poor? - `pickle` (in Python) - `binhex` (in Python) - `LinkedList<E>` (in Java's `java.util`) - `vector<T>` (in C++'s `std`) - `SortedList` (in C#'s `System.Collections`) <details> <summary>Answers (click to expand)</summary> <p> `pickling` is a rather odd way to refer to serializing and deserializing data as "preserving" it. `binhex` sounds like a name for some binary and hexadecimal utilities, but it's actually for a module that handles an old Mac format. A linked list and a doubly linked list are not the same thing, yet Java names the latter as if it was the former. A vector has a specific meaning in mathematics; C++'s `vector` is really a resizeable array. `SortedList` is an acceptable name for a sorted list class. But the class with that name is a sorted map! </p> </details> --- Overall, names are a tool to make code clear and succinct, as well as consistent with other code so that readers don't have to explicitly think about names. ### Documentation _Documentation_ is a tool to explain _what_ a piece of code does. Documentation is the main way developers learn about the code they use. When writing code, developers consult its documentation comments, typically within an IDE as tooltips. Documentation comments should thus succinctly describe what a class or method does, including information developers are likely to need such as whether it throws exceptions, or whether it requires its inputs to be in some specific format. ### Comments _Comments_ are a tool to _why_ a piece of code does what it does. Importantly, comments should not say _how_ a piece of code does what it does, as this information already exists in the code itself. Unfortunately, not all code is "self-documenting". Comments are a way to explain tricky code. Sometimes, code has to be written in a way that looks overly complicated or wrong because the code is working around some problem in its environment, such as a bug in a library, or a compiler that only produces fast assembly code in specific conditions. Consider the following good example of a comment, taken from an old version of the Java development kit's `libjsound`: ```c /* Workaround: 32bit app on 64bit linux gets assertion failure trying to open ports. Until the issue is fixed in ALSA (bug 4807) report no midi in devices in the configuration. */ if (jre32onlinux64) { return 0; } ``` This is a great example of an inline comment: it explains what the external problem is, what the chosen solution is, and refers to an identifier for the external problem. This way, a future developer can look up that bug in ALSA, a Linux audio system, and check if was fixed in the meantime so that the code working around the bug can be deleted. Inline comments are a way to explain code beyond what code itself can do, which is often necessary even if it ideally should not be. This explanation can be for the people who will review your code before accepting your proposed changes, or for colleagues who will read your code when working on the codebase months later. Don't forget that one of these "colleagues" is likely "future you". No matter how clear you think a piece of code is right now, future you will be grateful for comments that explain the non-obvious parts. ### Formatting Formatting code is all about making it easier to read code. You don't notice good formatting, but you do notice bad formatting, and it makes it harder to focus. Here is a real world example of bad formatting: ```c if (!update(&context, &params)) goto fail; goto fail; ``` Did you spot the problem? The code looks like the second `goto` is redundant, because it's formatted that way. But this is C. The second `goto` is actually outside of the scope of the `if`, and is thus always executed. This was a real bug that triggered [a vulnerability](https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/) in Apple products. Some languages enforce at least some formatting consistency, such as Python and F#. But as you saw with the `planets.py` exercise earlier, that does not mean it's impossible to format one's code poorly. ### Consistency Should you use `camelCase` or `snake_case` for your names? 4 or 8 spaces for indentation? Or perhaps tabs? So many questions. This is what _conventions_ are for. The entire team decides, once, what to do. Then every member of the team accepts the decisions, and benefits from a consistent code style without having to explicitly think about it. Beware of a common problem called _bikeshedding_ when deciding on conventions. The name comes from the story illustrating it: a city council meeting has two items on the agenda, the maintenance of a nuclear power plant and the construction of a bike shed. The council quickly approves the nuclear maintenance, which is very expensive, because they all agree that this maintenance is necessary to continue to provide electricity to the city. Then the council spends an hour discussing the plans for the bike shed, which is very cheap. Isn't it still too expensive? Surely the cost can be reduced a bit, a bike shed should be even cheaper. Should it be blue or red? Or perhaps gray? How many bikes does it need to contain? It's easy to spend lots of time on small decisions that ultimately don't matter much, because it's easy to focus on them. But that time should be spent on bigger decisions that are more impactful, even if they are harder to discuss. Once you have agreed on a convention, you should use tools to enforce it, not manual efforts. Command-line tools exist, such as `clang-format` for C code, as well as tools built into IDEs, which can be configured to run whenever you save a file. That way, you no longer have to think about what the team's preferences are, tools do it for you. ## How can one efficiently debug a program? Your program just got a bug report from a user: something doesn't work as expected. Now what? The presence of a bug implies that the code's behavior doesn't match the intent of the person who wrote it. The goal of _debugging_ is to find and fix the _root cause_ of the bug, i.e., the problem in the code that is the source of the bug. This is different from the _symptoms_ of the bug, in the same way that symptoms of a disease such as loss of smell are different from a root cause such as a virus. You will find the root cause by repeatedly asking "_why?_" when you see symptoms until you get to the root cause. For instance, let's say you have a problem: you arrived late to class. Why? Because you woke up late. Why? Because your alarm didn't ring. Why? Because your phone had no battery. Why? Because you forgot to plug your phone before going to sleep. Aha! That's the cause of the bug. If you had stopped at, say, "your alarm didn't ring", and tried to fix it by adding a second phone with an alarm, you would simply have two alarms that didn't ring, because you would forget to plug in the second phone as well. But now that you know you forgot to plug in your phone, you can attack the root cause, such as by putting a post-it above your bed reminding you to charge your phone. You could in theory continue asking "why?", but it stops being helpful after a few times. In this case, perhaps the "real" root cause is that you forget things often, but you cannot easily fix that. At a high level, there are three steps to debugging: reproduce the bug, isolate the root cause, and debug. Reproducing the bug means finding the conditions under which it appears: - What environment? Is it on specific operating systems? At specific times of the day? In specific system languages? - What steps need to be taken to uncover the bug? These could be as simple as "open the program, click on the 'login' button, the program crashes", or more complex, such as creating multiple users with specific properties and then performing a sequence of tasks that trigger a bug. - What's the expected outcome? That is, what do you expect to happen if there is no bug? - What's the actual outcome? This could be simply "a crash", or it could be something more complex, such as "the search results are empty even though there is one item matching the search in the database" - Can you reproduce the bug with an automated test? This makes it easier and less error-prone to check if you have fixed the bug or not. Isolating the bug means finding roughly where the bug comes from. For instance, if you disable some of your program's modules by commenting out the code that uses them, does the bug still appear? Can you find which modules are necessary to trigger the bug? You can also isolate using version control: does the bug exist in a previous commit? If so, what about an even older commit? Can you find the one commit that introduced the bug? If you can find which commit introduced the bug, and the commit is small enough, you have drastically reduced the amount of code you need to look at. Finally, once you've reproduced and isolated the bug, it's time to debug: see what happens and figure out why. You could do this with print statements: ```c printf("size: %u, capacity: %u\n", size, capacity); ``` However, print statements are not convenient. You have to write potentially a lot of statements, especially if you want to see the values within a data structure or an object. You may not even be able to see the values within an object if they are private members, at which point you need to add a method to the object just to print some of its private members. You also need to manually remove prints after you've fixed the bug. Furthermore, if you realize while executing the program that you forgot to print a specific value, using prints forces you to stop the program, add a print, and run it again, which is slow. Instead of print statements, use a tool designed for debugging: a debugger! ### Debuggers A debugger is a tool, typically built into an IDE, that lets you pause the execution of a program wherever you want, inspect what the program state is and even modify the state, and generally look at what a piece of code is actually doing without having to modify that piece of code. One remark about debuggers, and tools in general: some people think that not using a tool, and doing it the "hard" way instead, somehow makes them better engineers. This is completely wrong, it's the other way around: knowing what tools are available and using them properly is key to being a good engineer. Just like you would ignore people telling you to not take a flashlight and a bottle of water when going hiking in a cave, ignore people who tell you to not use a debugger or any other tool you think is useful. Debuggers also work for software that runs on other machines, such as a server, as long as you can launch a debugging tool there, you can run the graphical debugger on your machine to debug a program on a remote machine. There are also command-line debuggers, such as `jdb` for Java or `pdb` for Python, though these are not as convenient since you must manually input commands to, e.g., see what values variables have. The one prerequisite debuggers have is a file with _debug symbols_: the link between the source code and the compiled code. That is, when the program executes a specific line of assembly code, what line is it in the source code? What variables exist at that point, and in which CPU registers are they? This is of course not necessary for interpreted languages such as Python, for which you have the source code anyway. It is technically possible to run a debugger without debug symbols, but you then have to figure out how the low-level details map to high-level concepts yourself, which is tedious. Let's talk about five key questions you might ask yourself while debugging, and how you can answer them with a debugger. _Does the program reach this line?_ Perhaps you wonder if the bug triggers when a particular line of code executes. To answer this question, use a _breakpoint_, which you can usually do by right-clicking on a line and selecting "add a breakpoint" from the context menu. Once you have added a breakpoint, run the program in debug mode, and execution will pause once that line is reached. Debuggers typically allow more advanced breakpoints as well, such as "break only if some condition holds", or "break once every N times this line is executed". You can even use breakpoints to print things instead of pausing execution. Wait, didn't we just say prints weren't a good idea? The reason why printing breakpoints are better is that you don't need to edit the code, and thus don't need to revert those edits later, and you can change what is printed where while the program is running. _What's the value of this variable?_ You've added a breakpoint, the program ran to it and paused execution, now you want to see what's going on. In an IDE, you can typically hover your mouse over a variable in the source code to see its value while the program is paused, as well as view a list of all local variables. This includes the values within data structures such as arrays, and the private members in classes. You can also execute code to ask questions, such as `n % 12 == 0` to see if `n` is currently a multiple of 12, or `IsPrime(n)` if you have an `IsPrime` method and want to see if what it returns for `n`. _What if instead...?_ You see that a variable has a value you didn't expect, and wonder if the bug would disappear if it had a different value. Good news: you can try exactly that. Debuggers typically have some kind of "command" window where you can write lines such as `n = 0` to change the value of `n`, or `lst.add("x")` to add `"x"` to the list `lst`. _What will happen next?_ The program state looks fine, but maybe the next line is what causes the problem? "Step" commands let you execute the program step-by-step, so that you can look at the program state after executing each step to see when something goes awry. "Step into" will let you enter any method that is called, "step over" will go to the next line instead of entering a method, and "step out" will finish executing the current method. Some debuggers have additional tools, such as a "smart" step that only goes inside methods with more than a few lines. Depending on the programming language and the debugger, you might even be able to change the instruction pointer to whichever line of code you want, and edit some code on the fly without having to stop program execution. Note that you don't have to use the mouse to run the program and run step by step: debuggers typically have keyboard shortcuts, such as using F5 to run, F9 to step into, and so on, and you can usually customize those. Thus, your workflow will be pressing a key to run, looking at the program state after the breakpoint is hit, then pressing a key to step, looking at the program state, stepping again, and so on. _How did we get here?_ You put a breakpoint in a method, the program reached it and paused execution, but how did the program reach this line? The _call stack_ is there to answer this: you can see which method called you, which method called that one, and so on. Not only that, but you can view the program state at the point of that call. For instance, you can see what values were given as arguments to the method who called the method who called the method you are currently in. _What happened to cause a crash?_ Wouldn't it be nice if you could see the program state at the point at which there was a crash on a user's machine? Well, you can! The operating system can generate a _crash dump_ that contains the state of the program when it crashes, and you can load that crash dump into a debugger, along with the source code of the program and the debugging symbols, to see what the program state was. This is what happens when you click on "Report the problem to Microsoft" after your Word document crashed. Note that this only works with crashes, not with bugs such as "the behavior is not what I expect" since there is no automated way to detect such unexpected behavior. ### Debugging in practice When using a debugger to find the root cause of a bug, you will add a breakpoint, run the program until execution pauses to inspect the state, optionally make some edits to the program given your observations, and repeat the cycle until you have found the root cause. However, sometimes you cannot figure out the problem on your own, and you need help. This is perfectly normal, especially if you are debugging code written by someone else. In this case, you can ask a colleague for help, or even post on an Internet forum such as [StackOverflow](https://stackoverflow.com). Come prepared, so that you can help others help you. What are the symptoms of the bug? Do you have an easy way to reproduce the bug? What have you tried? Sometimes, you start explaining your problem to a colleague, and during your explanation a light bulb goes off in your head: there's the problem! Your colleague then stares at you, happy that you figured it out, but a bit annoyed to be interrupted. To avoid this situation, start by _rubber ducking_: explaining your problem to a rubber duck, or to any other inanimate object. Talk to the object as if it was a person, explaining what your problem is. The reason this works is that when we explain a problem to someone else, we typically explain what is actually happening, rather than what we wish was happening. If you don't understand the problem while explaining it to a duck, at least you have rehearsed how you will explain the bug, and you will be able to better explain it to a human. There is only one way to get better at debugging: practice doing it. Next time you encounter a bug, use a debugger. The first few times, you may be slower than you would be without one, but after that your productivity will skyrocket. --- #### Exercise Run the code in the [binary-tree](exercises/lecture/binary-tree) folder. First, run it. It crashes! Use a debugger to add breakpoints and inspect what happens until you figure out why, and fix the bugs. Note that the crash is not the only bug. <details> <summary>Solution (click to expand)</summary> <p> First, there is no base case to the recursive method that builds a tree, so you should add one to handle the `list.size() == 0` case. Second, the bounds for sub-lists are off: they should be `0..mid` and `mid+1..list.size()`. There is a correctness bug: the constructor uses `l` twice, when it should set `right` to `r`. This would not have happened if the code used better names! We provide a [corrected version](exercises/solutions/lecture/BinaryTree.java). </p> </details> ## What makes code debuggable? The inventor [Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage) once said about a machine of his "_On two occasions, I have been asked 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?'_ _I am not able to rightly apprehend the kind of confusion of ideas that could provoke such a question._" It should be clear that a wrong input cannot lead to a correct output. Unfortunately, often a wrong input leads to a wrong output _silently_: there is no indication that anything wrong happened. This makes it hard to find the root cause of a bug. If you notice something is wrong, is it because the previous operation did something wrong? Or because the operation 200 lines of code earlier produced garbage that then continued unnoticed until it finally caused a problem? [Margaret Hamilton](https://en.wikipedia.org/wiki/Margaret_Hamilton_\(software_engineer\)), who coined the term "software engineering" to give software legitimacy based on her experience developing software for early NASA missions, [said](https://www.youtube.com/watch?v=ZbVOF0Uk5lU) of her early work "we learned to spend more time up front [...] so that we wouldn't waste all that time debugging". We will see three methods to make code debuggable: defensive programming, logging, and debug-only code. ### Defensive programming Bugs are attacking you, and you must defend your code and data! That's the idea behind _defensive programming_: make sure that problems that happen outside of your code cannot corrupt your state or cause you to return garbage. These problems could for instance be software bugs, humans entering invalid inputs, humans deliberately trying to attack the software, or even hardware corruption. It may seem odd to worry about hardware corruption, but it happens more often than one thinks; for instance, a single bit flip can turn `microsoft.com` into `microsfmt.com`, since `o` is usually encoded as `01101101` in binary, which can flip to `01101111`, the encoding for `m`. Software that intends to talk to `microsoft.com` could thus end up receiving data from `microsfmt.com` instead, which may be unrelated, specifically set up for attacks, or [an experiment to see how much this happens](http://dinaburg.org/bitsquatting.html). Instead of silently producing garbage, code should fail as early as possible. The closest a failure is to its root cause, the easier it is to debug. The key tool to fail early is _assertions_. An assertion is a way to check whether the code actually behaves in the way the engineer who wrote it believes it should. For instance, if a piece of code finds the `index` of a `value` in an `array`, an engineer could write the following immediately after finding `index`: ```java if (array[index] != val) { throw new AssertionError(...); } ``` If this check fails, there must be a bug in the code that finds `index`. The "isolate the bug" step of debugging is already done by the assertion. What should be done if the check fails, though? Crash the program? This depends on the program. Typically, if there is a way to cut off whatever caused the problem from the rest of the program, that's a better idea. For instance, the current _request_ could fail. This could be a request made to a server, for instance, or an operation triggered by a user pressing a button. The software can then display a message stating an error occurred, enabling the user to either retry or do something else. However, some failures are so bad that it is not reasonable to continue. For instance, if the code loading the software's configuration fails an assertion, there is no point in continuing without the configuration. An assertion that must hold when calling a method is a _precondition_ of that method. For instance, an `int pickOne(int[] array)` method that returns one of the array's elements likely has as precondition "the array isn't `null` and has at least `1` element". The beginning of the method might look like this: ```java int pickOne(int[] array) { if (array == null || array.length == 0) { throw new IllegalArgumentException(...); } // ... } ``` If a piece of code calls `pickOne` with a null or empty array, the method will throw an `IllegalArgumentException`. Why bother checking this explicitly when the method would fail early anyway if the array was null or empty, since the method will dereference the array and index its contents? The type of exception thrown indicates _whose fault it is_. If you call `pickOne` and get a `NullPointerException`, it is reasonable to assume that `pickOne` has a bug, because this exception indicates the code of `pickOne` believes a given reference is non-null, since it dereferences it, yet in practice the reference is null. However, if you call `pickOne` and get an `IllegalArgumentException`, it is reasonable to assume that your code has a bug, because this exception indicates you passed an argument whose value is illegal. Thus, the type of exception helps you find where the bug is. An assertion that must hold when a method returns is a _postcondition_ of that method. In our example, the postcondition is "the returned value is some value within the array", which is exactly what you call `pickOne` to get. If `pickOne` returns a value not in the array, code that calls it will yield garbage, because the code expected `pickOne` to satisfy its contract yet this did not happen. It isn't reasonable to insert assertions every time one calls a method to check that the returned value is acceptable; instead, it's up to the method to check that it honors its postcondition. For instance, the end of `pickOne` might look like this: ```java int result = ... if (!contains(array, result)) { throw new AssertionError(...); } return result; ``` This way, if `result` was computed incorrectly, the code will fail before corrupting the rest of the program with an invalid value. Some assertions are both pre- and postconditions for the methods of an object: _object invariants_. An invariant is a condition that always hold from the outside. It may be broken during an operation, as long as this is not visible to the outside world because it is restored before the end of the operation. For instance, consider the following fields for a stack: ```java class Stack { private int[] values; private int top; // top of the stack within `values` } ``` An object invariant for this class is `-1 <= top < values.length`, i.e., either `top == -1` which means the stack is empty, or `top` points to the top value of the stack within the array. One way to check invariants is to write an `assertInvariants` method that asserts them and call it at the end of the constructor and the beginning and end of each method. All methods of the class must preserve the invariant so that they can also rely on it holding when they get called. This is one reason encapsulation is so useful: if anyone could modify `values` or `top` without going through the methods of `Stack`, there would be no way to enforce this invariant. Consider the following Java method: ```java void setWords(List<String> words) { this.words = words; } ``` It seems trivially correct, and yet, it can be used in the following way: ``` setWords(badWords); badWords.add("Bad!"); ``` Oops! Now the state of the object that holds `words` has been modified from outside of the object, which could break any invariants the object is supposed to have. To avoid this and protect one's state, _data copies_ are necessary when dealing with mutable values: ```java void setWords(List<String> words) { this.words = new ArrayList<>(words); } ``` This way, no changes can occur to the object's state without its knowledge. The same goes for reads, with `return this.words` being problematic and `return new ArrayList<>(this.words)` avoiding the problem. Even better, if possible the object could use an _immutable_ list for `words`, such as Scala's default `List[A]`. This fixes the problem without requiring data copies, which slow down the code. --- #### Exercise Check out the code in the [stack](exercises/lecture/stack) folder, which contains an `IntStack` class and a usage example. Add code to `IntStack` to catch problems early, and fix any bugs you find in the process. First, look at what the constructor should do. Once you've done that, add an invariant and use it, and a precondition for `push`. Then fix any bugs you find. <details> <summary>Solution (click to expand)</summary> <p> First, the constructor needs to throw if `maxSize < 0`, since that is invalid. Second, the stack should have the invariant `-1 <= top < values.length`, as discussed above. After adding this invariant, note that `top--` in `pop` can break the invariant since it is used unconditionally. The same goes for `top++` in `push`. These need to be changed to only modify `top` if necessary. To enable the users of `IntStack` to safely call `push`, one can expose an `isFull()` method, and use it as a precondition of `push`. We provide a [corrected version](exercises/solutions/lecture/Stack.java). </p> </details> ### Logging _What happened in production?_ If there was a crash, then you can get a crash dump and open it in a debugger. But if it's a more subtle bug where the outcome "looks wrong" to a human, how can you know what happened to produce this outcome? This is where _logging_ comes in: recording what happens during execution so that the log can be read in case something went wrong. One simple way to log is print statements: ```python print("Request: " + request) print("State: " + state) ``` This works, but is not ideal for multiple reasons. First, the developer must choose what to log at the time of writing the program. For instance, if logging every function call is considered too much for normal operation, then the log of function calls will never be recorded, even though in some cases it could be useful. Second, the developer must choose how to log at the time of writing the program. Should the log be printed to the console? Saved to a file? Both? Perhaps particular events should send an email to the developers? Third, using the same print function for every log makes it hard to see what's important and what's not so important. Instead of using a specific print function, logging frameworks provide the abstraction of a log with multiple levels of importance, such as Python's logging module: ```python logging.debug("Detail") logging.info("Information") logging.warning("Warning") logging.error("Error") logging.critical("What a Terrible Failure") ``` The number of log levels and their name changes in each logging framwork, but the point is that there are multiple ones and they do not imply anything about where the log goes. Engineers can write logging calls for everything they believe might be useful, using the appropriate log level, and decide _later_ what to log and where to log. For instance, by default, "debug" and "info" logs might not even be stored, as they are too detailed and not important enough. But if there is currently a subtle bug in production, one can enable them to see exactly what is going on, without having to restart the program. It may make sense to log errors with an email to the developers, but if there are lots of errors the developers are already aware of, they might decide to temporarily log errors to a file instead, again without having to restart the program. It is important to think about privacy when writing logging code. Logging the full contents of every request, for instance, might lead to logging plain text passwords for a "user creation" function. If this log is kept in a file, and the server is hacked, the attackers will have a nice log of every password ever set. ### Debug-only code What about defensive programming checks and logs that are too slow to reasonably enable in production? For instance, if a graph has as invariant "no node has more than 2 edges", but the graph typically has millions of nodes, what to do? This is where _debug-only_ code comes in. Programming languages, their runtimes, and frameworks typically offer ways to run code only in debug mode, such as when running automated tests. For instance, in Python, one can write an `if __debug__:` block, which will execute only when the code is not optimized. It's important to double-check what "debug" and "optimized" mean in any specific context. For instance, in Python `__debug__` is `True` by default, unless the interpreter is run with the `-O` switch, for "optimize". In Java, assertions are debug-only code but they are disabled by default, and can be enabld with the `-ea` switch. Scala has multiple levels of debug-only code that are all on by default but can be selectively disabled with the `-Xelide-below` switch. Even more important, before writing debug-only code, think hard about what is "reasonable" to enable in production given the workloads you have. Spending half a second checking an invariant is fine in a piece of code that will take seconds to run because it makes many web requests, for instance, even though half a second is a lot in CPU time. Keep in mind what [Tony Hoare](https://en.wikipedia.org/wiki/Tony_Hoare), one of the pioneers of computer science and especially programming languages and verification, once said in his ["Hints on Programming Language Design"](https://dl.acm.org/doi/abs/10.5555/63445.C1104368): "_It is absurd to make elaborate security checks on debugging runs, when no trust is put in the results,_ _and then remove them in production runs, when an erroneous result could be expensive or disastrous._ _What would we think of a sailing enthusiast who wears his life-jacket when training on dry land_ _but takes it off as soon as he goes to sea?_" ## Summary In this lecture, you learned: - How to write readable code: naming, formatting, comments, conventions - How to debug code: reproducing bugs, using a debugger - How to write debuggable code: defensive programming, logging, debug-only code You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Asynchrony You're writing an app and want it to download data and process it, so you write some code: ```java data = download(); process(data); ``` This works fine if both of these operations finish in the blink of an eye... but if they take more than that, since these operations are all your code is doing, your user interface will be frozen, and soon your users will see the dreaded "application is not responding" dialog from the operating system. Even if your app has no user interface and works in the background, consider the following: ```java firstResult = computeFirst(); secondResult = computeSecond(); compare(firstResult, secondResult); ``` If `computeFirst` and `computeSecond` are independent, the code as written is likely a waste of resources, since modern machines have multiple CPU cores and thus your app could have computed them in parallel before executing the comparison on both results. Even if you have a single CPU core, there are other resources, such as the disk: ```java for (int i = 0; i < 100; i++) { chunk = readFromDisk(); process(chunk); } ``` As written, this code will spend some of its time reading from the disk, and some of its time processing the data that was read, but never both at the same time, which is a waste of resources and time. These examples illustrate the need for _asynchronous code_. For instance, an app can start a download in the background, show a progress bar while the download is ongoing, and process the data once the download has finished. Multiple computations can be executed concurrently. A disk-heavy program can read data from the disk while it is processing data already read. ## Objectives After this lecture, you should be able to: - Understand _asynchrony_ in practice - Build async code with _futures_ - Write _tests_ for async code - _Design_ async software components ## What are async operations? Asynchronous code is all about starting an operation without waiting for it to complete. Instead, one schedules what to do after the completion. Asynchronous code is _concurrent_, and if resources are available it can also be _parallel_, though this is not required. There are many low-level primitives you could use to implement asynchrony: threads, processes, fibers, and so on. You could then use low-level interactions between those primitives, such as shared memory, locks, mutexes, and so on. You could do all of that, but low-level concurrency is _very hard_. Even experts who have spent years understanding hardware details regularly make mistakes. This gets even worse with multiple kinds of hardware that provide different guarantees, such as whether a variable write is immediately visible to other threads or not. Instead, we want a high-level goal: do stuff concurrently. An asynchronous function is similar to a normal function, except that it has two points of return: synchronously, to let you know the operation has started, and asynchronously, to let you know the operation has finished. Just like a synchronous function can fail, an asynchronous function can fail, but again at two points: synchronously, to let you know the operation cannot even start, perhaps because you gave an invalid argument, and asynchronously, to let you know the operation has failed, perhaps because there was no Internet connection even after retrying in the background. We would like our asynchronous operations to satisfy three goals: they should be composable, they should be completion-based, and they should minimize shared state. Let's see each of these three. ### Composition When baking a cake, the recipe might tell you "when the melted butter is cold _and_ the yeast has proofed, _then_ mix them to form the dough". This is a kind of composition: the recipe isn't telling you to stand in front of the melted butter and watch it cool, rather it lets you know what operations must finish for the next step and what that next step is. You are free to implement the two operations however you like; you could stand in front of the butter, or you could go do something else and come back later. Composition is recursive: once you have a dough, the next step might be "when the dough has risen _and_ the filling is cold, _then_ fill the dough". Again, this is a composition of asynchronous operations into one big operation representing making a filled dough. The two previous examples were _and_, but _or_ is also a kind of composition. The recipe might tell you "bake for 30 minutes, _or_ until golden brown". If the cake looks golden brown after 25 minutes, you take it out of the oven, and forget about the 30 minutes. One important property of composition is that errors must implicitly compose, too. If the ripe strawberries you wanted to use for the filling splash on the floor, your overall "bake a cake" operation has failed. The recipe doesn't explicitly tell you that, because it's a baking convention that if any step fails, you should stop and declare the whole operation a failure, unless you can re-do the failed operation from scratch. Maybe you have other strawberries you can use instead. ### Completion If you have a cake you'd like to bake, you could ask a baker "please let me know when you've finished baking the cake", which is _completion-based_. Alternatively, you could ask them "please let me know when the oven is free" and then bake it yourself, which is a bit lower level and gives you more control. This is _readiness-based_, and some older APIs, such as those found on Unix, were designed that way. The problem with readiness-based operations is that they lead to inefficiencies due to concurrent requests. The baker just told you the oven was ready, but unbeknownst to you, another person has put their cake in the oven before you've had time to get there. Now your "put the cake in the oven" operation will fail, and you have to ask the baker to let you know when the oven is free again, at which point the same problem could occur. ### Minimizing shared state Multiple asynchronous operations might need to read and write to the same shared state. For instance, the task of counting all elements in a large collection that satisfy some property could be parallelized by dividing the collection into chunks and processing multiple chunks in parallel. Each sub-task could then increment a global counter after every matching element it sees. However, shared state introduces an exponential explosion in the number of paths through a piece of software. There is one path in which the code of sub-task 1 accesses the shared state first, and one in which sub-task 2 accesses it first, and so on for each sub-task and for each shared state access. Even with a simple counter, one already needs to worry about atomic updates. With more complex shared state, one needs to worry about potential bugs that only happen with specific "interleavings" of sub-task executions. For instance, there may be a crash only if sub-task 3 accessed shared state first, followed by 2, followed by 3 again, followed by 1. This may only happen to a small fraction of users. Then one day, a developer speeds up the code of sub-task 3, and now the bug happens more frequently because the problematic interleaving is more common. The next day, a user gets an operating system update which slightly changes the scheduling policy of threads in the kernel. Now the bug happens all the time for this user, because the operating system happens to choose an order of execution that exposes the bug on that user's machine. Asynchronous operations must minimize shared state, for instance by computing a local result, then merging all local results into a single global result at the end. One extreme form of minimizing state is _message passing_: operations send each other messages rather than directly accessing the same state. For instance, operations handling parts of a large collection could do their work and then send their local result as a message to another "monitor" operation which is responsible for merging these results. Message passing is the standard way to communicate for operations across machines already, so it can make sense to do it even on a single machine. One interesting use of this is the [Multikernel](https://www.sigops.org/s/conferences/sosp/2009/papers/baumann-sosp09.pdf), an operating system that can run on multiple local CPUs each of a different architecture, because it uses only message passing and never shared memory, thus what each local thread runs on is irrelevant. ## How can we write maintainable async code? A simple and naïve way to write asynchronous code is with _callbacks_. Instead of returning a value, functions take an additional callback argument that is called with the value once it's ready: ```java void send(String text, Consumer<String> callback); send("hello", reply -> { System.out.println(reply); }); ``` One can call an asynchronous function within a callback, leading to nested callbacks: ```java send("hello", reply -> { send("login", reply2 -> { // ... }); }); ``` But this becomes rather messy. And we haven't even discussed errors yet, which need another callback: ```java void send( String text, Consumer<String> callback, Consumer<Exception> errorCallback ); ``` Code that uses callbacks frequently ends in "callback hell": ```java send("hello", reply -> { send("login", reply2 -> { send("join", reply3 -> { send("msg", reply4 -> { send("msg", reply5 -> { send("logout", reply6 -> { // ... }); }); }); }); }); }); ``` This code is hard to read and to maintain, because callbacks are _too_ simple and low-level. They do not provide easy ways to be composed, especially when dealing with errors as well. The resulting code is poorly structured. Just because something is simple does not mean it is good! Instead of overly-simple callbacks, modern code uses _futures_. A future is an object that represents an operation in one of three states: in progress, finished successfully, or failed. In Java, futures are represented with the `CompletableFuture<T>` class, where T is the type of the result. Since `void` is not a type, Java has the type `Void` with a capital `V` to indicate no result, thus an asynchronous operation that would return `void` if it was synchronous instead returns a `CompletableFuture<Void>`. `CompletableFuture`s can be composed with synchronous operations and with asynchronous operations using various methods. ### Composing `CompletableFuture`s The `thenAccept` method creates a future that composes the current one with a synchronous operation. If the current future fails, so does the overall future; but if it succeeds, the overall future represents applying the operation to the result. And if the operation fails, the overall future has failed: ```java CompletableFuture<String> future = // ... return future.thenAccept(System.out::println); ``` Sometimes a failure can be replaced by some kind of "backup" value, such as printing the error message if there is one instead of not printing anything. The `exceptionally` method returns a future that either returns the result of the current future if there is one, or transforms the future's exception into a result: ```java return future.exceptionally(e -> e.getMessage()) .thenAccept(System.out::println); ``` One may wish to not potentially wait forever, such as when making a network request if the server is very slow or the network connectivity is just good enough to connect but not good enough to transmit data at a reasonable rate. Implementing timeouts properly is difficult, but thankfully the Java developers provided a method to do it easily: ```java return future.orTimeout(5, TimeUnit.SECONDS) .exceptionally(e -> e.getMessage()) .thenAccept(System.out::println); ``` The returned combined future represents: - Printing the result of the original future, if it completes successfully within 5s - Printing the failure of the original future, if it fails within 5s - Printing the message from the timeout error, if the original future takes more than 5s Futures can be composed with asynchronous operations too, such as with `thenCompose`: ```java CompletableFuture<String> getMessage(); CompletableFuture<Void> log(String text); return getMessage().thenCompose(log); ``` The returned future represents first getting the message, then logging it, or failing if either of these operations fail. Composing futures in parallel and doing something with both results can be done with the `thenCombine` method: ```java CompletableFuture<String> computeFirst(); CompletableFuture<String> computeSecond(); return computeFirst().thenCombine(computeSecond(), (a, b) -> a + b); ``` The resulting future in this example represents doing both operations concurrently and returning the concatenation of their results, or failing if either future fails or if the combination operation fails. One can compose more than two futures into one that executes them all concurrently with a method such as allOf: ``` CompletableFuture<Void> uploads = ...; for (int n = 0; n < uploads.length; n++) { uploads[n] = ... } return CompletableFuture.allOf(uploads); ``` In the loop, each upload will start, and by the time the loop has ended, some of the uploads may have finished while others may still be in progress. The resulting future represents the combined operation. One can also use `anyOf` to represent the operation of waiting for any one of the futures to finish and ignoring the others. Refer to the [Javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/CompletableFuture.html) for the exact semantics of these operations on failures. _A quick warning about rate limits._ We have just seen code that allows one to easily upload a ton of data at the same time. Similar code can be written with an operation to download data, or to call some API that triggers an operation. However, in practice, many websites will rate limit users to avoid one person using too many resources. For instance, at the time of this writing, GitHub allows 5000 requests per hour. Doing too many operations in a short time may get you banned from an API, so look at the documentation of any API you're using carefully before starting hundreds of futures representing API calls. ### Creating `CompletableFuture`s One can create a future and complete it after some work in a background thread like so: ```java var future = new CompletableFuture<String>(); new Thread(() -> { // ... do some work ... future.complete("hello"); }).start(); return future; ``` Instead of `complete`, one can use `completeExceptionally` to fail the future instead, giving the exception that caused the failure as an argument instead of the result. This code forks execution into two logical threads: one that creates `future`, creates and starts the threads, and returns `future`; and one that contains the code in the `Thread` constructor. By the time `return future` executes, the future may already have been completed, or it may not. The beauty of futures is that the code that obtains the returned future doesn't have to care. Instead, it will use composition operations, which will do the right thing whether the future is already completed, still in progress, or will fail. Creating a Future representing a background operation is common enough that there is a helper method for it: ```java return CompletableFuture.supplyAsync(() -> { // ... do some work ... return "hello"; // or throw an exception to fail the Future }); ``` Sometimes one wants to create a future representing an operation that is already finished, perhaps because the result was cached. There is a method for that too: ```java return CompletableFuture.completedFuture("hello"); ``` However, creating futures is a low-level operation. Most code composes futures created by lower-level layers. For instance, a TCP/IP stack might create futures. Another reason to create futures is when adapting old asynchronous code that uses other patterns, such as callbacks. --- #### Exercise Take a look at the four methods in [`Basics.java`](exercises/lecture/src/main/java/Basics.java), and complete them one by one, based on the knowledge you've just acquired. You can run `App.java` to see if you got it right. <details> <summary>Suggested solution (click to expand)</summary> <p> - Printing today's weather is done by composing `Weather.today` with `System.out.println` using `thenAccept` - Uploading today's weather is done by composing `Weather.today` with `Server.upload` using `thenCompose` - Printing either weather is done using `acceptEither` on two individual futures, both of which use `thenApply` to prefix their results, with `System.out.println` as the composition operation - Finally, `Weather.all` should be composed with `orTimeout` and `exceptionallyCompose` to use `Weather.today` as a backup We provide a [solution example](exercises/solutions/lecture/src/main/java/Basics.java). </p> </details> --- ### Sync over async Doing the exercise above, you've noticed `App.java` uses `join()` to block until a future finishes and either return the result or throw the error represented by the future. There are other such "sync over async" operations, such as `isDone()` and `isCompletedExceptionallly()` to check a future's status. "Sync over async" operations are useful specifically to use asynchronous operations in a context that must be synchronous, typically because you are working with a framework that expects a synchronous operation. Java's `main()` method must be synchronous, for instance. JUnit also expects `@Test`s to be synchronous. This is not true of all frameworks, e.g., C# can have asynchronous main methods, and most C# testing frameworks support running asynchronous test methods. You might also need to use methods such as `isDone()` if you are implementing your own low-level infrastructure code for asynchronous functions, though that is a rare scenario. In general, everyday async functions must _not_ use `join()` or any other method that attempts to synchronously wait for or interact with an asynchronous operation. If you call any of these methods on a future outside of a top-level method such as `main` or a unit test, you are most likely doing something wrong. For instance, if in a button click handler you call `join()` on a `CompletableFuture` representing the download of a picture, you will freeze the entire app until the picture is downloaded. Instead, the button click handler should compose that future with the operation of processing the picture, and the app will continue working while the download and processing happen in the background. ### Sync errors Another form of synchrony in asynchronous operations is synchronous errors, i.e., signalling that an asynchronous operation could not even be created. Unlike asynchronous errors contained in Futures, which in Java are handled with methods such as `exceptionally(...)`, synchronous errors are handled with the good old `try { ... } catch { ... }` statement. Thus, if you call a method that could fail synchronously or asynchronously and you want to handle both cases, you must write the error handling code twice. Only use sync errors for bugs, i.e., errors that are not recoverable and indicate something has gone wrong such as an `IllegalArgumentException`: ```java CompletableFuture<Void> send(String s) { if (s == null) { // pre-condition violated, the calling code has a bug throw new IllegalArgumentException(...); } ... } ``` You will thus not have to duplicate error handling logic, because you will not handle unrecoverable errors. **Never** do something like this in Java: ```java CompletableFuture<Void> send(String s) { if (internetUnavailable) { // oh well, we already know it'll fail, we can fail synchronously...? throw new IOError(...); } ... } ``` This forces all of your callers to handle both synchronous and asynchronous exceptions. Instead, return a `CompletableFuture` that has failed already: ```java if (internetUnavailable) { return CompletableFuture.failedFuture(new IOError(...)); } ``` This enables your callers to handle that exception just like any other asynchronous failure: with future composition. Another thing you should **never** do is return a `null` future: ```java if (s.equals("")) { // nothing to do, might as well do nothing...? return null; } ``` While Java allows any value of a non-primitive type to be `null`, ideally `CompletableFuture` would disallow this entirely, as once again this forces all of your callers to explicitly handle the `null` case. Instead, return a `CompletableFuture` that is already finished: ```java if (s.equals("")) { return CompletableFuture.completedFuture(null); } ``` ### Cancellation One form of failure that is expected is _cancellation_: a future might fail because it has been explicitly canceled. Canceling futures is a common operation to avoid wasting resources. For instance, if a user has navigated away from a page which was still loading pictures, there is no point in finishing the download of these pictures, decoding them from raw bytes, and displaying them on a view that is no longer on screen. Cancellation is not only about ignoring a future's result, but actually stopping whatever operation was still ongoing. One may be tempted to use a method such as `Thread::stop()` in Java, but this method is obsolete for a good reason: forceful cancellation is dangerous. The thread could for instance be holding a lock when it is forcefully stopped, preventing any other thread from ever entering the lock. (`CompletableFuture` has a `cancel` method with a `mayInterruptIfRunning` parameter, but this parameter only exists because the method implements the more general interface `CompletionStage`; as the documentation explains, the parameter is ignored because forcefully interrupting a computation is not a good idea in general) Instead, cancellation should be _cooperative_: the operation you want to cancel must be aware that cancellation is a possibility, and provide a way to cancel at well-defined points in the operation. Some frameworks have built-in support for cancellation, but in Java you have to do it yourself. One way to do it is to pass around an `AtomicBoolean` value, which serves as a "box" to pass by reference a flag indicating whether a future should be canceled. Because this is shared state, you must be disciplined in its use: only write to it outside of the future, and only read from it inside of the future. The computation in the future should periodically check whether it should be canceled, and if so throw a cancellation exception instead of continuing: ```java for (int step = 0; step < 100; step++) { if (cancelFlag.get()) { throw new CancellationException(); } ... } ``` ### Progress If you've implemented cancellation and let your users cancel ongoing tasks, they might ask themselves "should I cancel this or not?" after a task has been running for a while. Indeed, if a task has been running for 10 minutes, one may want to cancel it if it's only 10% done, whereas if it's 97% done it's probably be better to wait. This is where _progress_ indication comes in. You can indicate progress in units that make sense for a given operation, such as "files copied", "bytes downloaded", or "emails sent". Some frameworks have built-in support for progress, but in Java you have to do it yourself. One way to do it is to pass around an `AtomicInteger` value, which serves as a "box" to pass by reference a counter indicating the progress of the operation relative to some maximum. Again, because this is shared state, you must be disciplined in its use, this time the other way around: only read from it outside of the future, and only write to it from inside of the future. The computation in the future should periodically update the progress: ```java for (int step = 0; step < 100; step++) { progress.set(step); ... } progress.set(100); ``` It is tempting to define progress in terms of time, such as "2 minutes remaining". However, in practice, the duration of most operations cannot be easily predicted. The first 10 parts of a 100-part operation might take 10 seconds, and then the 11th takes 20 seconds on its own; how long will the remaining 89 take? Nobody knows. This leads to poor estimates. One way to show something to users without committing to an actual estimate is to use an "indeterminate" progress bar, such as a bar that continuously moves from left to right. This lets users know something is happening, meaning the app has not crashed, and is typically enough if the operation is expected to be short so users won't get frustrated waiting. --- #### Exercise Take a look at the three methods in [`Advanced.java`](exercises/lecture/src/main/java/Advanced.java), and complete them one by one, based on the knowledge you've just acquired. Again, you can run `App.java` to see if you got it right. <details> <summary>Suggested solution (click to expand)</summary> <p> - `Server.uploadBatch` should be modified to support cancellation as indicated above, and then used in a way that sets the cancel flag if the operation times out using `orTimeout` - Converting `OldServer.download` can be done by creating a `CompletableFuture<String>` and passing its `complete` and `completeExceptionally` methods as callbacks - Reliable downloads can be implemented in the equivalent of a recursive function: `download` composed with `reliableDownload` if it fails, using `exceptionallyCompose` We provide a [solution example](exercises/solutions/lecture/src/main/java/Advanced.java). </p> </details> --- ### In other languages We have seen futures in Java as `CompletableFuture`, but other languages have roughly the same concept with different names such as `Promise` in JavaScript, `Task<T>` in C#, and `Future` in Rust. Importantly, operations on these types don't always have the exact same semantics, so be sure to read their documentation before using them. Some languages have built-in support for asynchronous operations. Consider the following C# code: ```csharp Task<string> GetAsync(string url); async Task WriteAsync() { var text = await GetAsync("epfl.ch"); Console.WriteLine(text); } ``` `Task<T>` is C#'s future equivalent, so `GetAsync` is an asynchronous operation that takes in a string and returns a string. `WriteAsync` is marked `async`, which means it is an asynchronous operation. When it calls `GetAsync`, it does so with the `await` operator, which is a way to compose futures while writing code that looks and feels synchronous. To be clear, `WriteAsync` is an asynchronous operation and does not block. It is equivalent to explicitly returning `GetAsync("epfl.ch")` composed with `Console.WriteLine`, C#'s equivalent of `System.out.println`. But because the language supports it, the compiler does all of the future composition, an engineer can write straightforward asynchronous code without having to explicitly reason about future composition. It is still possible to explicitly compose futures, such as with `Task.WhenAll` to compose many futures into one. Handling failures is also easier: ```csharp try { var text = await GetAsync("epfl.ch"); Console.WriteLine(text); } catch (Exception) { ... } ``` Whether `GetAsync` fails synchronously or asynchronously, the handling is in the `catch` block, and the compiler takes care of transforming this code into code that composes futures in the expected way. Similarly, Kotlin uses "coroutines", a form of lightweight threads, which can be suspended by `suspend` functions: ```kotlin suspend fun getAsync(url: String): String suspend fun writeAsync() { val content = getAsync("epfl.ch") println(content) } ``` Once again, this code is fully asynchronous: when `writeAsync` calls `getAsync`, it can get _suspended_, and the language runtime will then schedule another coroutine that is ready to run, such as one that updates the user interface with a progress bar. Kotlin can also handle both kinds of failures with a `catch` block. ### Futures as functions Now that we've seen different kinds of futures, let's take a step back and think of what a future is at a high level. There are two fundamental operations for futures: (1) turning a value, or an error, to a future; and (2) combining a future with a function handling its result into a new future. The first operation, creation, is two separate methods in Java's `CompletableFuture`: `completedFuture` and `failedFuture`. The second operation, transformation, is the `thenCompose` method in Java, which takes a future and a function from the result to another future and returns the aggregate future. You may have already seen this pattern before. Consider Java's `Optional<T>`. One can create a full or empty optional with the `of` and `empty` methods, and transform it with the `flatMap` method. In the general case, there are two operations on a "value of T" type: create a `Value<T>` from a `T`, and map a `Value<T>` with a `T -> Value<U>` function to a `Value<U>`. Mathematically-inclined folks use different names for these. "Create" is called "Return", "Map" is called "Bind", and the type is called a _monad_. What's the use of knowing about monads? You can think of monads as a kind of design pattern, a "shape" for abstractions. If you need to represent some kind of "box" that can contain values, such as an optional, a future, or a lists, you already know many useful methods you should provide: the ones you can find on optionals, futures, and lists. Consider the following example from the exercises: ```java return Weather.today() .thenApply(w -> "Today: " + w) .acceptEither( Weather.yesterday() .thenApply(w->"Yesterday: " + w), System.out::println ); ``` You know this code operates on futures because you've worked with the codebase and you know what `Weather.today()` and `Weather.yesterday()` return. But what if this was a different codebase, one where these methods return optionals instead? The code still makes sense: if there is a weather for today, transform it and print it, otherwise get the weather for yesterday, transform it and print it. Or maybe they return lists? Transform all elements of today's prediction, and if there are none, use the elements of yesterday's predictions instead, transformed; then print all these elements. ## How should we test async code? Consider the following method: ```java void printWeather() { getString(...) .thenApply(parseWeather) .thenAccept(System.out::println); } ``` How would you test it? The problem is that immediately after calling the method, the `getString` future may not have finished yet, so one cannot test its side effect yet. It might even never finish if there is an infinite loop in the code, or if it expects a response from a server that is down. One commonly used option is to sleep via, e.g., `Thread.sleep`, and then assume that the operation must have finished. **Never, ever, ever, ever sleep in tests for async code**. It slows tests down immensely since one must sleep the whole duration regardless of how long the operation actually takes, it is brittle since a future version of the code may be slower, and most importantly it's unreliable since the code could sometimes take more time due to factors out of your control, such as continuous integration having fewer resources because many pull requests are open and being tested. The fundamental problem with the method above is its return value, or rather the lack of a return value. Tests cannot access the future, they cannot even name it, because the method does not expose it. To be testable, the method must be refactored to expose the future: ```java CompletableFuture<Void> printWeather() { return getString(...) .thenApply(parseWeather) .thenAccept(System.out::println); } ``` It is now possible to test the method using the future it returns. One option to do so is this: ```java printWeather().thenApply(r -> { // ... test? ... }); ``` However, this is a bad idea because the lambda will not run if the future fails or if it never finishes, so the test will pass even though the future has not succeeded. In fact, the test does not even wait for the future to finish, so the test may pass even if the result is wrong because the lambda will execute too late! To avoid these problems, one could write this instead: ```java printAnswer().join(); // ... test ... ``` But this leaves one problem: if the code is buggy and the future never completes, `join()` will block forever and the tests will never complete. To avoid this problem, one can use the timeout method we saw earlier: ```java printWeather() .orTimeout(5, TimeUnit.SECONDS) .join(); // ... test ... ``` There is of course still the issue unrelated to asynchrony that the method has an implicit dependency on the standard output stream, which makes testing difficult. You can remove this dependency by returning the `CompletableFuture<String>` directly instead of printing it, which makes tests much simpler: ```java String weather = getWeather() .orTimeout(5, TimeUnit.SECONDS) .join(); // ... test weather ... ``` Exposing the underlying future is the ideal way to test asynchronous operations. However, this is not always feasible. Consider an app for which we want to test a button click "end-to-end", i.e., by making a fake button click and testing the resulting changes in the user interface. The button click handler must typically have a specific interface, including a `void` return type: ```java @Override void onClick(View v) { ... } ``` One cannot return the future here, since the `void` return type is required to comply with the button click handler interface. Instead, one can add an explicit callback for tests: ```java @Override void onClick(View v) { // ... callback.run(); } public void setCallback(...) { ... } ``` Tests can then set a callback and proceed as usual: ```java setCallback(() -> { // ... can we test here? }); // ... click the button ... ``` However, this now raises another problem: how to properly test callback-based methods? One way would be to use low-level classes such as latches or barriers to wait for the callback to fire. But this is a reimplementation of the low-level code the authors of `CompletableFuture` have already written for us, so we should be reusing that instead! ```java var future = new CompletableFuture<Void>(); setCallback(() -> future.complete(null)); // ... click the button ... future.orTimeout(5, TimeUnit.SECONDS) .join(); ``` We have reduced the problem of testing callbacks to a known one, testing futures, which can then be handled as usual. --- #### Exercise Take a look at the three tests in [`WeatherTests.java`](exercises/lecture/src/test/java/WeatherTests.java), and complete them one by one, based on the knowledge you've just acquired. <details> <summary>Suggested solution (click to expand)</summary> <p> - As we did above, call `orTimeout(...)` then `join()` on `Weather.today()`, then assert that its result is `"Sunny"` - Create a `CompletableFuture<Void>`, call its `complete` method in the callback of `WeatherView`, then wait for it with a timeout after executing `WeatherView.clickButton()`, and test the value of `WeatherView.weather()` - There are multiple ways to do the last exercise; one way is to return the combination of the two futures with `allOf` in `printWeather`, and replace `System.out::println` with a `Consumer<String>` parameter, then test it with a consumer that adds values to a string; another would be a more thorough refactoring of `printWeather` that directly returns a `CompletableFuture<List<String>>` We provide a [solution example](exercises/solutions/lecture/src/test/java/WeatherTests.java). </p> </details> --- ## How does asynchrony interact with software design? Which operations should be sync and which should be async, and why? This is a question you will encounter over and over again when engineering software. One naïve option is to make everything asynchronous. Even `1 + 1` could be `addAsync(1, 1)`! This is clearly going too far. It's important to remember that _asynchrony is viral_: if a method is async, then the methods that call it must also be async, though it can itself call sync methods. A sync method that calls an async method is poor design outside of the very edges of your system, typically tests and the main method, because it will need to block until the async method is done, which can introduce all kinds of issues such as UI freezes or deadlocks. This also applies to inheritance: if a method might be implemented in an asynchronous way, but also has other synchronous implementations, it must be async. For instance, while fetching the picture for an album in a music player may be done from a local cache in a synchronous way, it will also sometimes be done by downloading the image from the Internet. Thus, you should make operations async if they are expected to be implemented in an asynchronous way, typically I/O operations. One policy example is the one in the [Windows Runtime APIs](https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/concurrency#asynchronous-operations-and-windows-runtime-async-functions), which Microsoft introduced with Windows 8. Any operation that has the potential to take more than 50 milliseconds to complete returns a future instead of a synchronous result. 50ms may not be the optimal threshold for everything, but it is a reasonable and clear position to take that enables engineers to decide whether any given operation should be asynchronous. Remember the "YAGNI" principle: "_You Aren't Gonna Need It". Don't make operations async because they might perhaps one day possibly maybe need to be async. Only do so if there is a clear reason to. Think of how painful, or painless, it would be to change from sync to async if you need it later. One important principle is to be consistent. Perhaps you are using an OS that gives you asynchronous primitives for reading and writing to files, but only a synchronous primitive to delete it. You could expose an interface like this: ```java class File { CompletableFuture<String> read(); CompletableFuture<Void> write(String text); void delete(); } ``` However, this is inconsistent and surprising to developers using the interface. Instead, make everything async, even if deletion has to be implemented by returning an already-completed future after synchronously deleting the file: ```java class File { CompletableFuture<String> read(); CompletableFuture<Void> write(String text); CompletableFuture<Void> delete(); } ``` This offers a predictable and clear experience to developers using the interface. What if you need to asynchronously return a sequence of results? For instance, what should the return type of a `downloadImagesAsync` method be? It could be `CompletableFuture<List<Image>>`, if you want to batch the results. Or it could be `List<CompletableFuture<Image>>`, if you want to parallelize the downloads. But if you'd like to return "a sequence of asynchronous operations", what should you return? Enter "reactive" programming, in which you react to events such as downloads, clicks, or requests, each of which is an asynchronous event. For instance, if you have a "flow" of requests, you could `map` it to a flow of users and their data, then `filter` it to remove requests from users without the proper access right, and so on. In other words, it's a monad! Thus, you already mostly know what operations exist and how to use it. Check out [ReactiveX.io](https://reactivex.io) if you're interested, with libraries such as [RxJava](https://github.com/ReactiveX/RxJava). ## Summary In this lecture, you learned: - Asynchrony: what it is, how to use it, and when to use it - Maintainable async code by creating and combining futures - Testable async code with reliable and useful tests You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Infrastructure > **Prerequisites**: Before following this lecture, you should: > - Install Git. On Windows, use [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) as Git is designed mostly for Linux. > On macOS, see [the git documentation](https://git-scm.com/download/mac). On Linux, Git may already be installed, or use your distribution's package manager. > If you have successfully installed Git, running `git --version` in the command line should show a version number. > - Create a GitHub account (you do not have to use an existing GitHub account, you can create one just for this course if you wish) > - Set up an SSH key for GitHub by following [their documentation](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account) > - Tell Git who you are by running `git config --global user.name 'your_name'` with your name and `git config --global user.email 'your_email'` with the e-mail you used for GitHub > - Choose an editor Git will open to write a summary of your changes with `git config --global core.editor 'your_editor'`, since Git defaults to `vi` which is hard to use for newcomers. > On Windows with WSL you can use `notepad.exe`, which will open Windows's Notepad. > On macOS you can use `open -e -W -n` which will open a new TextEdit window. > On Linux you can use your distribution's built-in graphical text editor, or `nano`. > > If you use Windows with WSL, note that running `explorer.exe .` from the Linux command line will open Windows's Explorer in the folder your command-line is, which is convenient. > > Optionally, you may want to set the Git config setting `core.autocrlf` to `true` on Windows and `input` on Linux and macOS, > so that Git converts between Unix-style line endings (`\n`) and Windows-style line separators (`\r\n`) automatically. Where do you store your code, and how do you make changes to it? If you're writing software on your own, this is not a problem, as you can use your own machine and change whichever files you want whenever you want. But if you're working with someone else, it starts being problematic. You could use an online cloud service where you store files, and coordinate who changes which file and when. You could email each other changes to sets of files. But this does not work so well when you have more people, and it is completely unusable when you have tens or hundreds of people working on the same codebase. This is where infrastructure comes in. ## Objectives - Contrast old and new _version control_ systems - Organize your code with the _Git_ version control system - Write useful descriptions of code changes - Avoid mistakes with _continuous integration_ ## What is version control? Before we talk about how to manage your code using a version control system, we must define some terms. A _repository_ is a location in which you store a codebase, such as a folder on a remote server. When you make a set of changes to a repository, you are _pushing_ changes. When you retrieve the changes that others have made from the repository, you are _pulling_ changes. A set of changes is called a _commit_. Commits have four main components: who, what, when, and why. "Who" is the author of the commit, the person who made the changes. "What" is the contents of the commit, the changes themselves. "When" is the date and time at which the commit was made. This can be earlier than when the commit was actually pushed to a repository. "Why" is a message associated with the commit that explains why the changes were made, such as detailing why there was a bug and why the new code fixes the bug. The "why" is particularly important because you will often have to look at old changes later and understand why they were made. Sometimes, a commit causes problems. Perhaps a commit that was supposed to improve performance also introduces a bug. Version control systems allow you to _revert_ this commit, which creates a new commit whose contents are the reverse of the original one. That is, if the original commit replaced "X" by "Y", then the revert commit replaces "Y" with "X". Importantly, the original commit is not lost or destroyed, instead a new revert commit is created. Commits are put together in a _history_ of changes. Initially, a repository is empty. Then someone adds some content in a commit, then more content in another commit, and so on. The history of a repository thus contains all the changes necessary to go from nothing to the current state. Some of these changes could be going back and forth, such as revert commits, or commits that replace code that some previous commit added. At any time, any developer with access to the repository can look at the entire history to see who made what changes when and why. _1st generation_ version control systems were essentially a layer of automation on manual versioning. As we mentioned earlier, if you are developing with someone else, you might put your files somewhere and coordinate who is changing what and when. A 1st generation system helps you do that with fewer mistakes, but still fundamentally uses the same model. With 1st generation version control, if Alice wants to work on file A, she "checks out" the file. At that point, the file is locked: Alice can change it, but nobody else can. If Bob wants to also check out file A, the system will reject his attempt. Bob can, however, check out file B if nobody else is using it. Once Alice is done with her work, she creates a commit with her changes, and releases the lock. At that point, Bob can check out file A and make his changes. 1st generation version control systems thus act as locks at the granularity of files. They prevent developers from making parallel changes to the same file, which prevents some mistakes but isn't very convenient. For instance, Alice might want to modify function X in file A, while Bob wants to modify function Y in file A. These changes won't conflict, but they still cannot do them in parallel, because locks in 1st generation version control are at the file granularity. Developers moved on from 1st generation systems because they wanted more control over _conflicts_. When two developers want to work on the same file at the same time, they should be able to, as long as they can then _merge_ their changes into one unified version. Merging changes isn't always possible automatically. If two developers changed the same function in different ways, for instance, they probably need to have a chat to decide which changes should be kept. Another feature that makes sense if a system can handle conflicts and merges is _branches_. Sometimes, developers want to work on multiple copies of the codebase in parallel. For instance, you might be working on some changes that improve performance, when a customer comes in with a bug report. You could fix the bug and commit it with your performance changes, but the resulting commit is not convenient. If you later need to revert the performance changes, for instance, you would also revert the bugfix because it's in the same commit. Instead, you create a branch for your performance changes, then you switch to a branch for the bugfix, and you can work on both in parallel. When your bugfix is ready, you can _merge_ it into the "main" branch of the repository, and the same goes for the performance changes. One common use of branches is for versions: you can release version 1.0 of your software, for instance, and create a branch representing the state of the repository for that version. You can then work on the future version 2.0 in the "main" branch. If a customer reports a bug in version 1.0, you can switch to the branch for version 1.0, fix the bug, release the fix, then go back to working on version 2.0. Your changes for version 1.0 did not affect your main branch, because you made them in another branch. The typical workflow with branches for modern software is that you will create a branch starting from the main branch of the repository, then add some commits to the branch to fix a bug or add a feature or perform whatever task the branch is for, and then ask a colleague to review it. If the colleague asks for some changes, such as adding more code comments, you can add a commit to the branch with these changes. Once your colleague is happy, you can merge the branch's commits into the main branch. Then you can create another branch to work on something else, and so on. Your colleagues are themselves also working on their own branches. This workflow means everyone can push whatever commits they want on their branch without conflicting with others, even if their work isn't quite finished yet. Often it is a good idea to _squash_ a branch's commits into a single commit and merge the resulting commit into the main branch. This combines all of the branch's changes into one clean commit in the history of the main branch, rather than having a bunch of commits that do a few small changes each but make no sense without each other. In the case of branches that represent versions, one sometimes needs to apply the same changes to multiple branches. For instance, while developing version 2.0 in the main branch, you may find a bug, and realize that the bug also exists in version 1.0. You can make a commit fixing the bug in version 2.0, and then _cherry pick_ the commit into the branch for version 1.0. As long as the change does not conflict with other changes made in the version 1.0 branch, the version control system can copy your bugfix commit into a commit for another branch. _2nd generation_ version control systems were all about enabling developers to handle conflicts. Alice can work on file A without the need to lock it, and Bob can also work on file A at the same time. If Alice pushes her changes first, the system will accept them, and when Bob then wants to apply his changes, two things can happen. One possibility is that the changes can be merged automatically, for instance because the changes are on two different parts of the file. The other possibility is that the changes conflict and must be merged manually. Bob then has to choose what to do, perhaps by asking Alice, and produce one "merged" version of the file that can be pushed. The main remaining disadvantage of 2nd generation version control is its centralization. There is one repository that developers work with, hosted on one server. Committing changes requires an Internet connection to that server. This is a problem if the server is down, or a developer is in a place without access to the Internet, or any other issue that prevents a developer from reaching the server. _3rd generation_ version control systems are all about decentralization. Every machine has its own repository. It is not a "backup" or a "replica" of some "main" repository, but just another clone of the repository. Developers can make commits locally on their own repository, then push these commits to other clones of the repository, such as on a server. Developers can also have multiple branches locally, with different commits in each, and push some or all of these branches to other clones of the repository. This all works as long as the repositories have compatible histories. That is, one cannot push a change to a repository that isn't based on the same history as one's local repository. In practice, teams typically agree on one "main" repository that they will all push commits to, and work locally on their clone of that repository. While from the version control system's point of view all repository clones are equal, it is convenient for developers to agree on one place where everyone puts their changes. The main version control system in use today is _Git_. Git was invented by Linus Torvalds, who invented Linux, because he was tired of the problems with the previous version control system he used for Linux. There are also other 3rd generation version control systems such as Mercurial and Bazaar, but Git is by far the most used. Many developers use public websites to host the "main" repository clone of their projects. The most famous these days is GitHub, which uses Git but isn't technically related to it. GitHub not only stores a repository clone, but can also host a list of "issues" for the repository, such as bugs and feature requests, as well as other data such as a wiki for documentation. There are also other websites with similar features such as GitLab and BitBucket, though they are not as popular. An example of a project developed on GitHub is [the .NET Runtime](https://github.com/dotnet/runtime), which is developed mainly by Microsoft employees and entirely using GitHub. Conversations about bugs, feature requests, and code reviews happen in the open, on GitHub. ## How does one use Git? Now that we've seen the theory, let's do some practice! You will create a repository, make some changes, and publish it online. Then we'll see how to contribute to an existing online repository. Git has a few basic everyday commands that we will see now, and many advanced commands we won't discuss here. You can always look up commands on the Internet, both basic and advanced ones. You will eventually remember the basics after using them enough, but there is no shame at all in looking up what to do. We will use Git on the command line for this tutorial, since it works the same everywhere. However, for everyday tasks you may prefer using graphical user interfaces such as [GitKraken](https://www.gitkraken.com/), [GitHub Desktop](https://desktop.github.com/), or the Git support in your favorite IDE. Start by creating a folder and _initializing_ a repository in that folder: ```sh ~$ mkdir example ~$ cd example ~/example$ git init ``` Git will tell you that you have initialized an empty Git repository in `~/example/.git/`. This `.git/` folder is a special folder Git uses to store metadata. It is not part of the repository itself, even though it is in the repository folder. Let's create a file: ```sh $ echo 'Hello' > hello.txt" ``` We can now ask Git what it thinks is going on: ```sh $ git status ... Untracked files: hello.txt ``` Git tells us that it sees we added `hello.txt`, but this file isn't tracked yet. That is, Git won't include it in a commit unless we explicitly ask for it. So let's do exactly that: ```sh $ git add -A ``` This command asks Git to include all current changes in the repository for the next commit. If we make more changes, we will have to ask for these new changes to be tracked as well. But for now, let's ask Git what it thinks: ```sh $ git status ... Changes to be committed: new file: hello.txt ``` Now Git knows we want to commit that file. So let's commit it: ```sh $ git commit ``` This will open a text editor for you to type the commit message in. As we saw earlier, the commit message should be a description of _why_ the changes were made. Often the very first commit in a repository sets up the basic file structure as an initial commit, so you could write `Initial commit setting up the file` or something similar. You will then see output like this: ```sh [...] Initial commit. 1 file changed, 1 insertion(+) create mode 100644 hello.txt ``` Git repeats the commit message you put, here `Initial commit.`, and then tells you what changes happened. Don't worry about that `mode 100644`, it's more of an implementation detail. Let's now make a change by adding one line: ```sh $ echo 'Goodbye' >> hello.txt ``` We can ask git for the details of what changes we did: ```sh $ git diff ``` This will show a detailed list of the differences between the state of the repository as of the latest commit and the current state of the repository, i.e., we added one line saying `Goodbye`. Let's track the changes we just made: ```sh $ git add -A ``` What happens if we ask for a list of differences again? ```sh $ git diff ``` ...Nothing! Why? Because `diff` by default shows differences that are not tracked for the next commit. There are three states for changes to files in Git: modified, staged, and committed. By default changes are modified, then with `git add -A` they are staged, and with `git commit` they are committed. We have been using `-A` with `git add` to mean "all changes", but we could in fact add only specific changes, such as specific files or even parts of files. In order to see staged changes, we have to ask for them: ```sh $ git diff --staged ``` We can now commit our changes. Because this is a small commit that does not need much explanation, we can use `-m` to write the commit message directly in the command: ```sh $ git commit -m 'Say goodbye' ``` Let's now try out branches, by creating a branch and switching to it: ```sh git switch -c feature/today ``` The slash in the branch name is nothing special to Git, it's only a common naming convention to distinguish the purpose of different branches. For instance, you might have branches named `feature/delete-favorites` or `bugfix/long-user-names`. But you could also name your branch `delete-favorites` or `bugfix/long/user/names` if you'd like, as long as everybody using the repository agrees on a convention for names. Now make a change to the single line in the file, such as changing "Hello" to "Hello today". Then, track the changes and commit them: ```sh $ git add -A && git commit -m 'Add time' ``` You will notice that Git tells you there is `1 insertion(+), 1 deletion (-)`. This is a bit odd, we changed one line, why are there two changes? The reason is that Git tracks changes at the granularity of lines. When you edit a line, Git sees this as "you deleted the line that was there, and you added a new line". The fact that the "deleted" and the "added" lines are similar is not relevant. If you've already used Git before, you may have heard of the `-a` to `git commit`, which could replace the explicit `git add -A` in our case. The reason we aren't using it here, and the reason why you should be careful if using it, is that `-a` only adds changes to existing files. It does not add changes to new files or deleted files. This makes it very easy to accidentally forget to include some new or deleted files in the commit, and to then have to make another commit with just these files, which is annoying. Anyway, we've made a commit on our `feature/today` branch. In case we want to make sure that we are indeed on this branch, we can ask Git: ```sh $ git branch ``` This will output a list of branches, with an asterisk `*` next to the one we are on. Let's now switch to our main branch. Depending on your Git version, this branch might have different names, so look at the output of the previous command and use the right one, such as `master` or `main`: ```sh $ git switch main ``` To see what happens when two commits conflict, let's make a change to our `hello.txt` file that conflicts with the other branch we just made. For instance, replace "Hello" with "Hello everyone". Then, track the change and commit it as before. At this point, we have two branches, our main branch and `feature/today`, that have diverged: they both have one commit that is not in the other. Let's ask Git to merge the branches, that is, add the commits from the branch we specify into the current branch: ```sh $ git merge feature/today ``` Git will optimistically start with `Auto-merging hello.txt`, but this will soon fail with a `Merge conflict in hello.txt`. Git will ask us to fix conflicts and commit the result manually. What does `hello.txt` look like now? ```sh $ cat hello.txt <<<<<<< HEAD Hello everyone ======= Hello today >>>>>>> feature/today Goodbye ``` Let's take a moment to understand this. The last line hasn't changed, because it's not a part of the conflict. The first line has been expanded to include both versions: between the `<<<` and `===` is the version in `HEAD`, that is, the "head", the latest commit, in the current branch. Indeed, on our main branch the first line was `Hello everyone`. Between the `===` and the `>>>` is the version in `feature/today`. What we need to do is manually merge the changes, i.e., edit the file to replace the conflict including the `<<<`, `===`, and `>>>` lines with the merged changes we want. For instance, we could end up with a file containing the following: ```sh $ cat hello.txt Hello everyone today Goodbye ``` This is one way to merge the file. We could also have chosen `Hello today everyone`, or perhaps we would rather discard one of the two changes and keep `Hello everyone` or `Hello today`. Or perhaps we want yet another change, we could have `Hello hello` instead. Git does not care, it only wants us to decide what the merged version should be. Once we have made our merge changes, we should add the changes and commit as before: ```sh $ git add -A && git commit -m 'Merge' ``` Great. Wait, no, actually, not so great. That's a pretty terrible commit message. It's way too short and not descriptive. Thankfully, _because we have not published our changes to another clone of the repository yet_, we can make changes to our commits! This is just like how a falling tree makes no sound if there's no one around to hear it. If nobody can tell, it did not happen. We can change our commit now, and when we push it to another clone the clone will only see our modified commit. However, if we had already pushed our commit to a clone, our commit would be visible, so we could not change it any more as the clone would get confused by a changing commit since commits are supposed to be immutable. To change our commit, which again should only be done if the commit hasn't been pushed yet, we "amend" it: ```sh $ git commit --amend -m 'Merge the feature/today branch' ``` We have only modified the commit message here, but we could also modify the commit contents, i.e., the changes themselves. Sometimes we make changes we don't actually want, for instance temporary changes while we debug some code. Let's make a "bad" change: ```sh $ echo 'asdf' >> hello.txt ``` We can restore the file to its state as of the latest commit to cancel this change: ```sh $ git restore hello.txt ``` Done! Our temporary changes have disappeared. You can also use `.` to restore all files in the current directory, or any other path. However, keep in mind that "disappeared" really means disappeared. It's as if we never changed the file, as the file is now in the state it was after the latest commit. Do not use `git restore` unless you actually want to lose your changes. Sometimes we accidentally add files we don't want. Perhaps a script went haywire, or perhaps we copied some files by accident. Let's make a "bad" new file: ```sh $ echo 'asdf' > mistake.txt ``` We can ask Git to "clean" the repository, which means removing all untracked files and directories. However, because this will delete files, we'd better first run it in "dry run" mode using `-n`: ```sh $ git clean -fdn ``` This will show a list of files that _would_ be deleted if we didn't include `-n`. If we're okay with the proposed deletion, let's do it: ```sh $ git clean -fd ``` Now our `mistake.txt` is gone. Finally, before we move on to GitHub, one more thing: keep in mind that Git only tracks _files_, not _folders_. Git will only keep track of folders if they are a part of a file's path. So if we create a folder and ask Git what it sees, it will tell us there is nothing, because the folder is empty: ```sh $ mkdir folder $ git status ``` If you need to include an "empty" folder in a Git repository for some reason, you should add some empty file in it so that Git can track the folder as part of that file. Let's now publish our repository. Go to [GitHub](https://github.com) and create a repository using the "New" button on the home page. You can make it public or private, but do not create files such as "read me" files or anything else, just an empty repository. Then, follow the GitHub instructions for an existing repository from the command line. Copy and paste the commands GitHub gives you. These commands will add the newly-created GitHub repository as a "remote" to your local repository, which is to say, another clone of the repository that Git knows about. Since it will be the only remote, it will also be the default one. The default remote is traditionally named `origin`. The commands GitHub provide will also push your commits to this remote. Once you've executed the commands, you can refresh the page on your GitHub repository and see your files. Now make a change to your `hello.txt`, track the change, and commit it. You can then sync the commit with the GitHub repository clone: ```sh $ git push ``` You can also get commits from GitHub: ```sh $ git pull ``` Pulling will do nothing in this case, since nobody else is using the repository. In a real-world scenarios, other developers would also have a clone of the repository on their machine and use GitHub as their default remote. They would push their changes, and you would pull them. Importantly, `git pull` only synchronizes the current branch. If you would like to sync commits from another branch, you must `git switch` to that branch first. Similarly, `git push` only synchronizes the current branch, and if you create a new branch you must tell it where to push with `-u` by passing both the remote name and the branch name: ```sh $ git switch -c example $ git push -u origin example ``` Publishing your repository online is great, but sometimes there are files you don't want to publish. For instance, the binary files compiled from source code in the repository probably should not be in the repository, since they can be recreated easily and would only take up space. Files that contain sensitive data such as passwords should also not be in the repository, especially if it's public. Let's simulate a sensitive file: ```sh $ echo '1234' > password.txt ``` We can tell Git to pretend this file doesn't exist by adding a line with its name to a special file called `.gitignore`: ```sh $ echo 'password.txt' >> .gitignore ``` Now, if you try `git status`, it will tell you that `.gitignore` was created but ignore `password.txt` since you told Git to ignore it. You can also ignore entire directories. Note that this only works for files that haven't been committed to the repository yet. If you had already made a commit in which `password.txt` exists, adding its name to `.gitignore` will only ignore future changes, not past ones. If you accidentally push to a public repository a commit with a file that contains a password, you should assume that the password is compromised and immediately change it. There are bots that scan GitHub looking for passwords that have been accidentally committed, and they will find your password if you leave it out there, even for a few seconds. Now that you have seen the basics of Git, time to contribute to an existing project! You will do this through a _pull request_, which is a request that the maintainers of an existing project pull your changes into their project. This is a GitHub concept, as from Git's perspective it's merely syncing changes between clones of a repository. Go to <https://github.com/sweng-example/hello> and click on the "Fork" button. A _fork_ is a clone of the repository under your own GitHub username, which you need here because you do not have write access to `sweng-example/hello` so you cannot push changes to it. Instead, you will push changes to your fork, to which you have write access, and then ask the maintainers of `sweng-example/hello` to accept the change. You can create branches within a fork as well, as a fork is just another clone of the repository. Typically, if you are a collaborator of a project, you will use a branch in the project's main repository, while if you are an outsider wanting to propose a change, you will create a fork first. Now that you have a forked version of the project on GitHub, click on the "Code" button and copy the SSH URL, which should start with `git@github.com:`. Then, ask Git to make a local clone of your fork, though you should go back to your home directory first, since creating a repository within a repository causes issues: ```sh $ cd ~ $ git clone git@github.com:... ``` Git will clone your fork locally, at which point you can make a change, commit, and push to your fork. Once that's done, if you go to your fork on GitHub, there should be a banner above the code telling you that the branch in your fork is 1 commit ahead of the main branch in the original repository. Click on the "Contribute" button and the "Open pull request" button that shows up, then confirm that you want to open a pull request, and write a description for it. Congratulations, you've made your first contribution to an open source project! The best way to get used to Git is to use it a lot. Use Git even for your own projects, even if you do not plan on using branches. You can use private repositories on GitHub as backups, so that even if your laptop crashes you will not lose your code. There are many advanced features in Git that can be useful in some cases, such as `bisect`, `blame`, `cherry-pick`, `stash`, and many more. Read the [official documentation](https://git-scm.com/docs/) or find online advanced tutorials for more if you're curious! ## How does one write good commit messages? Imagine being an archaeologist and having to figure out what happened in the past purely based on some half-erased drawings, some fossils, and some tracks. You will eventually figure out something that could've happened to cause all this, but it will take time and you won't know if your guess is correct. Wouldn't it be nice if there was instead a journal that someone made, describing everything important they did and why they did it? This is what commit messages are for: keep track of what you do and why you did it, so that other people will know it even after you're done. Commit messages are useful to people who will review your code before approving it for merging in the main branch, and to your colleagues who investigate bugs months after the code was written. Your colleagues in this context include "future you". No matter how "obvious" or "clear" the changes seems to you when you make them, a few months later you won't remember why you did something the way you did it. The typical format of a commit message is a one-line summary followed by a blank line and then as many lines as needed for details. For instance, this is a good commit message: ``` Fix adding favorites on small phones The favorites screen had too many buttons stacked on the same row. On phones with small screens, there wasn't enough space to show them all, and the "add" button was out of view. This change adds logic to use multiple rows of buttons if necessary. ``` As we saw earlier, "squashing" commits is an option when merging your code into the main branch, so not all commits on a branch need to have such detailed messages. Sometimes a commit is just "Fix a typo" or "Add a comment per the review feedback". These commits aren't important to understand the changes, so their messages will be dropped once the branch is squashed into a single commit while being merged. The one-line summary is useful to get an overview of the history without having to see every detail. You can see it on online repositories such as GitHub, but also locally. Git has a `log` command to show the history, and `git log --oneline` will show only the one-line summary of each commit. A good summary should be short and in the imperative mood. For instance: - "Fix bug #145" - *Add an HD version of the wallpaper" - "Support Unicode 14.0" The details should describe _what_ the changes do and _why_ you did them, but not _how_. There is no point in describing how because the commit message is associated with the commit contents, and those already describe how you changed the code. ## How can we avoid merging buggy code? Merging buggy code to the main branch of a repository is an annoyance for all contributors to that repository. They will have to fix the code before doing the work they actually want to do, and they may not all fix it in the same way, leading to conflicts. Ideally, we would only accept pull requests if the resulting code compiles, is "clean" according to the team's standards, and has been tested. Different teams have different ideas of what "clean" code is, as well as what "testing" means since it could be manual, automated, performed on one or multiple machines, and so on. When working in an IDE, there will typically be menu options to analyze the code for cleanliness, to compile the code, to run the code, and to run automated tests if the developers wrote some. However, not everyone uses the same IDE, which means they may have different definitions of what these operations mean. The main issue with using operations in an IDE to check properties about the code is that humans make mistakes. On a large enough projects, human mistakes happen all the time. For instance, it's unreasonable to expect hundreds of developers to never forget even once to check that the code compiles and runs. Checking for basic mistakes also a poor use of people's time. Reviewing code should be about the logic of the code, not whether every line is syntactically valid, that's the compiler's job. We would instead like to _automate_ the steps we need to check code. This is done using a _build system_, such as CMake for C++, MSBuild for C#, or Gradle for Java. There are many build systems, some of which support multiple languages, but they all fundamentally provide the same feature: build automation. A build system can invoke the compiler on the right files with the right flags to compile the code, invoke the resulting binary to run the code, and even perform more complex operations such as downloading dependencies based on their name if they have not been downloaded already. Build systems are configured with code. They typically have a custom declarative language embedded in some other language such as XML. Here is an example of build code for MSBuild: ```xml <Project Sdk="Microsoft.NET.Sdk"> <ItemGroup> <PackageReference Include="Microsoft.Z3" Version="4.10.2" /> </ItemGroup> </Project> ``` This code tells MSBuild that (1) this is a .NET project, which is the runtime typically associated with C#, and (2) it depends on the library `Microsoft.Z3`, specifically its version `4.10.2`. One can then run MSBuild with this file from the command line, and MSBuild will compile the project after first downloading the library it depends on if it hasn't been downloaded already. In this case, the library name is associated with an actual library by looking up the name on [NuGet](https://www.nuget.org/), the library catalog associated with MSBuild. Build systems remove the dependency on an IDE to build and run code, which means everyone can use the editor they want as long as they use the same build system. Most IDEs can use build system code as the base for their own configuration. For instance, the file above can be used as-is by Visual Studio to configure a project. Build systems enable developers to build, run, and check their code anywhere. But it has to be somewhere, so which machine or machines should they use? Once again, using a developer's specific machine is not a good idea because developers customize their machine according to their personal preferences. The machines developers use may not be representatives of the machines the software will actually run on when used by customers. Just as we defined builds using code through a build system, we can define environments using code! Here is an example of environment definition code for the Docker container system, which you do not need to understand: ``` FROM node:12-alpine RUN apk add python g++ make COPY . . RUN yarn install CMD ["node", "src/index.js"] EXPOSE 3000 ``` This code tells Docker to use the `node:12-alpine` base environment, which has Node.js preinstalled on an Alpine Linux environment. Then, Docker should run `apk add` to install specific packages, including `make`, a build system. Docker should then copy the current directory inside of the container, and run `yarn install` to invoke Node.js's `yarn` build system to pre-install dependencies. The file also tells Docker the command to run when starting this environment and the HTTP port to expose to the outside world. Defining an environment using code enables developers to run and test their code in specific environments that can be customized to match customers' environments. Developers can also define multiple environments, for instance to ensure their software can run on different operating systems, or on operating systems in different languages. We have been using the term "machine" to refer to the environment code runs in, but in practice it's unlikely to be a physical machine as this would be inefficient and costly. Pull requests and pushes happen fairly rarely given that modern computers can do billions of operations per second. Provisioning one machine exclusively for one project would be a waste. Instead, automated builds use _virtual machines_ or _containers_. A virtual machine is a program that emulates an entire machine inside it. For instance, one can run an Ubuntu virtual machine on Windows. From Windows's perspective, the virtual machine is just another program. But for programs running within the virtual machine, it looks like they are running on real hardware. This enables partitioning resources: a single physical machine can run many virtual machines, especially if the virtual machines are not all busy at the same time. It also isolates the programs running inside the virtual machine, meaning that even if they attempt to break the operating system, the world outside of the virtual machine is not affected. However, virtual machines have overhead, especially when running many of them. Even if 100 virtual machines all run the exact same version of Windows, for instance, they must all run an entire separate instance of Windows including the Windows kernel. This is where _containers_ come in. Containers are a lightweight form of virtual machines that share the host operating system's kernel instead of including their own. Thus, there is less duplication of resources, at the cost of less isolation. Typically, services that allow anyone to upload code will use virtual machines to isolate it as much as possible, whereas private services can use containers since they trust the code they run. Using build systems and virtual machines to automatically compile, run, and check code whenever a developer pushes commits is called _continuous integration_, and it is a key technique in modern software development. When a developer opens a pull request, continuous integration can run whatever checks have been configured, such as testing that the code compiles and passes some static analysis. Merging can then be blocked unless continuous integration succeeds. Thus, nobody can accidentally merge broken code into the main branch, and developers who review pull requests don't need to manually check that the code works. Importantly, whether a specific continuous integration run succeeds or fails means that there exists a machine on which the code succeeds or fails. It is possible that code works fine on the machine of the developer who wrote it, yet fails in continuous integration. A common response to this is "but it works on my machine!", but that is irrelevant. The goal of software is not to work on the developer's machine but to work for users. Problems with continuous integration typically stem from differences between developers' machines and the virtual machines configured for continuous integration. For instance, a developer may be testing a phone app on their own phone, with a test case of "open the 'create item' page and click the 'no' button", which they can do fine. But their continuous integration environment may be set up with a phone emulator that has a small screen with few pixels, and the way the app is written means the 'no' button is not visible: <p align="center"><img alt="Illustration of the phones example." src="images/phones.svg" width="50%" /></p> The code thus does not work in the continuous integration environment, not because of a problem with continuous integration, but because the code does not work on some phones. The developer should fix the code so that the "No" button is always visible, perhaps below the "Yes" button with a scroll bar if necessary. --- #### Exercise: Add continuous integration Go back to the GitHub repository you created, and add some continuous integration! GitHub includes a continuous integration service called GitHub Actions, which is free for basic use. Here is a basic file you can use, which should be named `.github/workflows/example.yml`: ```yaml on: push jobs: example: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: echo "Hello!" ``` After pushing this file to the GitHub repository and waiting for a few seconds, you should see a yellow circle next to the commit indicating GitHub Actions is running, which you can also see in the "Actions" tab of the repository. This is a very basic action that only clones the repository and prints text. In a real-world scenario, you would at least invoke a build system. GitHub Actions is quite powerful, as you can read on [the GitHub Actions documentation](https://docs.github.com/en/actions). --- Version control, continuous integration, and other such tasks were typically called "operations", and were done by a separate team from the "development" team. However, nowadays, these concepts have combined into "DevOps", in which the same team does both, which makes it easier for developers to configure exactly the operations they want. ## Summary In this lecture, you learned: - Version control systems, and the differences between 1st, 2nd, and 3rd generation - Git: how to use it for basic scenarios, and how to write good commit messages - Continuous integration: build systems, virtual machines, and containers You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Design Imagine if, in order to display "Hello, World!" on a screen, you had to learn how everything worked. You'd need to learn all about LED lights and their physics. And then you'd need to read the thousands of pages in CPU data sheets to know what assembly code to write. Instead, you can write `print("Hello, World!")` in a language like Scala or Python, and that's it. The language's runtime does all the work for you, with the help of your operating system, which itself contains drivers for hardware. Even those drivers don't know about LED lights, as the screen itself exposes an interface to display data that the drivers use. Python itself isn't a monolith either: it contains sub-modules such as a tokenizer, a parser, and an interpreter. Unfortunately, it's not easy to write large codebases in a clean way, and this is where _design_ comes in. ## Objectives After this lecture, you should be able to: - Apply _modularity_ and _abstraction_ in practice - Compare ways to handle _failures_ - Organize code with _design patterns_ - Use common patterns for modern applications ## How can one design large software systems? [Barbara Liskov](https://en.wikipedia.org/wiki/Barbara_Liskov), one of the pioneers of computer science and programming language design in particular, once [remarked](https://infinite.mit.edu/video/barbara-liskov) that "_the basic technique we have for managing the complexity of software is modularity_". Modularity is all about dividing and sub-dividing software into independent units that can be separately maintained and be reused in other systems: _modules_. Each module has an _interface_, which is what the module exposes to the rest of the system. The module _abstracts_ some concept and presents this abstraction to the world. Code that uses the module does not need to know or care about how the abstraction is implemented, only that it exists. For instance, one does not need to know woodworking or textiles to understand how to use a sofa. Some sofas can even be customized by customers, such as choosing whether to have a storage compartment or a convertible bed, because the sofas are made of sub-modules. In programming, a module's interface is typically called an "API", which is short for "Application Programming Interface". APIs contain objects, functions, errors, constants, and so on. This is _not_ the same thing as the concept of an `interface` in programming languages such as Java. In this lecture, we will talk about the high-level notion of an interface, not the specific implementation of this concept in any specific language. Consider the following Java method: ```java static int compute(String expr) { // ... } ``` This can be viewed as a module, whose interface is the method signature: `int compute(String expr)`. Users of this module do not need to know how the module computes expressions, such as returning `4` for `2 + 2`. They only need to understand its interface. A similar interface can be written in a different technology, such as Microsoft's COM: ```cpp [uuid(a03d1424-b1ec-11d0-8c3a-00c04fc31d2f)] interface ICalculator : IDispatch { HRESULT Compute([in] BSTR expr, [out] long* result); }; ``` This is the interface of a COM component, which is designed to be usable and implementable in different languages. It fundamentally defines the same concept as the Java one, except it has a different way of defining errors (exceptions vs. `HRESULT` codes) and of returning data (return values vs. `[out]` parameters). Anyone can use this COM module given its interface, without having to know or care about how it is implemented and in which language. Another kind of cross-program interface is HTTP, which can be used through server frameworks: ```java @Get("/api/v1/calc") String compute(@Body String expr) { // ... } ``` The interface of this HTTP server is `HTTP GET /api/v1/calc` with the knowledge that the lone parameter should be passed in the body, and the return value will be a string. The Java method name is _not_ part of the interface, because it is not exposed to the outside world. Similarly, the name of the parameter `expr` is not exposed either. These three interfaces could be used in a single system that combines three modules: an HTTP server that internally calls a COM component that internally calls a Java method. The HTTP server doesn't even have to know the Java method exists if it goes through the COM component, which simplifies its development. However, this requires some discipline in enforcing boundaries. If the Java method creates a file on the local disk, and the HTTP server decides to use that file, then the modularity is broken. This problem also exists at the function level. Consider the same Java method as above, but this time with an extra method: ```java static int compute(String expr); static void useReversePolishNotation(); ``` The second method is intended to configure the behavior of the first. However, it creates a dependency between any two modules that use `compute`, since they have to agree on whether to call `useReversePolishNotation` or not, as the methods are `static`. If a module tries to use `compute` assuming the default infix notation, but another module in the system has chosen to use reverse polish notation, the former will fail. Another common issue with modules is voluntarily exposing excess information, usually because it makes implementation simpler in the short term. For instance, should a `User` class with a `name` and a `favoriteFood` also have a Boolean property `fetchedFromDatabase`? It may make sense in a specific implementation, but the concept of tracking users' favorite foods is completely unrelated to a database. The maintainers of code using such a `User` class would need to know about databases any time they deal with users, and the maintainers of the `User` class itself could no longer change the implementation of `User` to be independent of databases, since the interface mandates a link between the two concepts. Similarly, at the package level, a "calc" package for a calculator app with a `User` class and a `Calculator` class probably should not have a `UserInterfaceCheckbox` class, as it is a much lower level concept. --- #### Exercise What would a `Student` class's interface look like... - ... for a "campus companion" app? - ... for a course management system? - ... for an authentication system? How will they differ and why? <details> <summary>Proposed solution (click to expand)</summary> <p> A campus companion app could view students as having a name and preferences such as whether to display vegetarian menus first or in what order to display the user's courses. The campus companion does not care about whether the student has paid their fee for the current semester, which is something a course management system might care about, along with what major the student is in. Neither the campus companion nor the course management should know what the user's password is, or even the concept of passwords since the user might log in using biometric data or two-factor authentication. Those concepts are what the authentication system cares about for students. </p> </details> ## What does modularity require in practice? It is all too easy to write software systems in which each "module" is a mishmash of concepts, modules depend on each other without any clear pattern. Maintaining such a system requires reading and understanding most of the system's code, which doesn't scale to large systems. We have seen the theoretical benefits and pitfalls of modularity, now let's see how to design modular systems in practice. We will talk about the _regularity_ of interfaces, _grouping_ and _layering_ modules, and organizing modules by _abstraction level_. ### Regularity Consider fractals such as this one: <p align="center"><img alt="A rendering of the Mandelbrot fractal" src="images/mandelbrot.png" width="50%" /></p> This image may look complex, but because it is a fractal, it is very regular. It can be [formally defined](https://en.wikipedia.org/wiki/Mandelbrot_set#Formal_definition) with a short mathematical equation and a short sentence. Contrast it to this image: <p align="center"><img alt="Random noise" src="images/noise.png" width="50%" /></p> This is random noise. It has no regularity whatsoever. The only way to describe it is to describe each pixel in turn, which takes a long time. The idea that things should be regular and have short descriptions applies to code as well. Consider the following extract from Java's `java.util` package: ```java class Stack { /** Returns the 1-based position where an object is on this stack. */ int search(Object o); } ``` For some reason, `search` returns a 1-based position, even though every other index in Java is 0-based. Thus, any description of `search` must include this fact, and a cursory glance at code that uses `search` may not spot a bug if the index is accidentally used as if it was 0-based. One should follow the "principle of least surprise", i.e., things should behave in the way most people will expect them to, and thus not have exceptions to common rules. Another example from Java is the `URL` class's `equals` method. One would expect that, like any other equality check in Java, `URL::equals` checks the fields of both objects, or perhaps some subset of them. However, what it [actually does](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/net/URL.html#equals(java.lang.Object)) is to check whether the two URLs resolve to the same IP address. This means the result depends on whether the two URLs happen to point to the same IP at that particular point in time, and even whether the machine the code is running on has an Internet connection. It also takes time to resolve IP addresses, which is orders of magnitude slower than usual `equals` methods that check for field equality. A more formal way to view regularity is [Kolmogorov complexity](https://en.wikipedia.org/wiki/Kolmogorov_complexity): how many words do you need to describe something? For instance, the fractal above has low Kolmogorov complexity because it can be described in very few words. One can write a short computer program to produce it. In comparison, the random noise above has high Kolmogorov complexity because it can only be described with many words. A program to produce it has to produce each pixel individually. Any module whose description must include "and..." or "except..." has higher Kolmogorov complexity than it likely needs to. ### Grouping What do the following classes have in common? `Map<K, V>, Base64, Calendar, Formatter, Optional<T>, Scanner, Timer, Date`. Not much, do they? Yet they are all in the same `java.util` package in Java's standard library. This is not a good module interface: it contains a bunch of unrelated things! If you see that a Java program depends on `java.util`, you don't gain much information, because it is such a broad module. Now what do the following classes have in common? `Container, KeysView, Iterable, Sequence, Collection, MutableSet, Set, AsyncIterator`. This is much more straightforward: they are all collections, and indeed they are in the Python collections module. Unfortunately, that module is named `collections.abc`, because it's a fun acronym for "abstract base classes", which is not a great name for a module. But at least if you see a Python program depends on `collections.abc`, after looking up the name, you now know that it uses data structures. The importance of _grouping_ related things together explains why global variables are such a problem. If multiple modules all access the same global variable, then they all effectively form one module since a programmer needs to understand how each of them uses the global variable to use any of them. The grouping done by global variables is accidental, and thus unlikely to produce useful groups. ### Layering You may already know the networking stack's layers: the application layer uses the transport layer, which uses the network layer, and so on until the physical layer at the bottom-most level. The application layer does not use the network layer directly, nor does it even know there is a network layer. The network layer doesn't know there is an application or a transport layer, either. Layering is a way to define the dependencies between modules in a minimal and manageable way, so that maintaining a module can be done without knowledge of most other modules. There can be more than one module at a given layer: for instance, an app could use mobile and server modules, which form the layer below the app module. The server module itself may depend on an authentication module and a database module, which form the layer below, and so on. Thus, layer `N` depends _only_ on layer `N-1`, and the context for layer `N`'s implementation is the interface of layer `N-1`. By building layers in a tall stack, one minimizes the context of each layer's implementation. Sometimes, however, it is necessary to have one layer take decisions according to some higher-level logic, such as what comparison to use in a sorting function. Hardcoding knowledge about higher-level items in the sorting function would break layering and make it harder to maintain the sorting function. Instead, one can inject a "comparison" function as a parameter of the sort function: ```scala def sort(items, less_than) = { ... if (less_than(items(i), items(j)) ... } ``` The higher-level layers can thus pass a higher-level comparison function, and the sorting function does not need to explicitly depend on any layer above it, solving the problem. This can also be done with objects by passing other objects as constructor parameters, and even with packages in languages that permit it such as [Ada](https://en.wikipedia.org/wiki/Ada_(programming_language)). Layering also explains the difference between _inheritance_, such as `class MyApp extends MobileApp`, and _composition_, such as `class MyApp { private MyApp app; }`. The former requires `MyApp` to expose all of the interface of `MobileApp` in addition to its own, whereas the latter lets `MyApp` choose what to expose and optionally use `MobileApp` to implement its interface: <p align="center"><img alt="Visual representation of the layers from inheritance or composition of MyApp and MobileApp" src="images/layers.svg" width="50%" /></p> In most cases, composition is the appropriate choice to avoid exposing irrelevant details to higher-level layers. However, inheritance can be useful if the modules are logically in the same layer, such as `LaserPrinter` and `InkjetPrinter` both inheriting from `Printer`. ### Abstraction levels An optical fiber cable provides a very low-level abstraction, which deals with light to transmit individual bits. The Ethernet protocol provides a higher-level abstraction, which deals with MAC addresses and transmits bytes. A mobile app provides provides a high-level abstraction, which deals with requests and responses to transmit information such as the daily menus in cafeterias. If you had to implement a mobile app, and all you had available was an optical fiber cable, you would spend most of your time re-implementing intermediate abstractions, since defining a request for today's menu in terms of individual bits is hard. On the other hand, if you had to implement an optical fiber cable extension, and all you had available was the high-level abstraction of daily cafeteria menus, you would not be able to do your job. The high-level abstraction is convenient for high-level operations, but voluntarily hides low-level details. When designing a module, think about its _abstraction level_: where does it stand in the spectrum from low-level to high-level abstractions? If you provide an abstraction of a level higher than what is needed, others won't be able to do their work because they cannot access the low-level information they need. If you provide an abstraction of a level lower than what is needed, others will have to spend lots of time reinventing the high-level wheel on top of your low-level abstraction. You do not always have to choose a single abstraction level: you can expose multiple ones. For instance, a library might expose a module to transmit bits on optical fiber, a module to transmit Ethernet packets, and a module to make high-level requests. Internally, the high-level request module might use the Ethernet module, which might use the optical fiber module. Or not; there's no way for your customers to know, and there's no reason for them to care, as long as your modules provide working implementations of the abstractions they expose. A real-world example of differing abstraction levels is displaying a triangle using a GPU, which is the graphics equivalent of printing the text "Hello, World!". Using a high-level API such as [GDI](https://en.wikipedia.org/wiki/Graphics_Device_Interface) displaying a triangle requires around 10 lines of code. You can create a window object, create a triangle object, configure these objects' colors, and show them. Using a lower-level API such as [OpenGL](https://en.wikipedia.org/wiki/OpenGL), displaying a triangle requires around 100 lines of code, because you must explicitly deal with vertexes and shaders. Using an even lower-level API such as [Vulkan](https://en.wikipedia.org/wiki/Vulkan), displaying a triangle requires around 1000 lines of code, because you must explicitly deal with all of the low-level GPU concepts that even OpenGL abstracts away. Every part of the graphics pipeline must be configured in Vulkan. But this does not make Vulkan a "bad" API, only one that is not adapted to high-level tasks such as displaying triangles. Instead, Vulkan and similar APIs such as [Direct3D 12](https://en.wikipedia.org/wiki/Direct3D#Direct3D_12) are intended to be used for game engines and other "intermediate" abstractions that themselves provide higher-level abstractions. For instance, OpenGL can be implemented as a layer on top of Vulkan. Without such low-level abstractions, it would be impossible to implement high-level abstractions efficiently, and indeed performance was the main motivation for the creation of APIs such as Vulkan. When implementing an abstraction on top of a lower-level abstraction, be careful to avoid _abstraction leaks_. An abstraction leak is when a low-level detail "pops out" of a high-level abstraction, forcing users of the abstraction to understand and deal with lower-level details than they care about. For instance, if the function to show today's menu has the signature `def showMenu(date: LocalDate, useIPv4: Boolean)`, anyone who wants to write an application that shows menus must explicitly think about whether they want to use IPv4, a lower-level detail that should not be relevant at all in this context. Note that the terminology "abstraction leak" is not related to the security concept of "information leak", despite both being leaks. One infamous abstraction leak is provided by the former C standard library function `char* gets(char* str)`. "Former" function because it is the only one that was considered so bad it had to be removed from the C standard library, breaking compatibility with previous versions. What `gets` does is to read a line of input on the console and store it in the memory pointed to by `str`. However, there's a mismatch in abstraction levels: `gets` tries to provide the abstraction of "a line of text", yet it uses the C concept of "a pointer to characters". Because the latter has no associated length, this abstraction leak is a security flaw. No matter how large the buffer pointed to by `str` is, the user could write more characters than that, at which point `gets` would overwrite whatever is next in memory with whatever data the user typed. ### Recap Design systems such that individual modules have a regular API that provides one coherent abstraction. Layer your modules so that each module only depends on modules in the layer immediately below, and the layers are ordered by abstraction level. For instance, here is a design in which the green module provides a high-level abstraction and depends on the yellow modules, which provide abstractions of a lower level, and themselves depend on the red modules and their lowest-level abstractions: <p align="center"><img alt="A module diagram as explained in text" src="images/system.svg" width="50%" /></p> One way to do this at the level of individual functions is to write the high-level module first, with a high-level interface, and an implementation that uses functions you haven't written yet. For instance, for a method that predicts the weather: ```java int predictWeather(LocalDate date) { var past = getPastWeather(date); var temps = extractTemperatures(past); return predict(temps); } ``` After doing this, you can implement `getPastWeather` and others, themselves in terms of lower-level interfaces, until you either implement the lowest level yourself or reuse existing code for it. For instance, `getPastWeather` will likely be implemented with some HTTP library, while `extractTemperature` will likely be custom-made for the format of `past`. --- #### Exercise Look at `App.java` in the [`calc`](exercises/lecture/calc) project. It mixes all kinds of concepts together. Modularize it! Think about what modules you need, and how you should design the overall system. First off, what will the new `main` method look like? <details> <summary>Suggested solution (click to expand)</summary> <p> Create one function for obtaining user input, one for parsing it into tokens, one for evaluating these tokens, and one for printing the output or lack thereof. The evaluation function can internally use another function to execute each individual operator, so that all operators are in one place and independent of input parsing. See the [solution file](exercises/solutions/lecture/Calc.java) for an example, which has the following structure: ```mermaid graph TD A[main] B[getInputl] C[parseInput] D[compute] E[execute] F[display] A --> B A --> C A --> D A --> F D --> E ``` </p> </details> --- At this point, you may be wondering: how far should you go with modularization? Should your programs consist of thousands of tiny modules stacked hundreds of layers high? Probably not, as this would cause maintainability issues just like having a single big module for everything does. But where to stop? There is no single objective metric to tell you how big or small a module should be, but here are some heuristics. You can estimate _size_ using the number of logical paths in a module. How many different things can the module do? If you get above a dozen or so, the module is probably too big. You can estimate _complexity_ using the number of inputs for a module. How many things does the module need to do its job? If it's more than four or five, the module is probably too big. Remember the acronym _YAGNI_, for "You Aren't Gonna Need It". You could split that module into three even smaller parts that hypothetically could be individually reused, but will you need this? No? You Aren't Gonna Need It, so don't do it. You could provide ten different parameters for one module to configure every detail of what it does, but will you need this? No? You Aren't Gonna Need It, so don't do it. One way to discuss designs with colleagues is through the use of diagrams such as [UML class diagrams](https://en.wikipedia.org/wiki/Class_diagram), in which you draw modules with their data and operations and link them to indicate composition and inheritance relationships. Keep in mind that the goal is to discuss system design, not to adhere to specific conventions. As long as everyone agrees on what each diagram element means, whether or not you adhere to a specific convention such as UML is irrelevant. Beware of the phenomenon known as "[cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming)". The idea of a "cargo cult" originated in remote islands used by American soldiers as bases during wars. These islands were home to native populations who had no idea what planes were, but who realized that when Americans did specific gestures involving military equipment, cargo planes full of supplies landed on the islands. They naturally hypothesized that if they, the natives, could replicate these same gestures, more planes might land! Of course, from our point of view we know this was useless because they got the correlation backwards: Americans were doing landing gestures because they knew planes were coming, not the other way around. But the natives did not know that, and tried to get cargo planes to land. Some of these cults lasted for longer than they should have, and their modern-day equivalent in programming is engineers who design their system "because some large company, like Google or Microsoft, does it that way" without the knowledge nor the understanding of why the large company does it that way. Typically, big system in big companies have constraints that do not apply to the vast majority of systems, such as dealing with thousands of requests per second or having to provide extreme availability guarantees. ## How can one mitigate the impact of failures? What should happen when one part of a system has a problem? [Margaret Hamilton](https://en.wikipedia.org/wiki/Margaret_Hamilton_(software_engineer)), who along with her team wrote the software that put spaceships in orbit and people on the Moon, recalled [in a lecture](https://www.youtube.com/watch?v=ZbVOF0Uk5lU) how she tried persuading managers to add a safety feature to a spaceship. She had brought her young daughter to work one day, and her daughter tried the spaceship simulator. Surprisingly, the daughter managed to crash the software running in the simulator. It turned out that the software was not resilient to starting one operation while the spaceship was supposed to be in a completely different phase of flight. Hamilton tried to persuade her managers that the software should be made resilient to such errors, but as she recalls it: "_[the managers] said 'this won't ever happen, astronauts are well-trained, they don't make mistakes... the very next mission, Apollo 8, this very thing happened [...] it took hours to get [data] back_". The lack of a check for this condition was an _error_, i.e., the team who programmed the software chose not to consider a problem that might happen in practice. Other kinds of errors involve forgetting to handle a failure case, or writing code that does not do what the programmer think it does. Errors cause _defects_ in the system, which can be triggered by external inputs, such as an astronaut pressing the wrong button. If defects are not handled, they cause _failures_, which we want to avoid. Errors are inevitable in any large system, because systems involve humans and humans are fallible. "Just don't make errors" is not a realistic solution. Even thinking about all possible failure cases is hard; consider the "[Cat causes login screen to hang](https://bugs.launchpad.net/ubuntu/+source/unity-greeter/+bug/1538615)" in Ubuntu. Who would have thought that thousands of characters in a username input field was a realistic possibility from a non-malicious user? Preventing failures thus requires preventing defects from propagating through the system, i.e., _mitigating_ the impact of defects. We will see four ways to do it, all based on modules: isolating, repairing, retrying, and replacing. How much effort you should put into tolerating defects depends on what is at stake. A small script you wrote yourself to fetch cartoons should be tolerant to temporary network errors, but does not need advanced recovery techniques. On the other hand, the [barrier over the Thames river](https://www.youtube.com/watch?v=eY-XHAoVEeU) that prevents mass floods needs to be resilient against lots of possible defects. ### Isolating Instead of crashing an entire piece of software, it is desirable to _isolate_ the defect and crash only one module, as small and close to the source of the defect as possible. For instance, modern Web browsers isolate each tab into its own module, and if the website inside the tab causes a problem, only that tab needs to crash, not the entire browser. Similarly, operating systems isolate each program such that only the program crashes if it has a defect, not the entire operating system. However, only isolate if the rest of the program can reasonably function without the failed module. For instance, if the module responsible for drawing the overall browser interface crashes, the rest of the browser cannot function. On the other hand, crashing only a browser tab is acceptable, as the user can still use other tabs. ### Repairing Sometimes a module can go into unexpected states due to defects, at which point it can be _repaired_ by switching to a well-known state. This does not mean moving from the unexpected state in some direction, since the module does not even know where it is, but replacing the entirety of the module's state with a specific "backup" state that is known to work. An interesting example of this is [the "top secret" room](https://zelda-archive.fandom.com/wiki/Top_Secret_Room) in the video game _The Legend of Zelda: A Link to the Past_. If the player manages to get the game into an unknown state, for instance by switching between map areas too quickly for the game to catch up, the game recognizes that it is confused and drops the player into a special room, and pretends that this is intentional and the player has found a secret area. One coarse form of repair is to "turn it off and on again", such as restarting a program, or rebooting the operating system. The state immediately after starting is known to work, but this cannot be hidden from users and is more of a way to work around a failure. However, only repair if the entirety of a module's state can be repaired to a state known to work. Repairing only part of a module risks creating a Frankenstein abomination that only makes the problem worse. ### Retrying Not all failures are forever. Some failures come from external causes that can fix themselves without your intervention, and thus _retrying_ is often a good idea. For instance, if a user's Internet connection fails, any Web request your app made will fail. But it's likely that the connection will be restored quickly, for instance because the user was temporarily in a place with low cellular connectivity such as a tunnel. Thus, retrying some number of times before giving up avoids showing unnecessary failures to the user. How many times to retry, and how much to wait before retries, is up to you, and depends on the system and its context. However, only retry if a request is _idempotent_, meaning that doing it more than once has the same effect as doing it once. For instance, withdrawing cash from a bank account is not an idempotent request. If you retry it because you didn't get a response, but the request had actually reached the server, the cash will be withdrawn twice. You should also only retry when encountering problems that are _recoverable_, i.e., for which retrying has a chance to succeed because they come from circumstances beyond your control that could fix themselves. For instance, "no internet" is recoverable, and so is "printer starting and not ready yet". This is what Java tried to model as "checked" exceptions: if the exception is recoverable, the language should force the developer to deal with it. On the other hand, problems such as "the desired username is already taken" or "the code has a bug which divided by zero" are not recoverable, because retrying will hit the same issue again and again. ### Replacing Sometimes there is more than one way to perform a task, and some of these ways can serve as backups, _replacing_ the main module if there is a problem. For instance, if a fingerprint reader cannot recognize a user's finger because the finger is too wet, an authentication system could ask for a password instead. However, only replace if you have an alternative that is as robust and tested as the original one. The "backup" module should not be old code that hasn't been run in years, but should be treated with the same care and quality bar as the main module. ## How can one reuse concepts across software systems? When designing a system, the context is often the same as in previous systems, and so are the user requirements. For instance, "cross over a body of water" is a common requirement and context that leads to the natural solution "build a bridge". If every engineer designed the concept of a bridge from scratch every time someone needed to cross a body of water, each bridge would not be very good, as it would not benefit from the knowledge accumulated by building previous bridges. Instead, engineers have blueprints for various kinds of bridges, select them based on the specifics of the problem, and propose improvements when they think of any. In software engineering, these kinds of blueprints are named _design patterns_, and are so common that one sometimes forgets they even exist. For instance, consider the following Java loop: ```java for (int item : items) { // ... } ``` This `for` construct looks perfectly normal and standard Java, but it did not always exist. It was introduced in Java 1.5, alongside the `Iterable<T>` interface, instead of having every collection provide its own way to iterate. This used to be known as "the Iterator design pattern", but nowadays it’s such a standard part of modern programming languages that we do not explicitly think of it as a design pattern any more. Design patterns are blueprints, not algorithms. A design pattern is not a piece of code you can copy-paste, but an overall description of what the solution to a common problem can look like. You can think of it as providing the name of a dish rather than the recipe for it. Have some fish? You could make fish with vegetables and rice, which is a healthy combo. Soy sauce is also a good idea as part of the sauce. How exactly you cook the fish, or which vegetables you choose, is up to you. There are many patterns, and even more descriptions of them online. We provide a [short summary](DesignPatterns.md) of common ones. In this lecture, we will see patterns to separate the user interface of a program, the business logic that is core to the program, and the reusable strategies the program needs such as retrying when a request fails. The problem solved by design patterns for user interfaces is a common one: software engineers must write code for applications that will run on different kinds of systems, such as a desktop app and a mobile app. However, writing the code once per platform would not be maintainable: most of the code would be copy-pasted. Any modification would have to be replicated on all platforms’ code, which would inevitably lead to one copy falling out of sync. Instead, software engineers should be able to write the core logic of the application once, and only write different code per platform for the user interface. This also means tests can be written against the logic without being tied to a specific user interface. This is a requirement in practice for any large application. For instance, Microsoft Office is tens of millions of lines of code; it would be entirely infeasible to have this code duplicated in Office for Windows, Mac, Android, the web, and so on. The business logic is typically called the _model_, and the user interface is called the _view_. We want to avoid coupling them, thus we naturally need something in the middle that will talk to both of them, but what? ### Model-View-Controller (MVC) In the MVC pattern, the view and model are mediated by a controller, with which users interact. A user submits a request to the controller, which interacts with the model and returns a view to the user: <p align="center"><img alt="A diagram illustrating the MVC pattern" src="images/mvc.svg" width="50%" /></p> For instance, in a website, the user's browser sends an HTTP request to the controller, which eventually creates a view using data from the model, and the view renders as HTML. The view and model are decoupled, which is good, but there are also disadvantages. First, users don’t typically talk directly to controllers, outside of the web. Second, creating a new view from scratch every time is not very efficient. ### Model-View-Presenter (MVP) In the MVP pattern, the view and model are mediated by a presenter, but the view handles user input directly. This matches the architecture of many user interfaces: users interact directly with the view, such as by touching a button on a smartphone screen. The view then informs the presenter of the interaction, which talks to the model as needed and then tells the view what to update: <p align="center"><img alt="A diagram illustrating the MVP pattern" src="images/mvp.svg" width="50%" /></p> This fixes two of MVC's problems: users don’t need to know about the intermediary module, they can interact with the view instead, and the view can be changed incrementally. --- #### Exercise Transform the code of `App.java` in the [`weather`](exercises/lecture/weather) project to use the MVP pattern. As a first step, what will the interface of your model and view look like? Once that's set, implement them by moving the existing code around, and think about what the presenter should look like. <details> <summary>Suggested solution (click to expand)</summary> <p> The model should provide a method to get the forecast, and the view should provide a method to show text and one to run the application. Then, move the existing code into implementations of the model and the view, and write a presenter that binds them together. See the [solution file](exercises/solutions/lecture/Weather.java) for an example. </p> </details> --- MVP does have disadvantages. First, the view now holds state, as it is updated incrementally. This pushes more code into the view, despite one of our original goals being to have as little code in the view as possible. Second, the interface between the view and the presenter often becomes tied to specific actions that the view can do given the context, such as a console app, and it's hard to make the view generic over many form factors. ### Model-View-ViewModel (MVVM) Let's take a step back before describing the next pattern. What is a user interface anyway? - Data to display - Commands to execute ...and that's it! At a high-level, at least. The key idea behind MVVM is that the view should observe data changes using the Observer pattern, and thus the intermediary module, the viewmodel, only needs to be a platform-independent user interface that exposes data, commands, and an Observer pattern implementation to let views observe changes. The result is a cleanly layered system, in which the view has little code and is layered on top of the viewmodel, which holds state and itself uses the model to update its state when commands are executed: <p align="center"><img alt="A diagram illustrating the MVVM pattern" src="images/mvvm.svg" width="50%" /></p> The view observes changes and updates itself. It can choose to display the data in any way it wants, as the viewmodel does not tell it how to update, only what to display. The view is conceptually a function of the viewmodel: it could be entirely computed from the viewmodel every time, or it could incrementally change itself as an optimization. This is useful for platforms such as smartphones, in which applications running in the background need to use less memory: the view can simply be destroyed, as it can be entirely re-created from the viewmodel whenever needed. MVVM also enables the code reuse we set out to achieve, as different platforms need different views but the same model and viewmodel, and the viewmodel contains the code that keeps track of state, thus the views are small. ### Middleware You've written an app using an UI design pattern to separate your business logic and your user interface, but now you get a customer request: can the data be cached so that an Internet connection isn't necessary? Also, when there isn't cached data, can the app retry if it cannot connect immediately? You could put this logic in your controller, presenter, or viewmodel, but that would tie it to a specific part of your app. You could put it in a model, but at the cost of making that module messier as it would contain multiple orthogonal concepts. Instead, this is where the _middleware_ pattern comes in, also known as _decorator_. A middleware provides a layer that exposes the same interface as the layer below but adds functionality: <p align="center"><img alt="A diagram illustrating the Middleware pattern" src="images/middleware.svg" width="50%" /></p> A middleware can "short circuit" a request if it wants to answer directly instead of using the layers below. For instance, if a cache has recent data, it could return that data without asking the layer below for the very latest data. One real-world example of middlewares is in [Windows file system minifilters](https://learn.microsoft.com/en-us/windows-hardware/drivers/ifs/filter-manager-concepts), which are middlewares for storage that perform tasks such as virus detection, logging, or replication to the cloud. This design allows programs to add their own filter in the Windows I/O stack without interfering with others. Programs such as Google Drive do not need to know about other programs such as antiviruses. --- #### Exercise You've transformed the [`weather`](exercises/lecture/weather) project to use the MVP pattern already, now add a retrying middleware that retries until the weather is known and not `???`. As a first step, write a middleware that wraps a model and provides the same interface as the model, without adding functionality. Then add the retrying logic to your middleware. <details> <summary>Suggested solution (click to expand)</summary> <p> Your middleware needs to use the wrapped model in a loop, possibly with a limit on retries. See the [solution file](exercises/solutions/lecture/RetryingWeather.java) for an example. </p> </details> --- Beware: just because you _can_ use all kinds of patterns does not mean you _should_. Remember to avoid cargo cults! If "You Aren't Gonna Need It", don't do it. Otherwise you might end up with an "implementation of AspectInstanceFactory that locates the aspect from the BeanFactory using a configured bean name", just in case somebody _could_ want this flexibility. [Really](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.html)! ## Summary In this lecture, you learned: - Abstraction and modularity, and how to use them in practice: regularity, grouping, layering, abstraction levels, and abstraction leaks - Tolerating defects: isolating, retrying, repairing, and replacing - Design patterns, and specifically common ones to decouple user interfaces, business logic, and reusable strategies: MVC, MVP, MVVM, and Middleware You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Design Patterns This document contains a curated list of common design patterns, including context and examples. _These examples are there to concisely illustrate patterns._ _Real code would also include visibility annotations (`public`, `private`, etc.), make fields `final` if possible,_ _provide documentation, and other improvements that would detract from the point being made by each example._ ## Adapter An _adapter_ converts an object of type `X` when it must be used with an interface that accepts only objects of type `X'`, similar but not the same as `X`. For instance, an app may use two libraries that both represent color with four channels, one B/G/R/A and one A/R/G/B. It is not possible to directly use an object from one library with the other library, and that's where you can use an _adapter_: an object that wraps another object and provides a different interface. A real-world example is an electrical adapter, for instance to use a Swiss device in the United States: both plugs fundamentally do the same job, but one needs a passive adapter to convert from one plug type to the other. Example: ```java interface BgraColor { // 0 = B, 1 = G, 2 = R, 3 = A float getChannel(int index); } interface ArgbColor { float getA(); float getR(); float getG(); float getB(); } class BgraToArgbAdapter implements ArgbColor { BgraColor wrapped; BgraToArgbAdapter(BgraColor wrapped) { this.wrapped = wrapped; } @Override public float getA() { return wrapped.getChannel(3); } @Override public float getR() { return wrapped.getChannel(2); } @Override public float getG() { return wrapped.getChannel(1); } @Override public float getB() { return wrapped.getChannel(0); } } ``` ## Builder A _builder_ works around the limitations of constructors when an object must be immutable yet creating it all at once is not desirable. For instance, a `Rectangle` with arguments `width, height, borderThickness, borderColor, isBorderDotted, backgroundColor` is complex, and a constructor with all of these arguments would make code creating a `Rectangle` hard to read. Furthermore, some arguments logically form groups: it is not useful to specify both `borderColor` and `isBorderDotted` if one does not want a border. Creating many rectangles that share all but a few properties is also verbose if one must re-specify all of the common properties every time. Instead, one can create a `RectangleBuilder` object that defines property groups, uses default values for unspecified properties, and has a `build()` method to create a `Rectangle`. Each method defining properties returns `this` so that the builder is easier to use. A special case of builders is when creating an object incrementally is otherwise too expensive, as in immutable strings in many languages. If one wants to create a string by appending many chunks, using the `+` operator will copy the string data over and over again, creating many intermediate strings. For instance, appending `["a", "b", "c", "d"]` without a builder will create the intermediate strings `"ab"` and `"abc"` which will not be used later. In contrast, a `StringBuilder` can internally maintain a list of appended strings, and copy their data only once when building the final string. Example: ```java class Rectangle { public Rectangle(int width, int height, int borderThickness, Color borderColor, boolean isBorderDotted, Color backgroundColor, ...) { ... } } class RectangleBuilder { // width, height are required RectangleBuilder(int width, int height) { ... } // optional, no border by default RectangleBuilder withBorder(int thickness, Color color, boolean isDotted) { ... ; return this; } // optional, no background by default RectangleBuilder withBackgroundColor(Color color) { ... ; return this; } // to create the rectangle Rectangle build() { ... } } // Usage example: new RectangleBuilder(100, 200) .withBorder(10, Colors.BLACK, true) .build(); ``` ## Composite A _composite_ handles a group of objects of the same kind as a single object, through an object that exposes the same interface as each individual object. For instance, a building with many apartments can expose an interface similar to that of a single apartment, with operations such as "list residents" that compose the results of calling the operation on each apartment in the building. Example: ```java interface FileSystemItem { String getName(); boolean containsText(String text); ... } class File implements FileSystemItem { // implementation for a file } class Folder implements FileSystemItem { Folder(String name, List<FileSystemItem> children) { ... } // the implementation of "containsText" delegates to its children // the children could themselves be folders, without Folder having to know or care } ``` ## Facade A _facade_ hides unnecessary details of legacy or third-party code behind a clean facade. It's a kind of adapter whose goal is to convert a hard-to-use interface into an easy-to-use one, containing the problematic code into a single class instead of letting it spill in the rest of the system. This can be used for legacy code that will be rewritten: if the rewritten code has the same interface as the facade, the rest of the program won't need to change after the rewrite. Example: ```java // Very detailed low-level classes, useful in some contexts, but all we want is to read some XML data class BinaryReader { BinaryReader(String path) { ... } } class StreamReader { StreamReader(BinaryReader reader) { ... } } class TextReader { TextReader(StreamReader reader) { ... } } class XMLOptions { ... } class XMLReader { XMLReader(TextReader reader, XMLOptions options) { ... } } class XMLDeserializer { XMLDeserializer(XMLReader reader, bool ignoreCase, ...) { ... } } // So we provide a facade class XMLParser { XMLParser(String path) { // ... creates a BinaryReader, then a StreamReader, ..., and uses specific parameters for XMLOptions, ignoreCase, ... } } ``` ## Factory A _factory_ is a function that works around the limitations of constructors by creating an object whose exact type depends on the arguments, which is not something most languages can do in a constructor. Thus, one creates instead a factory function whose return type is abstract and which decides what concrete type to return based on the arguments provided to the factory. Example: ```java interface Config { ... } class XMLConfig implements Config { ... } class JSONConfig implements Config { ... } class ConfigFactory { static Config getConfig(String fileName) { // depending on the file, creates a XMLConfig or a JSONConfig } } ``` ## Middleware (a.k.a. Decorator) A _middleware_, also known as _decorator_ is a layer that exposes the same interface as the layer directly below it and adds some functionality, such as caching results or retrying failed requests. Instead of bloating an object with code that implements a reusable strategy orthogonal to the object's purpose, one can "decorate" it with a middleware. Furthermore, if there are multiple implementations of an interface, without a middleware one would need to copy-paste the reusable logic in each implementation. A middleware may not always use the layer below, as it can "short circuit" a request by answering it directly, for instance if there is recent cached data for a given request. Example: ```java interface HttpClient { /** Returns null on failure */ String get(String url); } // Implements HTTP 1 class Http1Client implements HttpClient { ... } // Implements HTTP 2 class Http2Client implements HttpClient { ... } class RetryingHttpClient implements HttpClient { HttpClient wrapped; int maxRetries; HttpClientImpl(HttpClient wrapped, int maxRetries) { this.wrapped = wrapped; this.maxRetries = maxRetries; } @Override String get(String url) { for (int n = 0; n < maxRetries; n++) { String result = wrapped.get(url); if (result != null) { return result; } } return null; } } class CachingHttpClient implements HttpClient { ... } // one can now decorate any HttpClient with a RetryingHttpClient or a CachingHttpClient, // and since the interface is the same, one can decorate an already-decorated object, e.g., new CachingHttpClient(new RetryingHttpClient(new Http2Client(...), 5)) ``` ## Null Object A _null object_ is a replacement for "a lack of object", e.g., `null`, that behaves as a "no-op" for all operations, which enables the rest of the code to not have to explicitly handle it. This is useful even in languages that do not directly have `null`, such as Scala with `Option`, since sometimes one may want to run an operation on a potentially missing object without having to explicitly handle `None` everywhere. It's the equivalent of returning an empty list instead of `null` to indicate a lack of results: one can handle an empty list like any other list. Example: ```java interface File { boolean contains(String text); } class RealFile implements File { ... } class NullFile implements File { @Override boolean contains(String text) { return false; } } class FileSystem { static File getFile(String path) { // if the path doesn't exist, instead of returning `null` (or a `None` option in languages like Scala), // return a `NullFile`, which can be used like any other `File` } } ``` ## Observer The _observer_ pattern lets objects be notified of events that happen in other objects, without having to poll for changes. For instance, it would be extremely inefficient for an operating system to constantly ask the keyboard "did the user press a key?", since >99% of the time this is not the case. Instead, the keyboard lets the OS "observe" it by registering for change notifications. Furthermore, the keyboard can implement a generic "input change notifier" interface so that the OS can handle input changes without having to depend on the specifics of any input device. Similarly, the OS can implement a generic "input change observer" interface so that the keyboard can notify the OS of changes without having to depend on the specifics of any OS. Example: ```java interface ButtonObserver { // Typically the object that triggered the event is an argument, so that the observer can distinguish multiple sources // if it has registered to their events void clicked(Button source); } class Button { void registerForClicks(ButtonObserver button) { // handles a list of all observers } // optionally, could provide a way to remove an observer } // One can now ask any Button to notify us when it is clicked // In fact, the Button may implement this by itself observing a lower-level layer, e.g., the mouse, and reporting only relevant events ``` ## Pool A _pool_ keeps a set of reusable objects to amortize the cost of creating these objects, typically because their creation involves some expensive operation in terms of performance. For instance, connecting to a remote server is slow as it requires multiple round-trips to perform handshakes, cryptographic key exchanges, and so on; a connection pool can lower this cost by reusing an existing connection that another part of the program used but no longer needs. As another example, language runtimes keep a pool of free memory that can be used whenever the program allocates memory, instead of asking the operating system for memory each time, which is slow because it involves a system call. The pool still needs to perform a system call to get more memory once it's empty, but that should happen rarely. The pool pattern is typically only necessary for advanced performance optimizations. Example: ```java class ExpensiveThing { ExpensiveThing() { // ... some costly operation, e.g., opening a connection to a server ... } } class ExpensiveThingPool { private Set<ExpensiveThing> objects; ExpensiveThing get() { // ... return an existing instance if `objects` contains one, or create one if the pool is empty ... } // Warning, "releasing" the same thing twice is dangerous! void release(ExpensiveThing thing) { ... } } // Instead of `new ExpensiveThing()`, one can now use a pool ``` ## Singleton A _singleton_ is a global variable by another name, which is typically either a bad idea or a workaround for the limitations of third-party code. A singleton is an object of which there is only one instance, publicly accessible by any other code. There are advanced cases in which a singleton might be justified, such as in combination with a pool to share a pool across libraries, but it should generally be avoided. ## Strategy A _strategy_ lets the callers of a function configure part of the function's logic by passing code as a parameter. For instance, a sorting method needs a way to compare two elements, but the same type of elements might be compared in different ways based on context, such as ascending or descending for integers. The sorting method can take as argument a function that compares two elements, and then call this function whenever it needs a comparison. Thus, the sorting method only cares about implementing an efficient sorting algorithm given a way to compare, and does not hardcode a specific kind of comparison. This also ensures the sorting method does not need to depend on higher-level modules to know how to sort its input, such as what kind of object is being sorted, since the strategy takes care of that. Example: ```java // (De)serializes objects interface Serializer { ... } // Persistent cache for objets, which stores objects on disk // Uses a "serializer" strategy since depending on context one may want different serialization formats, or perhaps even encryption for sensitive data class PersistentCache { PersistentCache(Serializer serializer) { ... } } ``` ## MVC: Model-View-Controller A _controller_ is an object that handles user requests, using a _model_ internally, then creates a _view_ that is rendered to the user. MVC is appropriate when the user interacts with the controller directly, e.g., through an HTTP request. MVC can decouple user interface code and business logic, making them more maintainable, reusable, and testable. Example: ```java // Model class WeatherForecast { WeatherForecast(...) { ... } int getTemperature(...) { ... } } // View // Could be HTML as is the example here, but we could also add a `WeatherView` interface and multiple types of views, // such as a JSON one for automated request (using the HTTP "Accept" header to know what view format the user wants) class HtmlWeatherView { HtmlWeatherView(int temperature, ...) { ... } String toString() { ... } } // Controller class WeatherController { WeatherForecast forecast; WeatherController(...) { // The controller could create its own WeatherForecast object, or have it as a dependency, likely with an interface for it to make it testable forecast = ...; } HtmlWeatherView get(...) { int temperature = forecast.getTemperature(...); return new HtmlWeatherView(temperature, ...); } } // In general, one would use a framework that can be configured to know which HTTP paths correspond to which method on which controller object, // But this can be done manually as well: System.out.println(new WeatherController(...).get(...).toString()); ``` ## MVP: Model-View-Presenter A _presenter_ is an object that is used by a _view_ to respond to user commands, and which uses a _model_ internally, updating the view with the results. MVP is appropriate when the user interacts with the view, such as a mobile app, and has the same goal as MVC: make code more maintainable, reusable, and testable. Example: ```java // Model class WeatherForecast { WeatherForecast(...) { ... } int getTemperature(...) { ... } } // View // Could have an interface if a single Presenter can use multiple Views, e.g., for testing, or for multiple app form factors class WeatherView { WeatherPresenter presenter; WeatherView(WeatherPresenter presenter) { this.presenter = presenter; presenter.setView(this); // ... configure the UI framework to call `onClick` when the user clicks } void start() { /* ... display the user interface ... */ } void onClick(...) { presenter.showTemperature(); } void showTemperature(int temperature) { // ... displays `temperature` ... } } // Presenter class WeatherPresenter { WeatherForecast forecast; WeatherView view; WeatherPresenter(...) { // Same remark as the MVC example concerning injection forecast = ...; } void setView(WeatherView view) { this.view = view; } void showTemperature() { int temperature = forecast.getTemperature(...); view.showTemperature(temperature); } } // Usage example: new WeatherView(new WeatherPresenter(...)).start(); ``` ## MVVM: Model-View-ViewModel A _viewmodel_ is a platform-independent user interface, which defines data, events for data changes using the _observer_ pattern, and commands. The viewmodel internally uses a _model_ to implement operations, and a _view_ can be layered on top of the viewmodel to display the data and interact with the user. MVVM is an evolution of MVP which avoids keeping state in the view, and which emphasizes the idea of a platform-independent user interface, instead of making the presenter/view interface match a specific kind of user interface such as a console app. Example: ```java // Model class WeatherForecast { WeatherForecast(...) { ... } int getTemperature(...) { ... } } // View // There is no need for an interface, because the viewmodel does not interact with the view, // thus there can be many different views for a viewmodel without any shared interface between them class WeatherView { WeatherViewModel viewModel; WeatherView(WeatherViewModel viewModel) { this.viewModel = viewModel; viewModel.registerForTemperatureChanges(showTemperature); // ... configure the UI framework to call `onClick` when the user clicks } void start() { /* ... display the user interface ... */ } void onClick(...) { viewModel.updateTemperature(); } void showTemperature() { // ... displays `this.viewModel.getTemperature()` ... // (or the viewmodel could pass the temperature as an argument directly) } } // ViewModel class WeatherViewModel { // No reference to a view! // Only an observer pattern enabling anyone (views, but also, e.g., unit tests) to register for changes WeatherForecast forecast; int temperature; Runnable temperatureCallback; WeatherViewModel(...) { // Same remark as the MVC example concerning injection forecast = ...; } // Data int getTemperature() { return temperature; } // Data change event void registerForTemperatureChanges(Runnable action) { this.temperatureCallback = action; } // Command void updateTemperature() { // In a real app, this operation would likely be asynchronous, // the viewmodel could perhaps have an "isLoading" property enabling views to show a progress bar int temperature = forecast.getTemperature(...); this.temperature = temperature; if (temperatureCallback != null) { temperatureCallback.run(); } } } // Usage example: new WeatherView(new WeatherViewModel(...)).start(); ```
CS-305: Software engineering
# Teamwork Working on your own typically means engineering a small application, such as a calculator. To design bigger systems, teams are needed, including not only engineers but also designers, managers, customer representatives, and so on. There are different kinds of tasks to do, which need to be sub-divided and assigned to people: requirements elicitation, design, implementation, verification, maintenance, and so on. This lecture is all about teamwork: who does what when and why? ## Objectives After this lecture, you should be able to: - Contrast different software development methodologies - Apply the Scrum methodology in a software development team - Divide tasks within a development team - Produce effective code reviews ## What methodologies exist to organize a project? We will see different methodologies, but let's start with one you may have already followed without giving it a name, _waterfall_. ### Waterfall In Waterfall, the team completes each step of the development process in sequence. Waterfall is named that way because water goes down, never back up. First requirements are written down, then the software is designed, then it is implemented, then it is tested, then it is released and maintained. Once a step is finished, its output is considered done and can no longer be modified, then the next step begins. There is a clear deadline for each task, and a specific goal, such as documents containing requirements or a codebase implementing the design. Waterfall is useful for projects that have a well-defined goal which is unlikely to change, typically due to external factors such as legal frameworks or externally-imposed deadlines. Projects that use Waterfall get early validation of their requirements, and the team is forced to document the project thoroughly during design. However, Waterfall is not a good fit if customer requirements aren't set in stone, for instance because the customers might change their mind, or because the target customers aren't even well-defined. The lack of flexibility can also result in inefficiencies, since steps must be completed regardless of whether their output is actually useful. Waterfall projects also delay the validation of the product itself until the release step, which might lead to wasted work if the software does not match what the customers expected. Typically, a project might use Waterfall if there are clear requirements that cannot change, using mature technologies that won't cause surprises along the way, with a team that may not have enough experience to take decisions on its own. ### Agile Agile is not a methodology by itself but a mindset born out of reaction to Waterfall's rigidity and formality, which is not a good fit for many teams including startups. The [Agile Manifesto](https://agilemanifesto.org/) emphasizes individuals and interactions, working software, customer collaboration, and responding to change, over processes and tools, comprehensive documentation, contract negotiation, and following a plan. In practice, Agile methods are all about iterative development in a way that lets the team get frequent feedback from customers and adjust as needed. ### Scrum Scrum is an Agile method that is all about developing projects in _increments_ during _sprints_. Scrum projects are a succession of fixed-length sprints that each produce a functional increment, i.e., something the customers can try and give feedback on. Sprint are usually a few weeks long; the team chooses at the start how long sprints will be, and that duration remains constant throughout the project. At the start of each sprint, the team assigns to each member tasks to complete for that sprint, and at the end the team meets with the customer to demo the increment. Scrum teams are multi-disciplinary, have no hierarchy, and should be small, i.e., 10 people or fewer. In addition to typical roles such as engineer and designer, there are two Scrum-specific roles: the "Scrum Master" and the "Product Owner". The Scrum Master facilitates the team's work and checks in with everyone to make sure the team is on pace to deliver the expected increment. The Scrum Master is _not_ a manager, they do not decide who does what. In general, a developer takes on the extra role of Scrum Master. The Product Owner is an internal representative for the customers, who formalizes and prioritizes requirements and converts them into a "Product Backlog" of items for the development team. The Product Backlog is a _sorted_ list of items, i.e., the most important are at the top. It contains both user stories and bugs. Because it is constantly sorted, new items might be inserted in any position depending on their priority, and the bottom-most items will likely never get done, because they are not important enough. For instance, the following items might be on a backlog: - "As an admin, I want to add a welcome message on the main page, so that I can keep my users informed" - "Bug: Impossible to connect if the user name has non-ASCII characters" - "As a player, I want to chat with my team in a private chat, so that I can discuss strategies with my team" To plan a sprint, the team starts by taking the topmost item in the Product Backlog and moves it to the "Sprint Backlog", which is the list of items they expect to complete in a sprint. The team then divides the item into development tasks, such as "add an UI to set the welcome message", "return the welcome message as part of the backend API", and "show the welcome message in the app". The team assigns each task a time estimate, dependent on its complexity, a "definition of done", which will be used to know when the task is finished, and a developer to implement the task. The "definition of done" represents specific expectations from the team, so that the person to which the task is assigned knows what they have to do. It can for instance represent a user scenario: "an admin should be able to go to the settings page and write a welcome message, which must be persisted in the database". This avoids misunderstandings between developers, e.g., Alice thought saving the message to the database was part of Bob's task and Bob thought Alice would do it. Tasks implicitly contain testing: whoever writes or modifies a piece of code is in charge of testing it, though the team might make specific decisions on specific kind of tests or test scenarios. During a sprint, the team members each work on their own tasks, and have a "Daily Scrum Meeting" at the start of each day. The Daily Scrum Meeting is _short_: it should last at most 15 minutes, preferably much less, and should only be attended by the development team including the Scrum Master, not by the Product Owner nor by any customer or other person. This meeting is also known as a "standup" meeting because it should be short enough that the team does not need to formally get a room and sit down. The Daily Scrum Meeting consists of each team member explaining what they've done in the previous day, what they plan to do this day, and whether they are blocked for any reason. Any such "blockers" can then be discussed _after_ the meeting is over, with only the relevant people. This way, all team members know each other's status, but they do not need to sit through meetings that are not relevant to them. Any bugs the team finds during the sprint should be either fixed on the spot if they are small enough, or reported to the Product Owner if they need more thought. The Product Owner will then prioritize these bugs in the Product Backlog. It is entirely normal that some bugs may stay for a while in the backlog, or even never be fixed, if they are not considered important enough compared to other things the team could spend time on. Importantly, the Sprint Backlog cannot be modified during a sprint. Once the team has committed to deliver a specific increment, it works only on that increment, in a small-scale version of Waterfall. If a customer has an idea for a change, they communicate it with the Product Owner, who inserts it at the appropriate position in the Product Backlog once the sprint is over. Once the sprint is over, the team demoes the resulting increment to the customer and any relevant stakeholders as part of a "Sprint Review" to get feedback, which can then be used by the Product Owner to add, remove, or edit Product Backlog items. The team then performs a "Sprint Retrospective" without the customer to discuss the development process itself. Once the Review and Retrospective are done, the team plans the next sprint and executes it, and the process starts anew. Scrum does not require all requirements to be known upfront, unlike Waterfall, which gives it flexibility. The team can change direction during development, since each sprint is an occasion to get customer feedback and act on it. The product can thus be validated often with the customer, which helps avoid building the wrong thing. However, Scrum does not impose any specific deadlines for the final product, and requires the existence of customers, or at least of someone who can play the role of customer if the exact customers are not yet known. It also does not fit well with micro-managers or specific external deadlines, since the team is in charge of its own direction. ### Other methodologies There are plenty of other software development methodologies we will not talk about in depth. For instance, the "[V Model](https://en.wikipedia.org/wiki/V-Model)" tries to represent Waterfall with more connections between design and testing, and the "[Spiral model](https://en.wikipedia.org/wiki/Spiral_model)" is designed to minimize risks. [Kanban](https://en.wikipedia.org/wiki/Kanban_(development)) is an interesting methodology that essentially takes Scrum to its logical extreme, centered on a board with tasks in various states that start from a sorted backlog and end in a "done" column. ## How can one effectively work in a team? The overall workflow of an engineer in a team is straightforward: create a branch in the codebase, work on it, then iterate on the work with feedback from the team before integrating the work in the codebase. This raises many questions. How can one form a team? How to be a "good" team member? How to divide tasks among team members? Team formation depends on development methodologies. In Scrum, teams are multi-disciplinary, i.e., there is no "user interface team" or "database team" but rather teams focused on an overall end-to-end product that include diverse specialists. Scrum encourages "two-pizza" teams, i.e., teams that could be fed with two large pizzas, so 4-8 people. Being a good team member requires three skills: communication, communication, and communication. Do you need help because you can't find a solution to a problem? Are you blocked because of factors outside of your control? Communicate! There are no winners on a losing team. It is not useful to write "perfect" code in isolation if it does not integrate with the rest of the team's code, or if there are other more important tasks to be done than the code itself, such as helping a teammate. A bug is never due to a single team member, since it implies the people who reviewed the code also made mistakes by not spotting the bug. Do not try to assign blame within the team for a problem, but instead communicate in a way that is the team vs. the problem. Dividing tasks within a team is unfortunately more of an art than a science, and thus requires practice to get right. If the tasks are too small, the overhead of each task's fixed costs is too high. If the tasks are too big, planning is hard because there are too many unknowns per task. One heuristic for task size is to think in terms of code review: what will the code for the task roughly look like, and how easy will that be to review? If the tasks are estimated to take more time than they really need, the team will run out of work to do and will need to plan again. If the tasks are estimated to take too little time, the team will not honor its deadlines. Estimating the complexity of a task is difficult and comes with experience. One way to do it is with "planning poker", in which team members write down privately their time estimate, then everyone reveals their estimate at once, the team discusses the results, and the process starts again until all team members independently agree. If the tasks are assigned to the wrong people, the team may not finish them on time because members have to spend too much time doing things they are not familiar with or do not enjoy doing. One key heuristic to divide tasks is to maximize parallelism while minimizing dependencies and interactions. If two people have to constantly meet in order to work, perhaps their tasks could be split differently so they need to meet less. Typically, a single task should be assigned to and doable by a single person. An important concept when assigning work within a team is the "bus factor": how many team members can be hit by a bus before the team can no longer continue working? This is a rather morbid way to look at it; one can also think of vacations, illnesses, or personal emergencies. Many teams have a bus factor of 1, because there is at least one member who is the only person with knowledge of some important task, password, or code. If this member leaves the team, gets sick, or is in any way incapacitated, the team grinds to a halt because they can no longer perform key tasks. Thus, tasks should be assigned such that nobody is the only person who ever does specific key tasks. One common mistake is to assign tasks in terms of application layers rather than end-to-end functionality. For instance, the entirety of the database work for a sprint in Scrum could be assigned to one person, the entirety of the UI work to another, and so on. However, if the database person cannot do their work, for instance because of illness, then no matter what other team members do, nothing will work end-to-end. Furthermore, if the same people are continuously assigned to the same layers, the bus factor becomes 1. Instead, team members should be assigned to features, such as one person in charge of user login, one in charge of informational messages, and one in charge of chat. Finally, another common mistake is to make unrealistic assumptions regarding time: everyone will finish on time, and little time is necessary to integrate the code from all tasks into the codebase. Realistically, some tasks will always be late due to incorrect estimations, illnesses, or other external factors. Integrating the code from all tasks also takes time and may require rework, because engineers may realize that they misunderstood each other and that they did not produce compatible code. It is necessary to plan for more time than the "ideal" time per task. ## How can one produce a useful code review? Code reviews have multiple goals. The most obvious one is to review the code for bugs, to stop bugs getting into the main branch of the codebase. Reviewers can also propose alternative solutions that may be more maintainable than the one proposed by the code author. Code review is also a good time for team members to learn about codebase changes. In 2013, [Bacchelli and Bird](https://dl.acm.org/doi/10.5555/2486788.2486882) found that knowledge transfer and shared code ownership were important reasons developers did code reviews in practice, right behind finding defects, improving the code, and proposing alternative solutions. Code reviews are cooperative, not adversarial. The point is not to try and find possible "backdoors" a colleague might have inserted; if you have a malicious colleague, code reviews are not the tool to deal with the problem. That is, unless your "colleague" is not a colleague but a random person on the Internet suggesting a change to your open source software, at which point you need to be more careful. ### Team standards and tools Each team must decide the standards with which it will review code, such as naming and formatting conventions and expected test coverage. Automate as much as possible: do not ask reviewers to check compliance with a specific naming convention if a static analyzer can do it, or to check the code coverage if a tool can run the tests and report the coverage. ### From the author's side To maximize the usefulness of the reviews you get as a code author, first review the code yourself to avoid wasting people's time with issues you could've found yourself, and then choose appropriate reviewers. For instance, you may ask a person who has worked for a while on that part of the codebase to chime in, as well as an expert on a specific subject such as security. Make it clear what you expect from the reviewers. Is this a "draft" pull request that you might heavily change? Is it a fix that must go in urgently and thus should get reviews as soon as possible? You also want to give reviewers a reasonable amount of code to review, ideally a few hundred lines of code at most. It's perfectly acceptable to open multiple pull requests in parallel for independent features, or to open pull requests sequentially for self-contained chunks of a single feature. ### From the reviewer's side Skim the code in its entirety first to understand what is going on, then read it in details with specific goals in mind, adding comments as you go. Finally, make a decision: does the code need changes or should it be merged as-is? If you request changes, perform another review once these are done. Since you might do multiple reviews, don't bother pointing out small issues if you are going to ask for major changes anyway. Sometimes you may also want to merge the code yet create a bug report for small fixes that should be performed later, if merging the code is important to unblock someone else. Evaluate the code in terms of correctness, design, maintainability, readability, and any other bar you think is important. For instance, do you think another developer could easily pick up the code and evolve it? If not, you likely want to explain why and what could be done to improve this aspect. When writing a comment, categorize it: are you requesting an important change? is it a small "nitpick"? is it merely a question for your own understanding? For instance, you could write "Important: this bound should be N+1, not N, because..." or "Question: could this code use the existing function X instead of including its own logic to do Y?". Be explicit: make it clear whether you are actually requesting a change, or merely doing some public brain-storming for potential future changes. Pick your battles: sometimes you may personally prefer one way to do it, but still accept what the author did instead of asking for small changes that don't really matter in the big picture. Remember to comment on _the code_, not _the person who wrote the code_. "Your code is insecure" is unnecessarily personal; "this method is insecure" avoids this problem. If you do not perform a thorough review of all of the code, specify what you did. It's perfectly fine to only check changes to code you already know, or to not be confident in evaluating specific aspects such as security or accessibility, but you must make this clear so that the code author does not get the wrong idea. There are plenty of guidelines available on the Internet that you might find useful, such as [Google's](https://google.github.io/eng-practices/review/reviewer/). ## Summary In this lecture, you learned: - Development methodologies, including Waterfall and especially Scrum - Dividing tasks within a team to maximize productivity and minimize conflicts - What code reviews are for and how to write one You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Testing > **Prerequisite**: Before following this lecture, you should make sure you can build and run the [sample project](exercises/sample-project). It's tempting to think that testing is not necessary if one "just" writes correct code from the first try and double-checks the code before running it. But in practice, this does not work. Humans make mistakes all the time. Even [Ada Lovelace](https://en.wikipedia.org/wiki/Ada_Lovelace), who wrote a correct algorithm to compute Bernoulli numbers for [Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage)'s "[Analytical Engine](https://en.wikipedia.org/wiki/Analytical_Engine)", made a typo by switching two variables in the code transcription of her algorithm. And she had plenty of time to double-check it, since the Analytical Engine was a proposed design by Babbage that was not actually implemented! The "first program ever" already contained a typo. One modern option is computer-aided verification, but it requires lots of time. If Ada Lovelace had lived in the 21st century, she could have written a proof and gotten a computer to check it, ensuring that the proof is correct as long as the prover program is itself correct. This can work in practice, but currently at the cost of high developer effort. The [seL4 operating system kernel](https://sel4.systems/), for instance, required 200,000 lines of proof for its 10,000 lines of code (Klein et al., ["seL4: formal verification of an OS kernel"](https://dl.acm.org/doi/10.1145/1629575.1629596)). Such a method might have worked for Ada Lovelace, an aristocrat with plenty of free time, but is not realistic yet for everyday programmers. Another modern option is to let users do the work, in a "beta" or "early access" release. Users get to use a program ahead of everyone else, at the cost of encountering bugs and reporting them, effectively making them testers. However, this only works if the program is interesting enough, such as a game, yet most programs out there are designed as internal tools for small audiences that are unlikely to want to beta test. Furthermore, it does not eliminate bugs entirely either. Amazon's "New World" game, despite having an "Open Beta" period, [released](https://www.denofgeek.com/games/new-world-bugs-glitches-exploits-list-cyberpunk-2077/) with many glitches including a 7-day delay before respawning. Do we even need tests in the first place? What's the worst that could happen with a bug? In some scenarios, the worst is not that bad comparatively, such as a bug in an online game. But imagine a bug in the course registration system of a university, leaving students wondering whether they are signed up to a course or not. Worse, a bug in a bank could make money appear or disappear at random. Even worse, bugs can be lethal, as in the [Therac-25 radiation therapy machine](https://en.wikipedia.org/wiki/Therac-25) which killed some patients. ## Objectives After this lecture, you should be able to: - Understand the basics of _automated testing_ - Evaluate tests with _code coverage_ - Identify _when_ to write which tests - _Adapt_ code to enable fine-grained testing ## What is a test? Testing is, at its core, three steps: 1. Set up the system 2. Perform an action 3. Check the outcome If the outcome is the one we expect, we gain confidence that the system does the right thing. However, "confidence" is not a guarantee. As [Edsger W. Dijkstra](https://en.wikipedia.org/wiki/Edsger_W._Dijkstra) once said, "_Program testing can be used to show the presence of bugs, but never to show their absence!_". The simplest way to test is manual testing. A human manually performs the workflow above. This has the advantage of being easy, since one only has to perform the actions that would be typically expected of users anyway. It also allows for a degree of subjectivity: the outcome must "look right", but one does not need to formally define what "looking right" means. However, manual testing has many disadvantages. It is slow: imagine manually performing a hundred tests. It is also error-prone: the odds increase with each test that a human will forget to perform one step, or perform a step incorrectly, or not notice that something is wrong. The subjectivity of manual testing is also often a disadvantage: two people may not agree on exactly what "right" or "wrong" is for a given test. Finally, it also makes it hard to test edge cases. Imagine testing that a weather app correctly shows snowfalls when they occur if it's currently sunny outside your home. To avoid the issues of manual testing, we will focus on automated testing. The workflow is fundamentally the same, but automated: 1. Code sets up the system 2. Code performs an action 3. Code checks the outcome These steps are commonly known as "Arrange", "Act", and "Assert". Automated testing can be done quickly, since computers are much faster than human, and do not forget steps or randomly make mistakes. This does not mean automated tests are always correct: if the code describing the test is wrong, then the test result is meaningless. Automated testing is also more objective: the person writing the test knows exactly what will be tested. Finally, it makes testing edge cases possible by programmatically faking the environment of the system under test, such as the weather forecast server for a weather app. There are other benefits to automated testing too: tests can be written once and used forever, everywhere, even on different implementations. For instance, the [CommonMark specification](https://spec.commonmark.org/) for Markdown parsers includes many examples that are used as tests, allowing anyone to use these tests to check their own parser. If someone notices a bug in their parser that was not covered by the standard tests, they can suggest a test that covers this bug for the next version of the specification. This test can then be used by everyone else. The number of tests grows and grows with time, and can reach enormous amounts such as [the SQLite test suite](https://www.sqlite.org/testing.html), which currently has over 90 million lines of tests. On the flip side, automated testing is harder than manual testing because one needs to spend time writing the test code, which includes a formal definition of what the "right" behavior is. ## How does one write automated tests? We will use Java as an example, but automated testing works the same way in most languages. The key idea is that each test is a Java method, and a test failure is indicated by the method throwing an exception. If the method does not throw exceptions, then the test passes. One way to do it using Java's built-in concepts is the following: ```java void test1plus1() { assert add(1, 1) == 2 } ``` If `add(1, 1)` returns `2`, then the assertion does nothing, the method finishes, and the test is considered to pass. But if it returns some other number, the assertion throws an `AssertionError`, which is a kind of exception, and the test is considered to fail. ...or, at least, that's how it should be, but [Java asserts are disabled by default](https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html), unfortunately. So this method does absolutely nothing unless the person running the test remembers to enable assertions. One could mimic the `assert` statement with an `if` and a `throw`: ```java void test1plus1() { if (add(1, 1) != 2) { throw new AssertionError() } } ``` This is a working implementation of a test, which we could run from a `main` method. However, if the test fails, there is no error message, since we did not put one when creating the `AssertionError`. For instance, if the test fails, what did `add(1, 1)` actually return? It would be good to know this. We could write code to store the result in a variable, test against that variable, and then create a message for the exception including that variable. Or we could use [JUnit](https://junit.org/junit5/) to do it for us: ```java @Test void test1plus1() { assertEquals(add(1, 1), 2); } ``` JUnit finds all methods annotated with `@Test` and runs them, freeing us from the need to write the code to do it ourselves, and throws exceptions whose message includes the "expected" and the "actual" value. ...wait, did we do that right? Should we have put the "expected" value first? It's hard to remember. And even if we do that part right, it's hard to make assertion messages useful for tests such as "this list should either be empty or contain `[1, 2, 3]`". We can write code to check that, but if the test fails we will get "expected `true`, but was `false`", which is not useful. Instead, let's use [Hamcrest](https://hamcrest.org/JavaHamcrest/) to write our assertions on top of JUnit: ```java @Test void test1plus1() { assertThat(add(1, 1), is(2)); } ``` This is much clearer! The `is` part is a Hamcrest "matcher", which describes what value is expected. `is` is the simplest one, matching exactly one value, but we can use fancier ones: ```java List<Integer> values = ...; assertThat(values, either(empty()) .or(contains(1, 2, 3))); ``` If this assertion fails, Hamcrest's exception message states "Expected: (an empty collection or iterable containing `[<1>, <2>, <3>]`) but: was `<[42]>`". Sometimes we need to test that a piece of code _fails_ in some circumstances, such as validating arguments properly and throwing an exception of an argument has an invalid value. This is what `assertThrows` is for: ```java var ex = assertThrows( SomeException.class, () -> someOperation(42) ); // ... test 'ex'... ``` The first argument is the type of exception we expect, the second is a function that should throw that type of exception. If the function does not throw an exception, or throws an exception of another type, `assertThrows` will throw an exception to indicate the test failed. If the function does throw an exception of the right type, `assertThrows` returns that exception so that we can test it further if needed, such as asserting some fact about its message. --- #### Exercise It's your turn now! Open [the in-lecture exercise project](exercises/lecture) and test `Functions.java`. Start by testing valid values for `fibonacci`, then test that it rejects invalid values. For `split` and `shuffle`, remember that Hamcrest has many matchers and has documentation. <details> <summary>Example solution (click to expand)</summary> <p> You could test `fibonacci` using the `is` matcher we discussed earlier for numbers such as 1 and 10, and test that it throws an exception with numbers below `0` using `assertThrows`. To test `split`, you could use Hamcrest's `contains` matcher, and for the shuffling function, you could use `arrayContainingInAnyOrder`. We provide some [examples](exercises/solutions/lecture/FunctionsTests.java). </p> </details> --- **Should you test many things in one method, or have many small test methods?** Think of what the tests output will look like if you combine many tests in one method. If the test method fails, you will only get one exception message about the first failure in the method, and will not know whether the rest of the test method would pass. Having big test methods also means the fraction of passing tests is less representative of the overall code correctness. In the extreme, if you wrote all assertions in a single method, a single bug in your code would lead to 0% of passing tests. Thus, you should prefer small test methods that each test one "logical" concept, which may need one or multiple assertions. This does not mean one should copy-paste large blocks of code between tests; instead, share code using features such as JUnit's `@BeforeAll`, `@AfterAll`, `@BeforeEach`, and `@AfterEach` annotations. **How can you test private methods?** You **don't**. Otherwise the tests must be rewritten every time the implementation changes. Think back to the SQLite example: the code would be impossible to change if any change in implementation details required modifying even a fraction of the 90 million lines of tests. **What standards should you have for test code?** The same as for the rest of the code. Test code should be in the same version control repository as other code, and should be reviewed just like other code when making changes. This also means tests should have proper names, not `test1` or `testFeatureWorks` but specific names that give information in an overview of tests such as `nameCanIncludeThaiCharacters`. Avoid names that use vague descriptions such as "correctly", "works", or "valid". ## What metric can one use to evaluate tests? What makes a good test? When reviewing a code change, how does one know whether the existing tests are enough, or whether there should be more or fewer tests? When reviewing a test, how does one know if it is useful? There are many ways to evaluate tests; we will focus here on the most common one, _coverage_. Test coverage is defined as the fraction of code executed by tests compared to the total amount of code. Without tests, it is 0%. With tests that execute each part of the code at least once, it is 100%. But what is a "part of the code"? What should be the exact metric for coverage? One naïve way to do it is _line_ coverage. Consider this example: ```java int getFee(Package pkg) { if (pkg == null) throw ...; int fee = 10; if (pkg.isHeavy()) fee += 10; if (pkg.isInternational()) fee *= 2; return fee; } ``` A single test with a non-null package that is both heavy and international will cover both lines. This may sound great since the coverage is 100% and easy to obtain, but it is not. If the `throw` was on a different line instead of being on the same line as the `if`, line coverage would no longer be 100%. It is not a good idea to define a metric for coverage that depends on code formatting. Instead, the simplest metric for test coverage is _statement_ coverage. In our example, the `throw` statement is not covered but all others are, and this does not change based on code formatting. Still, reaching almost 100% statement coverage based on a single test for the code above seems wrong. There are three `if` statements, indicating the code performs different actions based on a condition, yet we ignored the implicit `else` blocks in those ifs. A more advanced form of coverage is _branch_ coverage: the fraction of branch choices that are covered. For each branch, such as an `if` statement, 100% branch coverage requires covering both choices. In the code above, branch coverage for our single example test is 50%: we have covered exactly half of the choices. Reaching 100% can be done with two additional tests: one null package, and one package that is neither heavy nor international. But let us take a step back for a moment and think about what our example code can do: <p align="center"><img alt="Illustration of the paths in the code above; there are five, one throwing and four returning fee values" src="images/paths.svg" width="50%" /></p> There are five paths throughout the code, one of which fails. Yet, with branch coverage, we could declare victory after only three tests, leaving two paths unexplored. This is where path coverage comes in. Path coverage is the most advanced form of coverage, counting the fraction of paths throughout the code that are executed. Our three tests cover 60% of paths, i.e., 3 out of 5. We can reach 100% by adding tests for the two uncovered paths: a package that is heavy but not international, and one that is the other way around. Path coverage sounds very nice in theory. But in practice, it is often infeasible, as is obvious from the following example: ```java while (true) { var input = getUserInput(); if (input.length() <= 10) break; tellUser("No more than 10 chars"); } ``` The maximum path coverage obtainable for this code is _zero_. That's because there is an infinite number of paths: the loop could execute once, or twice, or thrice, and so on. Since one can only write a finite number of tests, path coverage is blocked at 0%. Even without infinite loops, path coverage is hard to obtain in practice. With just 5 independent `if` statements that do not return early or throw, one must write 32 tests. If 1/10th of the lines of code are if statements, a 5-million-lines program has more paths than there are atoms in the universe. And 5 million lines is well below what some programs have in practice, such as browsers. There is thus a tradeoff in coverage between feasibility and confidence. Statement coverage is typically easy to obtain but does not give that much confidence, whereas path coverage can be impossible to obtain in practice but gives a lot of confidence. Branch coverage is a middle ground. It is important to note that coverage is not everything. We could cover 100% of the paths in our "get fee" function above with 5 tests, but if those 5 tests do not actually check the value returned by the function, they are not useful. Coverage is a metric that should help you decide whether additional tests would be useful, but it does not replace human review. --- #### Exercise Run your tests from the previous exercise with coverage. You can do so either from the command line or from your favorite IDE, which should have a "run tests with coverage" command next to "run tests". Note that using the command line will run the [JaCoCo](https://www.jacoco.org/jacoco/) tool, which is a common way to get code coverage in Java. If you use an IDE, you may use the IDE's own code coverage tool, which could have minor differences in coverage compared to JaCoCo in some cases. ## When to test? Up until now we have assumed tests are written after development, before the code is released. This is convenient, since the code being tested already exists. But it has the risk of duplicating any mistakes found in the code: if an engineer did not think of an edge case while writing the code, they are unlikely to think about it while writing the tests immediately afterwards. It's also too late to fix the design: if a test case reveals that the code does not work because its design needs fundamental alterations, this will likely have to be done quickly under pressure due to a deadline, leading to a suboptimal design. If we simplify a product lifecycle to its development and its release, there are three times at which we could test: <p align="center"><img alt="Product lifecycle with 'development' followed by 'testing', and three times to test: before both, between both, or after both" src="images/lifecycle.svg" width="50%" /></p> The middle one is the one we have seen already. The two others may seem odd at first glance, but they have good reasons to exist. Testing before development is commonly known as **test-driven development**, or _TDD_ for short, because the tests "drive" the development, specifically the design of the code. In TDD, one first writes tests, then the code. After writing the code, one can run the tests and fix any bugs. This forces programmers to think before coding, instead of writing the first thing that comes to mind. It provides instant feedback while writing the code, which can be very gratifying: write some of the code, run the tests, and some tests now pass! This gives a kind of progress indication. It's also not too late to fix the design, since the design does not exist yet. The main downside of TDD is that it requires a higher time investment, and may even lead to missed deadlines. This is because the code under test must be written regardless of what tests are written. If too much time is spent writing tests, there won't be enough time left to write the code. When testing after development, this is not a problem because it's always possible to stop writing tests at any time, since the code already exists, at the cost of fewer tests and thus less confidence in the code. Another downside of TDD is that the design must be known upfront, which is fine when developing a module according to customer requirements but not when prototyping, for instance, research code. There is no point in writing a comprehensive test suite for a program if that program's very purpose will change the next day after some thinking. Let us now walk through a TDD example step by step. You are a software engineer developing an application for a bank. Your first task is to implement money withdrawal from an account. The bank tells you that "users can withdraw money from their bank account". This leaves you with a question, which you ask the bank: "can a bank account have a balance below zero?". The bank answers "no", that is not possible. You start by writing a test: ```java @Test void canWithdrawNothing() { var account = new Account(100); assertThat(account.withdraw(0), is(0)); } ``` The `new Account` constructor and the `withdraw` method do not exist, so you create a "skeleton" code that is only enough to make the tests _compile_, not pass yet: ```java class Account { Account(int balance) { } int withdraw(int amount) { throw new UnsupportedOperationException("TODO"); } } ``` You can now add another test for the "balance below zero" question you had: ```java @Test void noInitWithBalanceBelow0() { assertThrows(IllegalArgumentException.class, () -> new Account(-1)); } ``` This test does not require more methods in `Account`, so you continue with another test: ```java @Test void canWithdrawLessThanBalance() { var account = new Account(100); assertThat(account.withdraw(10), is(10)); assertThat(account.balance(), is(90)); } ``` This time you need to add a `balance` method to `Account`, with the same body as `withdraw`. Again, the point is to make tests compile, not pass yet. You then add one final test for partial withdrawals: ```java @Test void partialWithdrawIfLowBalance() { var account = new Account(10); assertThat(account.withdraw(20), is(10)); assertThat(account.balance(), is(0)); } ``` Now you can run the tests... and see them all fail! This is normal, since you did not actually implement anything. You can now implement `Account` and run the tests every time you make a change until they all pass. Finally, you go back to your customer, the bank, and ask what is next. They give you another requirement they had forgotten about: the bank can block accounts and withdrawing from a blocked account has no effect. You can now translate this requirement into tests, adding code as needed to make the tests compile, then implement the code. Once you finish, you will go back to asking for requirements, and so on until your application meets all the requirements. ---- #### Exercise It's your turn now! In [the in-lecture exercise project](exercises/lecture) you will find `PeopleCounter.java`, which is documented but not implemented. Write tests first then implement the code and fix your code if it doesn't pass the tests, in a TDD fashion. First, think of what tests to write, then write them, then implement the code. <details> <summary>Example tests (click to expand)</summary> <p> You could have five tests: the counter initializes to zero, the "increment" method increments the counter, the "reset" method sets the counter to zero, the "increment" method does not increment beyond the maximum, and the maximum cannot be below zero. We provide [sample tests](exercises/solutions/lecture/PeopleCounterTests.java) and [a reference implementation](exercises/solutions/lecture/PeopleCounter.java). </p> </details> ---- Testing after deployment is commonly known as **regression testing**. The goal is to ensure old bugs do not come back. When confronted with a bug, the idea is to first write a failing test that reproduces the bug, then fix the bug, then run the test again to show that the bug is fixed. It is crucial to run the test before fixing the bug to ensure it actually fails. Otherwise, the test might not actually reproduce the bug, and will "pass" after the bug fix only because it was already passing before, providing no useful information. Recall the SQLite example: all of these 90 million lines of code show that a very long list of possible bugs will not appear again in any future release. This does not mean there are no bugs left, but that many if not all common bugs have been removed, and that the rest are most likely unusual edge cases that nobody has encountered yet. ## How can one test entire modules? Up until now we have seen tests for pure functions, which have no dependencies on other code. Testing them is useful to gain confidence in their correctness, but not all code is structured as pure functions. Consider the following function: ```java /** Downloads the book with the given ID * and prints it to the console. */ void printBook(String bookId); ``` How can we test this? First off, the function returns `void`, i.e., nothing, so what can we even test? The documentation also mentions downloading data, but from where does this function do that? We could test this function by passing a book ID we know to be valid and checking the output. However, that book could one day be removed, or have its contents update, invalidating our test. Furthermore, tests that depend on the environment such as the book repository this function uses cannot easily test edge cases. How should we test what happens if there is a malformed book content? Or if the Internet connection drops after downloading the table of contents but before downloading the first chapter? One could design _end-to-end tests_ for this function: run the function in a custom environment, such as a virtual machine whose network requests are intercepted, and parse its output from the console, or perhaps redirect it to a file. While end-to-end testing is useful, it requires considerable time and effort, and is infrastructure that must be maintained. Instead, let's address the root cause of the problem: the input and output to `printBook` are _implicit_, when they should be _explicit_. Let's make the input explicit first, by designing an interface for HTTP requests: ```java interface HttpClient { String get(String url); } ``` We can then give an `HttpClient` as a parameter to `printBook`, which will use it instead of doing HTTP requests itself. This makes the input explicit, and also makes the `printBook` code more focused on the task it's supposed to do rather than on the details of HTTP requests. Our `printBook` function with an explicit input thus looks like this: ```java void printBook( String bookId, HttpClient client ); ``` This process of making dependencies explicit and passing them as inputs is called **dependency injection**. We can then test it with whatever HTTP responses we want, including exceptions, by creating a fake HTTP client for tests: ```java var fakeClient = new HttpClient() { @Override public String get(String url) { ... } } ``` Meanwhile, in production code we will implement HTTP requests in a `RealHttpClient` class so that we can call `printBook(id, new RealHttpClient(...))`. We could make the output explicit in the same way, by creating a `ConsolePrinter` interface that we pass as an argument to `printBook`. However, we can change the method to return the text instead, which is often simpler: ```java String getBook( String bookId, HttpClient client ); ``` We can now test the result of `getBook`, and in production code feed it to `System.out.println`. Adapting code by injecting dependencies and making outputs explicit enables us to test more code with "simple" tests rather than complex end-to-end tests. While end-to-end tests would still be useful to ensure we pass the right dependencies and use the outputs in the right way, manual testing for end-to-end scenarios already provides a reasonable amount of confidence. For instance, if the code is not printing to the console at all, a human will definitely notice it. This kind of code changes can be done recursively until only "glue code" between modules and low-level primitives remain untestable. For instance, an "UDP client" class can take an "IP client" interface as a parameter, so that the UDP functionality is testable. The implementation of the "IP client" interface can itself take a "Data client" interface as a parameter, so that the IP functionality is testable. The implementations of the "Data client" interface, such as Ethernet or Wi-Fi, will likely need end-to-end testing since they do not themselves rely on other local software. --- #### Exercise It's your turn now! In [the in-lecture exercise project](exercises/lecture) you will find `JokeFetcher.java`, which is not easy to test in its current state. Change it to make it testable, write tests for it, and change `App.java` to match the `JokeFetcher` changes and preserve the original program's functionality. Start by writing an interface for an HTTP client, implement it by moving existing code around, and use it in `JokeFetcher`. Then add tests. <details> <summary>Suggestions (click to expand)</summary> <p> The changes necessary are similar to those we discussed above, including injecting an `HttpClient` dependency and making the function return a `String`. We provide [an example `JokeFetcher`](exercises/solutions/lecture/JokeFetcher.java), [an example `App`](exercises/solutions/lecture/App.java), and [tests](exercises/solutions/lecture/JokeFetcherTests.java). </p> </details> ---- If you need to write lots of different fake dependencies, you may find _mocking_ frameworks such as [Mockito](https://site.mockito.org/) for Java useful. These frameworks enable you to write a fake `HttpClient`, for instance, like this: ```java var client = mock(HttpClient.class); when(client.get(anyString())).thenReturn("Hello"); // there are also methods to throw an exception, check that specific calls were made, etc. ``` There are other kinds of tests we have not talked about in this lecture, such as performance testing, accessibility testing, usability testing, and so on. We will see some of them in future lectures. ## Summary In this lecture, you learned: - Automated testing, its basics, some good practices, and how to adapt code to make it testable - Code coverage as a way to evaluate tests, including statement coverage, branch coverage, and path coverage - When tests are useful, including testing after development, TDD, and regression tests You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Mobile Platforms This lecture's purpose is to give you a high-level picture of what the universe of mobile applications and devices is like. You will read about: * Differences between desktops and mobile devices w.r.t. applications, security, energy, and other related aspects * Challenges and opportunities created by mobile platforms * Brief specifics of the Android stack and how applications are structured * A few ideas for offering users a good experience on their mobile * The ecosystem that mobile apps plug into ## From desktops to mobiles Roughly every decade, a new, lower priced computer class forms, based on a new programming platform, network, and interface. This results in new types of usage, and often the establishment of a new industry. This is known as [Bell's Law](https://en.wikipedia.org/wiki/Bell%27s_law_of_computer_classes). With every new computer class, the number of computers per person increases drastically. Today we have clouds of vast data centers, and perhaps an individual computer, like our laptop, that we use to be productive. On top of that come several computer devices per individual, like phones, wearables, and smart home items, which we use for entertainment, communication, quality of life, and so on. It is in this context that mobile software development becomes super-important. We said earlier that, no matter what job you will have, you will write code. We can add to that: you will likely write code for mobile devices. There are more than 15 billion mobile devices operating worldwide, and that number is only going up. As Gordon Bell said, this leads to new usage patterns. We access the Internet more often from our mobile than our desktop or laptop. Most of the digital content we consume we do so on mobiles. We spend hours a day on our mobile, and the vast majority of that time we spend in apps, not on websites. A simple example of a major change in how we use computing and communication is social media. Most of the world's population uses it. It changes how we work. Even the professional workforce is increasingly dependent on mobiles, for this reason. ### Mobile vs. desktop: Applications There are many differences between how we write applications for a mobile device vs. a desktop computer. On a desktop, applications can do pretty much whatever they want, whereas, on a mobile, each app is super-specialized. On the desktop, users explicitly starts applications; on mobile, the difference between running or not is fluid: apps can be killed anytime, and they need to be ready to restart. On a desktop, you typically have multiple applications active in the foreground, with multiple windows on-screen. The mobile experience is difference: a user's interaction with an app doesn't always begin in the same place, but rather the user's journey often begins non-deterministically. As a result, a mobile app has a more complex structure than a traditional desktop application, with multiple types of components and entry points. The execution model on mobiles is more cooperative than on a desktop. For example, a social media app allows you to compose an email, and does so by reusing the email app. Another example is something like WhatsApp, which allows you to take pictures (and does so by asking the Photo app to do it). In essence, apps request services from other apps, and they build upon the functionality of others, which is fundamentally difference from the desktop application paradigm. ### Mobile vs. desktop: Operating environment One of the biggest differences is in the security model. Think of your parents' PC at home or in an Internet café: there are potentially multiple users that don’t trust each other, each have specific file permissions, every application by default inherits all of a user's permissions, all applications are trusted to run with user's privileges alongside each other. The operating system prevents one application from overwriting others, but does not protect the I/O resources (e.g., files). One could fairly say that security is somewhat of an afterthought on the desktop. A mobile OS has considerably stronger isolation. The assumption here is that users might naively install malicious apps, and the goal is to protect users’ data (and privacy) even when they do stupid things. So, each mobile app is sandboxed separately. When you install a mobile app, it will ask the device for necessary permissions, like access to contacts, camera, microphone, location information, SMS, WiFi, user accounts, body sensors, etc. A mobile device is more constrained, e.g., you don't really get "root" access. It provides strong hardware-based isolation and powerful authentication features (like face recognition). E.g., for iPhone's FaceID, the face scan pattern is encrypted and sent to a secure hardware "enclave" in the CPU, to make sure that stored facial data is inaccessible to any party, including Apple. Power management is a first-class citizen in a mobile OS. While PCs use high-power CPUs and GPUs with heatsinks, smartphones and tablets are typically not plugged in, so they cannot provide sustained high power. On a mobile, the biggest energy hog is typically the screen, whereas in a desktop it is the CPU and GPU. Desktop OSes tend to be generic, whereas mobile OSes specialize for a given set of mobile devices, so they can have strict hardware requirements. This leads to less backward compatibility, and so the latest apps will not run on older versions of the OS, and new versions of a mobile OS won't run on older devices. There is also orders-of-magnitude less storage on mobiles, and orders-of-magnitude less memory. Plus, you cannot easily expand / modify storage and memory. Mobile networking tends to be more intermittent than in-wall connectivity. An Ethernet connections gives you Gbps, while a WiFi connection gives you Mbps. On a desktop, the input comes typically from a keyboard and a mouse, whereas mobiles have small touch keyboards, voice commands, complex gestures, etc. Output is also limited on mobiles, so often they communicate with other devices to achieve their output. We are witnessing today a convergence between desktop and mobile OSes, which will gradually make desktops disappear, and computing will become increasingly more embedded. ### Challenges and opportunities This new world of mobile presents both opportunities and challenges. Users are many more, and are more diverse. They have widely differing computer skills. Developers need to focus on ease of use, internationalization, and accessibility. Platforms are more diverse (think phones, wearables, TVs, cars, e-book readers). Different vendors take different approaches to dealing with this diversity: Apple has the "walled garden" approach, while Android is more like the wild west: Android is open-source, so OEMs (original equipment manufacturers) can customize Android to their devices, so naturally Android runs on tens of thousands of models of devices today. Mobiles get interesting new kinds of inputs, from multi-touch screens, accelerometers, GPS. But they also face serious limitations in terms of screen size, processor power, and battery capacity. Mobile devices need to (and can be) managed more tightly. Today you can remote-lock a device, you can locate the device, and with software like MDM (mobile device management) you can do everything on the device remotely. Some mobile carriers even block users from installing certain apps on their devices. App stores or Play stores are digital storefronts for content consumed on device. Today, the success of a mobile platform depends heavily on its app store, which becomes a central hub for content to be consumed on that particular mobile platform. The operator of the store controls apps published in the store (e.g., disallow sexually explicit content, violence, hate speech, anything illegal), which means that the developer needs to be aware of rules and laws in the places where app will be used. Operators typically use automated tools and human reviewers to check apps for malware and terms-of-service violations. ## How does a mobile operating environment work? A mobile device aims to achieve seemingly contradictory goals: On the one hand, it aims for greater integration than a desktop, to create a more cooperative ecosystem in which to enable apps to provide services to each other. On the other hand, it aims for greater isolation, it wants to offer a stronger sandbox, to protect user data, and to restrict apps from interacting in more complex ways Each mobile OS makes its own choices for how to do this. In this lecture, we chose to focus on Android, for three reasons: * it is open-source, so it's easier to understand what it really does * over 70% of mobiles use Android, there are more than 2.5 billion Android users and more than 3 billion active Android devices, so this is very real * we will use it in the follow-on course [Software Development Project](https://dslab.epfl.ch/teaching/sweng/proj) Android is based on Linux, and things like multi-threading and low-level memory management are all provided by the Linux kernel. There is a layer, called the hardware abstraction layer (HAL), that provides standard interfaces to specific hardware capabilities, such as the camera or the Bluetooth module. Whenever an application makes a call to access device hardware, Android loads a corresponding library module from the HAL for that hardware component. Above the HAL, there is the Android runtime (ART) and the Native C/C++ libraries. The ART provides virtual machines for executing DEX (Dalvik executable) bytecode, which is specially designed to have a minimal memory footprint. Java code gets turned into DEX bytecode, which can run on the ART. Android apps can be written in Kotlin, Java, or even C++. The Android SDK (software development kit) tools compile code + resource files into a so-called Android application package (APK), which is an archive used to install the app. When publishing to the Google Play app store, one generates instead an Android app bundle (ABB), and then Google Play itself generates optimized APKs for the target device that is requesting installation of the app. This is a more practical approach than having the developer produce individual APKs for each device. Each Android app lives in its own security sandbox. In Linux terms, each app gets its own user ID. Permissions for all the files accessed by the app are set so that only the assigned user ID can access them. It is possible for apps to share data and access each other's files, in which case they get the same Linux user ID; the apps however must be from the same developer (i.e., signed with the same developer certificate). Each app runs in its own Linux process. By default, an app can access only the components that it needs to do its work and no more (this follows the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege)). An app can access the device's location, camera, Bluetooth connection, etc. as long as the phone user has explicitly granted it these permissions. Each app has its own instance of the ART, with its own VM to execute DEX bytecode. In other words, apps don't run inside a common VM. In Android, the UI is privileged. Foreground and UI threads get higher priority in CPU scheduling than the other threads. Android uses process containers (a.k.a., [Linux cgroups](https://en.wikipedia.org/wiki/Cgroups)) to allocate a higher percentage of the CPU to them. When users switch between apps, Android keeps non-foreground apps (e.g., not visible to the user) in a cache (in Linux terms, the corresponding processes do not terminate) and, if the user returns to the app, the process is reused, which makes app switching faster. Many core system components (like the ART and HAL) require native libraries written in C/C++. Android provides Java APIs to expose the functionality of these native libraries to apps. This Java APIs framework is layered on top of the ART and native C/C++ libraries. Apps written in C/C++ can use the native libraries directly (this requires the Android native development kit, or NDK). Within the Java API framework, there are a number of Android features provided through APIs written in Java that provide key building blocks for apps. For example, the View System is used for building the UI. E.g., the Resource Manager is used by apps for accessing localized strings or graphics. E.g., the Activity Manager handles the lifecycle of apps and provides a common navigation back stack (more on this below). And, as a final example, Content Providers enable apps to access data from other apps (e.g., a social media app access the Contacts app) or to share their own data. On top of this entire stack are the apps. Android comes with core apps for email, SMS, calendaring, web browsing, contacts, etc. but these apps have no special status, then can be replaced with third-party apps. The point of shipping them with Android is to provide key capabilities to other apps out of the box (e.g., allow multiple apps to have the functionality of sending an SMS without having to write the code for it). An Android app is a collection of components, with each component providing an entry point to the app. There are 4 main components: * An _Activity_ provides an entry point with a UI, for interacting with the user. An activity represents a single screen with a user interface. For example, an email app has an activity to show a list of new emails, another activity to compose an email, another activity to read emails, and so on -- activities work together to form the email app, but each one is independent of the others. Unlike in desktop software, other apps can start any one of these activities if the email app allows it, e.g., the Camera app may start the compose-email activity in order to send a picture by email. * A _Service_ is a general-purpose entry point without a UI. This essentially keeps an app running in the background (e.g., play music in the background while the user is in a different app, or fetch data over the network without blocking user interaction with an activity). A service can also be started by another component. * A _Broadcast Receiver_ enables Android to deliver events to apps out-of-band, e.g., an app may set a timer and ask Android to wakes it up at some point in the future; this way, the app need not run non-stop until then. So broadcasts can be delivered even to apps that aren't currently running. Broadcast events can be initiated by the OS (e.g., the screen turned off, battery is low, picture was taken) or can be initiated by apps (e.g., some data has been downloaded and is available for other apps to use). Broadcast receivers have no UI, but they can create a status bar notification to alert the user. * A _Content Provider_ manages data that is shared among apps. Such data can be local (e.g., file system, SQLite DB) or remote on some server. Through a content provider, apps can query / modify the data (e.g., the Contacts data is a content provider: any app with the proper permissions can get contact info and can write contact info). Remember that any app can cause another app’s component to start. For instance, if WhatsApp wants to take a photo with the camera, it can ask that an activity be started in the Camera app, without the WhatsApp developer having to write the code to take photos--when done, the photo is returned to WhatsApp, and to the user it appears as if the camera is actually a part of WhatsApp. To start a component, Android starts the process for target app (if not already running), instantiates the relevant classes (this is because, e.g., the photo-taking activity runs in the Camera process, not WhatsApp's process). You see here an example of multiple entry points: there is no `main()` like in a desktop app. Then, to activate a component in another app, you must create an _Intent_ object, which is essentially a message that activates either a specific component (explicit intent) or a type of component (implicit intent). For activities and services, the intent defines the action to perform (e.g., view or send something) and specifies the URI of the data to act on (e.g., this is an intent to dial a certain phone number). If the activity returns a result, it is returned in an Intent (e.g., let the user pick a contact and return a URI pointing to it). For broadcast receivers, the intent defines the announcement being broadcast (e.g., if battery is low it includes the BATTERY_LOW string), and a receiver can register for it by filtering on the string. Content providers are not activated by intents but rather when targeted by a request from what's called a Content Resolver, which handles all interaction with the content provider. ## A mobile app: Structure and lifecycle The centerpiece of an Android app is the _activity_. Unlike the kinds of programs you've been writing so far, there is no `main()`, but rather the underlying OS initiates code in an _Activity_ by invoking specific callback methods. An activity provides the window in which the app draws its UI. One activity essentially implements one screen in an app, e.g., 1 activity for a Preferences screen, 1 activity for a Select Photo screen, etc. Apps contain multiple screens, each of which corresponds to an activity. One activity is specified as the main activity, i.e., the first screen to appear when you launch the app. Each activity can then start another activity, e.g., the main activity in an email app may provide the screen that shows your inbox, then you have screens for opening and reasing a message, one for writing, etc. As a user navigates through, out of, back into an app, the activities in the app transition through diff states. Transitioning from one state to another is handled by specific callbacks that must be implemented in the activity. The activity learns about changes and reacts to when the user leaves and re-enters the activity: For example, a streaming video player will likely pause the video and terminate the network connection when the user switches to another app; when the user returns to the app, it will reconnect to the network and allow the user to resume the video from the same spot. To understand the lifecycle of an activity, please see [the Android documentation](https://developer.android.com/guide/components/activities/activity-lifecycle). Another important element are _fragments_. These provide a way to modularize an activity's UI and reuse modules across different activities. This provides a productive and efficient way to respond to various screen sizes, or whether your phone is in portrait or landscape mode, where the UI is composed differently but from the same modules. A fragment may show the list of emails, and another fragment may display an email thread. On a phone, you would display only one at a time, and upon tap switch to the next activity. On a tablet, with the greater screen real estate, you have room for both. By modularizing the UI into fragments, it's easy to adapt the app to the different layouts by rearranging fragments within the same view when the phone switches from portrait to landscape mode. To understand fragments, please see [the Android documentation](https://developer.android.com/guide/fragments). You don't have to use fragments within activities, but such modularization makes the app more flexible and also makes it easier to maintain over time. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. But it cannot live on its own, it needs to be hosted by an activity or another fragment. Android beginners tend to put all their logic inside Activities and Fragments, ending up with "views" that do a lot more than just render the UI. Remember what we said about MVVM and how that maps to how you build an Android app. In the exercise set, we will ask you to go through an MVVM exercise. Android provides a nice ViewModel class to store and manage UI-related data. ## User experience (UX) User experience design (or "UX design") is about putting together an intuitive, responsive, navigable, usable interface to the app. You want to look at the app through the users' perspective to derive what can give them an easy, logical and positive experience. So you must ask who is your audience: Old or young people? Intellectuals or blue-collar workers? Think back to the lecture on personas and user stories. The UI should enable the user to get around the app easily, and to find quickly what they're looking for. To achieve this, several elements and widgets have emerged from the years of experience of building mobile apps. The [hamburger icons](https://en.wikipedia.org/wiki/Hamburger_button) are used for drop-down menus with further details--they avoid clutter. Home buttons give users a shortcut to home base. Chat bubbles offer quick help through context-sensitive messages. Personalization of the UI allows adapting to what the user is interested in, keeping the unrelated content away. For example, in the [EPFL Campus app](https://pocketcampus.org/epfl-en) you can select which features you see on the home screen, and so the home screen of two different users is likely to look different. In order to maximize readability, emphasize simplicity and clarity, choose adequate font size and image size. Avoid having too many elements on the screen, because that leads to confusion. Offer one necessary action per screen. Use [micro UX animations](https://uxplanet.org/ui-design-animations-microinteractions-50753e6f605c), which are little animations that appear when a specific action is performed or a particular item is hovered or touched; this can increase engagement and interactivity. E.g., hovering over a thumbnail shows details about it. E.g., hover zoom for maximizing the view of a specific part of something. Keep however the animations minimal, avoid flashiness, make them subtle and clear as to their intent. Keep in mind _thumb zones_. People use their mobile when they’re standing, walking, riding a bus, so the app should allow them to hold the device and view its screen and provide input in all these situations. So make it easy for the user to reach with their thumb the stuff they do most often. Leverage gesture controls to make it easy for a user to interact with apps--e.g., “holding” an item, “dragging” it to a container, and then “releasing”--but beware to do what users of that device are used to doing, not exotic stuff. Think of augmented reality and voice interaction, depending on the app, they can be excellent ways to interact with the device. ## The mobile ecosystem A modern mobile app, no matter how good it is, can hardly survive without plugging into its ecosystem. Most mobile apps are consists of the phone side of the app and the cloud side. Apps interact with cloud services typically over REST APIs, which is an architectural style that builds upon HTTP and JSON to offer CRUD (copy-read-update-delete) operations on objects that are addressed by a URI. You use HTTP methods to access these resources via URL-encoded parameters. Aside from the split architecture, apps also interact with the ecosystem through Push notifications. These are automated messages sent to the user by the server of the app that’s working in the background (i.e., not currently open). Each OS (e.g., Android, iOS) has its own push notification service with a specific API that apps can use, and they each operate a push engine in the cloud. The app developer enables their app with push notifications, at which point the app can start receiving incoming notifications. When you open the app, unique IDs for both the app and the device are created by the OS and registered with the OS push notification service. IDs are passed back to the app and also sent to the app publisher. The in-cloud service generates the message (either when a publisher produces it, or in response to some event, etc.) which can be targeted at users or a group of users and gets sent to the corresponding mobile. On Android, an incoming notification can create an Activity. A controversial aspect of the ecosystem is the extent to which it track the device and the user of the device. We do not discuss this aspect here in detail, it is just something to be aware of. A key ingredient of "plugging into" the ecosystem is the network. Be aware that your users may experience different bandwidth limitations (e.g., 3G vs. 5G), and the Internet doesn't work as smoothly everywhere in the world as we're used to. In addition to bandwidth issues, there is also the risk of experiencing a noticeable disconnection from the Internet. E.g., a highly interactive, graphic-heavy app will not be appropriate for apps that target Latin America or Africa, or users in rural areas, because today there are still many areas with spotty connectivity. Perhaps a solution can be offered by the new concept of fog computing (as opposed to cloud computing), also called edge computing. It is about the many "peripheral" devices that connect to the periphery of a cloud, and many of these devices will generate lots of raw data (e.g., from sensors). Rather than forward this data to cloud-based servers, one could do as much processing as possible using computing units nearby, so that processed rather than raw data is forwarded to the cloud. As a result, bandwidth requirements are reduced. "The Fog" can support the Internet of Things (IoT), including phones, wearable health monitoring devices, connected vehicle and augmented reality devices. IoT devices are often resource-constrained and have limited computational abilities to perform, e.g., cryptography computations, so a fog node nearby can provide security for IoT devices by performing these cryptographic computations instead. ## Summary In this lecture, you learned: * Several ways in which a desktop app differs from a mobile app * How security, energy, and other requirements change when moving from a desktop to a mobile * How activities and fragments work in Android apps * The basics of good UX * How mobile apps can leverage their ecosystem You can now check out the [exercises](exercises/).
CS-305: Software engineering
# Evolution Imagine you are an architect asked add a tower to a castle. You know what towers look like, you know what castles look like, and you know how to build a tower in a castle. This will be easy! But then you get to the castle, and it looks like this: <p align="center"><img alt="Howl's Moving Castle from the movie of the same name: a messy 'castle' on legs" src="images/castle.jpg" width="50%" /></p> Sure, it's a castle, and it fulfills the same purpose most castles do, but... it's not exactly what you had in mind. It's not built like a standard castle. There's no obvious place to add a tower, and what kind of tower will this castle need anyway? Where do you make space for a tower? How do you make sure you don't break half the castle while adding it? This lecture is all about evolving an existing codebase. ## Objectives After this lecture, you should be able to: - Find your way in a _legacy codebase_ - Apply common _refactorings_ to improve code - Document and quantify _changes_ - Establish solid foundations with _versioning_ ## What is legacy code, and why should we care? "Legacy code" really means "old code that we don't like". Legacy code may or may not have documentation, tests, and bugs. If it has documentation and tests, they may or may not be complete enough; tests may even already be failing. One common reaction to legacy code is disgust: it's ugly, it's buggy, why should we even keep it? If we rewrote the code from scratch we wouldn't have to ask all of these questions about evolution! It certainly sounds enticing. In the short term, a rewrite feels good. There's no need to learn about old code, instead you can use the latest technologies and write the entire application from scratch. However, legacy code works. It has many features, has been debugged and patched many times, and users rely on the way it works. If you accidentally break something, or if you decide that some "obscure" feature is not necessary, you will anger a lot of your users, who may decide to jump ship to a competitor. One infamous rewrite story is [that of Netscape 5](https://www.joelonsoftware.com/2000/04/06/things-you-should-never-do-part-i/). In the '90s, Netscape Navigator was in tough competition with Microsoft's Internet Explorer. While IE became the butt of jokes later, at the time Microsoft was heavily invested in the browser wars. The Netscape developers decided that their existing Netscape 4 codebase was too old, too buggy, and too hard to evolve. They decided to write Netscape 5 from scratch. The result is that it took them three years to ship the next version of Netscape; in that time, Microsoft had evolved their existing IE codebase, far outpacing Netscape 4, and Netscape went bankrupt. Most rewrites, like Netscape, fail. A rewrite means a loss of experience, a repeat of many previous mistakes, and that's just to get to the same point as the previous codebase. There then needs to be time to add features that justify the cost of upgrading to users. Most rewrites run out of time or money and fail. It's not even clear what "a bug" is in legacy code, which is one reason rewrites are dangerous: some users depend on things that might be considered "bugs". For instance, Microsoft Excel [treats 1900 as a leap year](https://learn.microsoft.com/en-us/office/troubleshoot/excel/wrongly-assumes-1900-is-leap-year) even though it is not, because back when it was released it had to compete with a product named Lotus 1-2-3 that did have this bug. Fixing the bug means many spreadsheets would stop working correctly, as dates would become off by one. Thus, even nowadays, Microsoft Excel still contains a decades-old "bug" in the name of compatibility. A better reaction to legacy code is to _take ownership of it_: if you are assigned to a legacy codebase, it is now your code, and you should treat it just like any other code you are responsible for. If the code is ugly, it is your responsibility to fix it. ## How can we improve legacy code? External improvements to an existing codebase, such as adding new features, fixing bugs, or improving performance, frequently require internal improvements to the code first. Some features may be difficult to implement in an existing location, but could be much easier if the code was improved first. This may require changing design _tradeoffs_, addressing _technical debt_, and _refactoring_ the codebase. Let's see each of these in detail. ### Tradeoffs Software engineers make tradeoffs all the time when writing software, such as choosing an implementation that is faster at the cost of using more memory, or simpler to implement at the cost of being slower, or more reliable at the cost of more disk space. As code ages, its context changes, and old tradeoffs may no longer make sense. For instance, Windows XP, released in 2001, groups background services into a small handful of processes. If any background service crashes, it will cause all of the services in the same process to also crash. However, because there are few processes, this minimizes resource use. It would have been too much in 2001, on computers with as little as 64 MB of RAM, to dedicate one process and the associated overheads per background service. But in 2015, when Windows 10 was released, computers typically had well over 2 GB of RAM. Trading reliability for low resource use no longer made sense, so Windows 10 instead runs each background service in its own process. The cost of memory is tiny on the computers Windows 10 is made for, and the benefits from not crashing entire groups of services at a time are well worth it. The same choice made 15 years apart yielded a different decision. ### Technical debt The cost of all of the "cheap" and "quick" fixes done to a codebase making it progressively worse is named _technical debt_. Adding one piece of code that breaks modularity and hacks around the code's internals may be fine to meet a deadline, but after a few dozen such hacks, the code becomes hard to maintain. The concept is similar to monetary debt: it can make sense to invest more money than you have, so you borrow money and slowly pay it back. But if you don't regularly pay back at least the interest, your debt grows and grows, and so does the share of your budget you must spend on repaying your debt. You eventually go bankrupt from the debt payments taking up your entire budget. With technical debt, a task that should take hours can take a week instead, because one now needs to update the code in the multiple places where it has been copy-pasted for "hacks", fix some unrelated code that in practice depends on the specific internals of the code to change, write complex tests that must set up way more than they should need, and so on. You may no longer be able to use the latest library that would solve your problem in an hour, because your codebase is too old and depends on old technology the library is not compatible with, so instead you need weeks to reimplement that functionality yourself. You may regularly need to manually reimplement security patches done to the platform you use because you use an old version that is no longer maintained. This is one reason why standards are useful: using a standard version of a component means you can easily service it. If you instead have a custom component, maintenance becomes much more difficult, even if the component is nicer to work with at the beginning. ### Refactoring Refactoring is the process of making _incremental_ and _internal_ improvements. These are improvements designed to make code easier to maintain, but that do not directly affect end users. Refactoring is about starting from a well-known code problem, applying a well-known solution, and ending up with better code. The well-known problems are sometimes called "code smells", because they're like a strange smell: not harmful on its own, but worrying, and could lead to problems if left unchecked. For instance, consider the following code: ```java class Player { int hitPoints; String weaponName; int weaponDamage; boolean isWeaponRanged; } ``` Something doesn't smell right. Why does a `Player` have all of the attributes of its weapon? As it is, the code works, but what if you need to handle weapons independently of players, say, to buy and sell weapons at shops? Now you will need fake "players" that exist just for their weapons. You'll need to write code that hides these players from view. Future code that deals with players may not handle those "fake players" correctly, introducing bugs. Pay some of your technical debt and fix this with a refactoring: extract a class. ```java class Player { int hitPoints; Weapon weapon; } class Weapon { ... } ``` Much better. Now you can deal with weapons independently of players. Your `Weapon` class now looks something like this: ```java class Weapon { boolean isRanged; void attack() { if (isRanged) { ... } else { ... } } } ``` This doesn't smell right either. Every method on `Weapon` will have to first check if it is ranged or not, and some developers might forget to do that. Refactor it: use polymorphism. ```java abstract class Weapon { abstract void attack(); } class MeleeWeapon extends Weapon { ... } class RangedWeapon extends Weapon { ... } ``` Better. But then you look at the damage calculation... ```java int damage() { return level * attack - max(0, armor - 500) * attack / 20 + min(weakness * level / 10, 400); } ``` What is this even doing? It's hard to tell what was intended and whether there's any bug in there, let alone to extend it. Refactor it: extract variables. ```java int damage() { int base = level * attack; int resistance = max(0, armor - 500) * attack / 20; int bonus = min(weakness * level / 10, 400); return base - resistance + bonus; } ``` This does the same thing, but now you can tell what it is: there's one component for damage that scales with the level, one component for taking the resistance into account, and one component for bonus damage. You do not have to do these refactorings by hand; any IDE contains tools to perform refactorings such as extracting an expression into a variable or renaming a method. --- #### Exercise Take a look at the [gilded-rose/](exercises/lecture/gilded-rose) exercise folder. The code is obviously quite messy. First, try figuring out what the code is trying to do, and what problems it has. Then, write down what refactorings you would make to improve the code. You don't have to actually do the refactorings, only to list them, though you can do them for more practice. <details> <summary>Proposed solution (click to expand)</summary> <p> The code tries to model the quality of items over time. But it has so many special cases and so much copy-pasted code that it's hard to tell. Some possible refactorings: - Turn the `for (int i = 0; i < items.length; i++)` loop into a simpler `for (Item item : items)` loop - Simplify `item.quality = item.quality - item.quality` into the equivalent but clearer `item.quality = 0` - Extract `if (item.quality < 50) item.quality = item.quality + 1;` into a method `incrementQuality` on `Item`, which can thus encapsulate this cap at 50 - Extract numbers such as `50` into named constants such as `MAX_QUALITY` - Extract repeated checks such as those on the item names into methods on `Item` such as `isPerishable`, and maybe create subclasses of `Item` instead of checking names </p> </details> ## Where to start in a large codebase? Refactorings are useful for specific parts of code, but where to even start if you are given a codebase of millions of lines of code and told to fix a bug? There may not be documentation, and if there is it may not be accurate. A naïve strategy is to "move fast and break things", as [was once Facebook's motto](https://www.businessinsider.com/mark-zuckerberg-on-facebooks-new-motto-2014-5). The advantage is that you move fast, but... the disadvantage is that you break things. The latter tends to massively outweigh the former in any large codebase with many users. Making changes you don't fully understand is a recipe for disaster in most cases. An optimistic strategy, often taken by beginners, is to understand _everything_ about the code. Spend days and weeks reading every part of the codebase. Watch video tutorials about every library the code uses. This is not useful either, because it takes far too long, and because it will in fact never finish since others are likely making changes to the code while you learn. Furthermore, by the time you have read half the codebase, you won't remember what exactly the first part you looked at was, and your time will have been wasted. Let's see three components of a more realistic strategy: learning as you go, using an IDE, and taking notes. ### Learning as you go Think of how detectives such as [Sherlock Holmes](https://en.wikipedia.org/wiki/Sherlock_Holmes) or [Miss Marple](https://en.wikipedia.org/wiki/Miss_Marple) solve a case. They need information about the victim, what happened, and any possible suspects, because that is how they will find out who did it. But they do not start by asking every person around for their entire life story from birth to present. They do not investigate the full history of every item found at the scene of the crime. While the information they need is somewhere in there, getting it by enumerating all information would take too much time. Instead, detectives only learn what they need when they need it. If they find evidence that looks related, they ask about that evidence. If somebody's behavior is suspect, they look into that person's general history, and if something looks related, they dig deeper for just that detail. This is what you should do as well in a large codebase. Learn as you go: only learn what you need when you need it. ### Using an IDE You do not have to manually read through files to find out which class is used where, or which modules call which function. IDEs have built-in features to do this for you, and those features get better if the language you're using is statically typed. Want to find who uses a method? Right click on the method's name, and you should find some tool such as "find all references". Do you realize the method is poorly named given how the callers use it? Refactor its name using your IDE, don't manually rename every use. One key feature of IDEs that will help you is the _debugger_. Find the program's "main" function, the one called at the very beginning, and put a breakpoint on its first statement. Run the program with the debugger, and you're ready to start your investigation by following along with the program's flow. Want to know more about a function call? Step into it. Think that call is not relevant right now? Step over it instead. ### Taking notes You cannot hope to remember all context about every part of a large codebase by heart. Instead, take notes as you go, at first for yourself. You may later turn these notes into documentation. One formal way to take notes is to write _regression tests_. You do not know what behavior the program should have, but you do know that it works and you do not want to break it. Thus, write a test without assertions, run the test under the debugger, and look at the code's behavior. Then, add assertions to the test for the current behavior. This serves both as notes for yourself of what happens when the code is used in a specific way, and as an automated way to check if you broke something while modifying the code later. Another formal way to take notes is to write _facades_. "Facade" is a design pattern intended to simplify and modularize existing code by hiding complex parts behind simpler facades. For instance, let's say you are working in a codebase that only provides a very generic "draw" method that takes a lot of arguments, but you only need to draw rectangles: ```java var points = new Point[] { new Point(0, 0), new Point(x, 0), new Point(x, y), new Point(0, y) }; draw(points, true, false, Color.RED, null, new Logger(), ...); ``` This is hard to read and maintain, so write a facade for it: ```java drawRectangle(0, 0, x, y, Color.RED); ``` Then implement the `drawRectangle` method in terms of the complex `draw` method. The behavior hasn't changed, but the code is easier to read. Now, you only need to look at the complex part of the code if you actually need to add functionality related to it. Reading the code that needs to draw rectangles no longer requires knowledge of the complex drawing function. --- #### Exercise Take a look at the [pacman/](exercises/lecture/pacman) exercise folder. It's a cool "Pac-Man" game written in Java, with a graphical user interface. It's fun! Imagine you were asked to maintain it and add features. You've never read its code before. so where to start? First, look at the code, and take some notes: which classes exist, and what do they do? Then, use a debugger to inspect the code's flow, as described above. If someone asked you to extend this game to add a new kind of ghost, with a different color and behavior, which parts of the code would you need to change? Finally, what changes could you make to the code to make it easier to add more kinds of ghosts? <details> <summary>Proposed solution (click to expand)</summary> <p> To add a kind of ghost, you'd need to add a value to the `ghostType` enum, and a class extending `Ghost`. You would then need to add parsing logic in `MapEditor` for your ghost, and to link the enum and class together in `PacBoard`. To make the addition of more ghosts easier, you could start by re-formatting the code to your desired standard, and changing names to be more uniform, such as the casing of `ghostType`. One task would be to have a single object to represent ghosts, instead of having both `ghostType` and `Ghost`. It would also probably make sense to split the parsing logic from `MapEditor`, since editing and parsing are not the same job. Remember, you might look at this Pac-Man game code thinking it's not as nice as some idealized code that could exist, but unlike the idealized code, this one does exist already, and it works. Put energy into improving the code rather than complaining about it. </p> </details> --- Remember the rule typically used by scouts: leave the campground cleaner than you found it. In your case, the campground is code. Even small improvements can pay off with time, just like monetary investments. If you improve a codebase by 1% every day, after 365 days, it will be around 38x better than you started. But if you let it deteriorate by 1% instead, it will be only 0.03x as good. ## How should we document changes? You've made some changes to legacy code, such as refactorings and bug fixes. Now how do you document this? The situation you want to avoid is to provide no documentation, lose all knowledge you gained while making these changes, and need to figure it all out again. This could happen to yourself or to someone else. Let's see three kinds of documentation you may want to write: for yourself, for code reviewers, and for maintainers. ### Documenting for yourself The best way to check and improve your understanding of a legacy codebase is to teach others about it, which you can do by writing comments and documentation. This is a kind of "refactoring": you improve the code's maintainability by writing the comments and documentation that good code should have. For instance, let's say you find the following line in a method somewhere without any explanation: ```java if (i > 127) i = 127; ``` After spending some time on it, such as commenting it out to see what happens, you realize that this value is eventually sent to a server which refuses values above 127. You can document this fact by adding a comment, such as `// The server refuses values above 127`. You now understand the code better. Then you find the following method: ```java int indexOfSpace(String text) { ... } ``` You think you understand what this does, but when running the code, you realize it not only finds spaces but also tabs. After some investigation, it turns out this was a bug that is now a specific behavior on which clients depend, so you must keep it. You can thus add some documentation: `Also finds tabs. Clients depend on this buggy behavior`. You now understand the code better, and you won't be bitten by this issue again. ### Documenting for code reviewers You submit a pull request to a legacy codebase. Your changes touch code that your colleagues aren't quite familiar with either. How do you save your colleagues some time? You don't want them to have to understand exactly what is going on before being able to review your change, yet if you only give them code, this is what will happen. First, your pull request should have a _description_, in which you explain what you are changing and why. This description can be as long as necessary, and can include remarks such as whether this is a refactoring-only change or a change in behavior, or why you had to change some code that intuitively looks like it should not need changes. Second, the commits themselves can help reviewing if you split your work correctly, or if you rewrite the history once you are done with the work. For instance, your change may involve a refactoring and a bug fix, because the refactoring makes the bug fix cleaner. If you submit the change as a single commit, reviewers will need time and energy to read and understand the entire change at once. If a reviewer is interrupted in the middle of understanding that commit, they will have to start from scratch after the interruption. Instead of one big commit, you can submit a pull request consisting of one commit per logical task in the request. For instance, you can have one commit for a refactoring, and one for a bug fix. This is easier to review, because they can be reviewed independently. This is particularly important for large changes: the time spent reviewing a commit is not linear in the length of the commit, but closer to exponential, because we humans have limited brain space and usually do not have large chunks of uninterrupted time whenever we'd like. Instead of spending an hour reviewing 300 modified lines of code, it's easier to spend 10 times 3 minutes reviewing commits of 30 lines at a time. This also lessens the effects of being interrupted during a review. ### Documenting for maintainers We've talked about documentation for individual bits of code, but future maintainers need more than that to understand a codebase. Design decisions must be documented too: what did you choose and why? Even if you plan on maintaining a project yourself for a long time, this saves some work: your future colleagues could each take 5 minutes of your time asking you the same question about some design decision taken long ago, or you could spend 10 minutes once documenting it in writing. At the level of commits, this can be done in a commit message, so that future maintainers can use tools such as [git blame](https://git-scm.com/docs/git-blame) to find the commit that last changed a line of code and understand why it is that way. At the level of modules or entire projects, this can be done with _Architectural Decision Records_. As their name implies, these are all about recording decisions made regarding the architecture of a project: the context, the decision, and its consequences. The goal of ADRs is for future maintainers to know not only what choices were made but also why, so that maintainers can make an informed decision on whether to make changes. For instance, knowing that a specific library for user interfaces was chosen because of its excellent accessibility features informs maintainers that even if they do not like the library's API, they should pay particular attention to accessibility in any potential replacement. Perhaps the choice was made at a time when alternatives had poor accessibility, and the maintainers can change that choice because in their time there are alternatives that also have great accessibility features. The context includes user requirements, deadlines, compatibility with previous systems, or any other piece of information that is useful to know to understand the decision. For instance, in the context of lecture notes for a course, the context could include "We must provide lecture notes, as student feedback tells us they are very useful" and "We want to allow contributions from students, so that they can easily help if they find typos or mistakes". The decision includes the alternatives that were considered, the arguments for and against each of them, and the reasons for the final choice. For instance, still in the same context, the alternatives might be "PDF files", "documents on Google Drive", and "documents on a Git repository". The arguments could then include "PDF files are convenient to read on any device, but they make it hard to contribute". The final choice might then be "We chose documents on a Git repository because of the ease of collaboration and review, and because GitHub provides a nice preview of Markdown files online". The consequences are the list of tasks and changes that must be done in the short-to-medium term. This is necessary to apply the decision, even if it may not be useful in the long term. For instance, one person might be tasked with converting existing lecture notes to Markdown, and another might be tasked to create an organization and a repository on GitHub. It is important to keep ADRs _close to the code_, such as in the same repository, or in the same organization on a platform like GitHub. If ADRs are in some unrelated location that only current maintainers know about, they will be of no use to future maintainers. ## How can we quantify changes? Making changes is not only about describing them qualitatively, but also about telling people who use the software whether the changes will affect them or not. For instance, if you publish a release that removes a function from your library, people who used that function cannot use this new release immediately. They need to change their code to no longer use the function you removed, which might be easy if you provided a replacement, or might require large changes if you did not. And if the people using your library cannot or do not want to update their software, for instance because they have lost the source code, they now have to rewrite their software. Let's talk _compatibility_, and specifically three different axes: theory vs practice, forward vs backward, and source vs binary. ### Theory vs practice In theory, any change could be an "incompatible" change. Someone could have copied your code or binary somewhere, and start their program by checking that yours is still the exact same one. Any change would make this check fail. Someone could depend on the exact precision of some computation whose precision is not documented, and then [fail](https://twitter.com/stephentyrone/status/1425815576795099138) when the computation is made more precise. In practice, we will ignore the theoretical feasibility of detecting changes and choose to be "reasonable" instead. What "reasonable" is can depend on the context, such as Microsoft Windows having to provide compatibility modes for all kinds of old software which did questionable things. Microsoft must do this because one of the key features they provide is compatibility, and customers might move to other operating systems otherwise. Most engineers do not have such strict compatibility requirements. ### Forward vs backward A software release is _forward compatible_ if clients for the next release can also use it without needing changes. This is also known as "upward compatibility". That is, if a client works on version N+1, forward compatibility means it should also work on version N. Forward compatibility means that you cannot ever add new features or make changes that break behavior, since a client using those new features could not work on the previous version that did not have these features. It is rare in practice to offer forward compatibility, since the only changes allowed are performance improvements and bug fixes. A software release is _backward-compatible_ if clients for the previous release can also use it without needing changes. That is, if a client works on version N-1, backward compatibility means it should also work on version N. Backward compatibility is the most common form of compatibility and corresponds to the intuitive notion of "don’t break things". If something works, it should continue working. For instance, if you upgrade your operating systems, your applications should still work. Backward compatibility typically comes with a set of "supported" scenarios, such as a public API. It is important to define what is supported when defining compatibility, since otherwise some clients could misunderstand what is and is not supported, and their code could break even though you intended to maintain backward compatibility. For instance, old operating systems did not have memory protection: any program could read and write any memory, including the operating system's. This was not something programs should have been doing, but they could. When updating to a newer OS with memory protection, this no longer worked, but it was not considered breaking backward compatibility since it was never a feature in the first place, only a limitation of the OS. One extreme example of providing backward compatibility is Microsoft's [App Assure](https://www.microsoft.com/en-us/fasttrack/microsoft-365/app-assure): if a company has a program that used to work and no longer works after upgrading Windows, Microsoft will fix it, for free. This kind of guarantee is what allowed Microsoft to dominate in the corporate world; no one wants to have to frequently rewrite their programs, no matter how much "better" or "nicer" the new technologies are. If something works, it works. ### Source vs binary Source compatibility is about whether your customers' source code still compiles against a different version of your code. Binary compatibility is about whether your customers’ binaries still link with a different version of your binary. These are orthogonal to behavioral compatibility; code may still compile and link against your code even though the behavior at run-time has changed. Binary compatibility can be defined in terms of "ABI", "Application Binary Interface", just like "API" for source code. The ABI defines how components call each other, such as method signatures: method names, return types, parameter types, and so on. The exact compatibility requirements differ due to the ABI of various languages and platforms. For instance, parameter names are not a part of Java's ABI, and thus can be changed without breaking binary compatibility. In fact, parameter names are not a part of Java's API either, and can thus also be changed without breaking source compatibility. An interesting example of preserving source but not binary compatibility is C#'s optional parameters. A definition such as `void Run(int a, int b = 0)` means the parameter `b` is optional with a default value of `0`. However, this is purely source-based; writing `Run(a)` is translated by the compiler as if one had written `Run(a, 0)`. This means that evolving the method from `void Run(int a)` to `void Run(int a, int b = 0)` is compatible at the source level, because the compiler will implicitly add the new parameter to all existing calls, but not at the binary level, because the method signature changed so existing binaries will not find the one they expect. An example of the opposite is Java's generic type parameters, due to type erasure. Changing a class from `Widget<X>` to `Widget<X, Y>` is incompatible at the source level, since the second type parameter must now be added to all existing uses by hand. It is however compatible at the binary level, because generic parameters in Java are erased during compilation. If the second generic parameter is not otherwise used, binaries will not even know it exists. --- #### Exercise Which of these preserves backward compatibility? - Add a new class - Make a return type _less_ specific (e.g., from `String` to `Object`) - Make a return type _more_ specific (e.g., from `Object` to `String`) - Add a new parameter to a function - Make a parameter type _less_ specific - Make a parameter type _more_ specific <details> <summary>Proposed solution (click to expand)</summary> <p> - Adding a new class is binary compatible, since no previous version could have referred to it. It is generally considered to be source compatible, except for the annoying scenario in which someone used wildcard imports (e.g., `import org.example.*`) for two modules in the same file, and your new class has the same name as another class in another module, at which point the compiler will complain of an ambiguity. - Making a return type less specific is not backward compatible. The signature changes, so binary compatibility is already broken, and calling code must be modified to be able to deal with more kinds of values, so source compatibility is also broken. - Making a return type more specific is source compatible, since code that dealt with the return type can definitely deal with a method that happens to always return a more specific type. However, since the signature changes, it is not binary compatible. - Adding a parameter is neither binary nor source compatible, since the signature changes and code must now be modified to pass an additional argument whenever the function is called. - Making a parameter type less specific is source compatible, since a function that accepts a general type of parameter can be used by always giving a more specific type. However, since the signature changes, it is not binary compatible. - Making a parameter type more specific is not backward compatible. The signature changes, so binary compatibility is already broken, and calling code must be modified to always pass a more specific type for arguments, so source compatibility is also broken. </p> </details> --- What compatibility guarantees should you provide, then? This depends on who your customers are, and asking them is a good first step. Avoid over-promising; the effort required to maintain very strict compatibility may be more than the benefits you get from the one or two specific customers who need this much compatibility. Most of your customers are likely to be "reasonable". Backward compatibility is the main guarantee people expect in practice, even if they do not say so explicitly. Breaking things that work is viewed poorly. However, making a scenario that previously had a "failure" result, such as throwing an exception, return a "success” result instead is typically OK. Customers typically do not depend on things _not_ working. ## How can we establish solid foundations? You are asked to run an old Python script that a coworker wrote ages ago. The script begins with `import simplejson`, and then proceeds to use the `simplejson` library. You download the library, run the script... and you get a `NameError: name 'scanstring' is not defined`. Unfortunately, because the script did not specify what _version_ of the library it expected, you now have to figure it out by trial and error. For crashes such as missing functions, this can be done relatively quickly by going through versions in a binary search. However, it is also possible that your script will silently give a wrong result with some versions of the library. For instance, perhaps the script depends on a bug fix made at a specific time, and running the script with a version of the library older than that will give a result that is incorrect but not obviously so. Versions are specific, tested, and named releases. For instance, "Windows 11" is a version, and so is "simplejson 3.17.6". Versions can be more or less specific; for instance, "Windows 11" is a general product name with a set of features, and some more minor features were added in updates such as "Windows 11 22H2". Typical components of a version include a major and a minor version number, sometimes followed by a patch number and a build number; a name or sometimes a codename; a date of release; and possibly even other information. In typical usage, changing the major version number is for big changes and new features, changing the minor version number is for small changes and fixes, and changing the rest such as the patch version number is for small fixes that may not be noticeable to most users, as well as security patches. Versioning schemes can be more formal, such as [Semantic Versioning](https://semver.org/), a commonly used format in which versions have three main components: `Major.Minor.Patch`. Incrementing the major version number is for changes that break compatibility, the minor version number is for changes that add features while remaining compatible, and the patch number is for compatible changes that do not add features. As already stated, remember that the definition of "compatible" changes is not objective. Some people may consider a change to break compatibility even if others think it is compatible. Let's see three ways in which you will use versions: publishing versioned releases, _deprecating_ public APIs if truly necessary, and consuming versions of your dependencies. ### Versioning your releases If you allowed customers to download your source code and compile it whenever they want, it would be difficult to track who is using what, and any bug report would start with a long and arduous process of figuring out exactly which version of the code is in use. Instead, if a customer states they are using version 5.4.1 of your product and encounter a specific bug, you can immediately know which code this corresponds to. Providing specific versions to customers means providing specific guarantees, such as "version X of our product is compatible with versions Y and Z of the operating system", or "version X of our product will be supported for 10 years with security patches". You do not have to maintain a single version at a time; products routinely have multiple versions under active support, such as [Java SE](https://www.oracle.com/java/technologies/java-se-support-roadmap.html). In practice, versions are typically different branches in a repository. If a change is made to the "main" branch, you can then decide whether it should be ported to some of the other branches. Security fixes are a good example of changes that should be ported to all versions that are still supported. ### Deprecating public APIs Sometimes you realize your codebase contains some very bad mistakes that lead to problems, and you'd like to correct them in a way that technically breaks compatibility but still leads to a reasonable experience for your customers. That is what _deprecation_ is for. By declaring that a part of your public surface is deprecated, you are telling customers that they should stop using it, and that you may even remove it in a future version. Deprecation should be reserved for cases that are truly problematic, not just annoying. For instance, if the guarantees provided by a specific method force your entire codebase to use a suboptimal design that makes everything else slower, it may be worth removing the method. Another good example is methods that accidentally make it very easy to introduce bugs or security vulnerabilities due to subtleties in their semantics. For instance, Java's `Thread::checkAccess` method was deprecated in Java 17, because it depends on the Java Security Manager, which very few people use in practice and which constrains the evolution of the Java platform, as [JEP 411 states](https://openjdk.org/jeps/411). Here is an example of a less reasonable deprecation from Python: ``` >>> from collections import Iterable DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working ``` Sure, having classes in the "wrong" module is not great, but the cost of maintaining backward compatibility is low. Breaking all code that expects the "Abstract Base Collections" to be in the "wrong" module is likely more trouble than it's worth. Deprecating in practice means thinking about whether the cost is worth the risk, and if it is, using your language's way of deprecating, such as `@Deprecated(...)` in Java or `[Obsolete(...)]` in C#. ### Consuming versions Using specific versions of your dependencies allows you to have a "known good" environment that you can use as a solid base to work. You can update dependencies as needed, using version numbers as a hint for what kind of changes to expect. This does not mean you should 100% trust all dependencies to follow compatibility guidelines such as semantic versioning. Even those who try to follow such guidelines can make mistakes, and updating a dependency from 1.3.4 to 1.3.5 could break your code due to such a mistake. But at least you know that your code worked with 1.3.4 and you can go back to it if needed. The worst-case scenario, which is unfortunately common with old code, is when you cannot build a codebase anymore because it does not work with the latest versions of its dependencies and you do not know which versions it expects. You then have to spend lots of time figuring out which versions work and do not work, and writing them down so future you does not have to do it all over again. In practice, in order to manage dependencies, software engineers use package managers, such as Gradle for Java, which manage dependencies given versions: ``` testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' ``` This makes it easy to get the right dependency given its name and version, without having to manually find it online. It's also easy to update dependencies; package managers can even tell you whether there is any newer version available. You should however be careful of "wildcard" versions: ``` testImplementation 'org.junit.jupiter:junit-jupiter-api:5.+' ``` Not only can such a version cause your code to break because it will silently use a newer version when one is available, which could contain some bug that breaks your code, but you will have to spend time figuring out which version you were previously using, since it is not written down. For big dependencies such as operating systems, one way to easily save the entire environment as one big "version" is to use a virtual machine or container. Once it is built, you know it works, and you can distribute your software on that virtual machine or container. This is particularly useful for software that needs to be exactly preserved for long periods of time, such as scientific artifacts. ## Summary In this lecture, you learned: - Evolving legacy code: goals, refactorings, and documentation - Dealing with large codebases: learning as you go, improving the code incrementally - Quantifying and describing changes: compatibility and versioning You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Requirements We do not write code for the sake of writing code: we develop software to _help people perform tasks_. These people can be "anyone on Earth" for widely-used software such as GitHub, "people who do a specific job" for internal applications, or even a single person whose life can be helped with software. In order to know _what_ software to develop, we must know what user needs: their _requirements_. ## Objectives After this lecture, you should be able to: - Define what user requirements are - Formalize requirements into _personas_ and _user stories_ - Develop software based on formalized requirements - Understand _implicit_ vs _explicit_ requirements ## What are requirements? A requirement is something users need. For instance, a user might want to move from one place to another. They could then use a car. But perhaps the user has other requirements such as not wanting or being able to drive, in which case a train could satisfy their requirements. Users may also have more specific requirements, such as specifically wanting a low-carbon means of transportation, and having to travel between places that are far from public transport, in which case an electric car powered with low-carbon electricity could be a solution. Requirements are _not_ about implementation details. A specific kind of electric motor no a specific kind of steel for the car doors are not user requirements. However, users may have needs that lead to such choices being made by the system designers. Sometimes you may encounter a division between "functional" and "non-functional" requirements, with the latter also being known as "quality attributes". "Functional" requirements are those that directly relate to features, whereas "non-functional" ones include accessibility, security, performance, and so on. The distinction is not always clear, but it is sometimes made anyway. Defining requirements typically starts by discussing with users. This is easier if the software has a small and well-defined set of users, such as software specifically made for one person to do their job in a company. It is harder if the software has a large and ill-defined set of users, such as a search engine or an app to listen to music. It is important, when listening to what users say, to keep track of what they _need_ rather than what they _want_. What users claim they want is heavily influenced by what they already know and use. For instance, someone used to traveling by horse who needs to go across a mountain might ask for a "flying horse", when in fact their need is crossing the mountain, and thus a train with a tunnel or a plane would satisfy their requirements. Similarly, before the modern smart phone, users would have asked for old-style phones purely because they did not even know a smart phone was feasible, even if now they actually like their smart phone more than they liked their old phone. What users want can be ambiguous, especially when there are many users. If you select cells with "100" and "200" in a spreadsheet program such as Microsoft Excel and expand the selection, what should happen? Should Excel fill the new cells with "300", "400", and so on? Should it repeat "100" and "200" ? What if you expand a selection containing the lone cell "Room 120" ? Should it be repeated or should it become "Room 121", "Room 122", and so on? There is no perfect answer to these questions, as any answer will leave some users unsatisfied, but a developer must make a choice. Not listening to users' requirements can be costly, as Microsoft found out with Windows 8. Windows 8's user interface was a major reinvention of the Windows interface, using a "start screen" rather than a menu, with full-screen apps that could be tiled rather than moved. It was a radical departure from the Windows that users knew, and it was a commercial failure. Microsoft had to bring back the start menu, and abandoned the concept of tiled full-screen apps. However, Apple later did something similar for a new version of their iPad operating system, and it worked quite well there, perhaps because users have different expectations on desktops and tablets. ## How can we formalize requirements? Once you've discussed with plenty of users and gotten many ideas on what requirements users have, how do you consolidate this feedback into actionable items? This is what formalizing requirements is about, and we will discuss formalizing _who_ with "personas" and _what_ with "user stories". Who is the software for? Sometimes the answer to that question is obvious because it is intended for a small and specific set of users, but most large pieces of software are intended for many people. In fact, large pieces of software typically have way too many users for any kind of personalized process to scale. Instead, you can use _personas_ to represent groups of users. A persona is an _abstract_ person that represents a group of similar users. For instance, in a music app, one persona might be Alice, a student, who uses the app in her commute on public transport. Alice is not a real person, and she does not need specific features such as a hair color or a nationality. Instead, Alice is an abstract representation of many people who could use the app and all have similar features from the app's point of view, namely that they use the app on public transport while commuting to their school, university, or other similar place. Alice's requirements might lead to features such as downloading podcasts in advance at home, and listening with the screen turned off. Another persona for the same app might be Bob, a pensioner, who uses the app while cooking and cleaning. Bob is not a real person either, but instead represents a group of potential users who aren't so familiar with the latest technology and want to use the app while performing tasks at home. While one can create personas for many potential groups of users, not all of them will make the cut. Still for the music app example, another persona could be Carol, a "hacker" who wants to listen to pirated music. Carol would need features such as loading existing music tracks into the app and bypassing copyright protection. Is the app intended for people like Carol? That's up to the developers to decide. One last word about personas: avoid over-abstracting. Personas are useful because they represent real people in ways that are helpful to development. If your personas end up sounding like "John, a user who uses the app" or "Jane, a person who has a phone", they will not be useful. Similarly, if you already know who exactly is in a group of users, there is no need to abstract it. "Sam, a sysadmin" is not a useful persona if your app has exactly one sysadmin: use the real person instead. --- #### Exercise What personas could a video chat app have? <details> <summary>Example solutions (click to expand)</summary> <p> Anne, a manager who frequently talks to her team while working remotely. Basil, a pensioner who wants to video chat his grandkids to stay in touch. Carlos, a doctor who needs to talk to patients as part of a telemedicine setup. </p> </details> --- What can users do? After defining who the software is for, one must decide what features to build. _User stories_ are a useful tool to formalize features based on requirements, including who wants the feature, what the feature is, and what the context is. Context is key because the same feature could be implemented in wildly different ways based on context. For instance, "sending emails with information" is a feature a software system might have. If the context is that users want to archive information, the emails should include very detailed information, but their arrival time matters little. If the context is that users want a notification as soon as something happens, the emails should be sent immediately, and great care should be taken to avoid ending up in a spam filter. If the context is that users want to share data with their friends who don't use the software, the emails should have a crisp design that contains only the relevant information so they can be easily forwarded. There are many formats for user stories; in this course, we will use the three-part one "_as a ... I want to ... so that ..._". This format includes the user who wants the feature, which could be a persona or a specific role, the feature itself, and some context explaining why that user wants that feature. For instance, "As a student, I want to watch course recordings, so that I can catch up after an illness". This user story lets developers build a feature that is actually useful to the person: it would not be useful to this student, for instance, to build a course recording feature that is an archive accessible once the course has ended, since presumably the student will not be ill for the entire course duration. Going back to our music app example, consider the following user story: "As Alice, I want to download podcasts in advance, so that I can save mobile data". This implies the app should download the entire podcast in advance, but Alice still does have mobile data, she just doesn't want to use too much of it. A similar story with a different context could be "As a commuter by car, I want to download podcasts in advance, so that I can use the app without mobile data". This is a different user story leading to a different feature: now the app cannot use mobile data at all, because the commuter simply does not have data at some points of their commute. To evaluate user stories, remember the "INVEST" acronym: - *I*ndependent: the story should be self-contained - *N*egotiable: the story is not a strict contract but can evolve - *V*aluable: the story should bring clear value to someone - *E*stimable: the developers should be able to estimate how long the story will take to implement - *S*mall: the story should be of reasonable size, not a huge "catch-all" story - *T*estable: the developers should be able to tell what acceptance criteria the story has based on its text, so they can test their implementation Stories that are too hard to understand and especially too vague will fail the "INVEST" test. #### Exercise What user stories could a video chat app have? <details> <summary>Example solutions (click to expand)</summary> <p> As Anne, I want to see my calendar within the app, so that I can schedule meetings without conflicting with my other engagements. As Basil, I want to launch a meeting from a message my grandkids send me, so that I do not need to spend time configuring the app. As a privacy enthusiast, I want my video chats to be encrypted end-to-end, so that my data cannot be leaked if the app servers get hacked. </p> </details> #### Exercise Which of the following are good user stories and why? 1. As a user, I want to log in quickly, so that I don't lose time 2. As a Google account owner, I want to log in with my Gmail address 3. As a movie buff, I want to view recommended movies at the top on a dark gray background with horizontal scroll 4. As an occasional reader, I want to see where I stopped last time, so that I can continue reading 5. As a developer, I want to improve the log in screen, so that users can log in with Google accounts <details> <summary>Solutions (click to expand)</summary> <p> 1 is too vague, 2 is acceptable since the reason is implicit and obvious, 3 is way too specific, 4 is great, and 5 is terrible as it relates to developers not users. </p> </details> ## How can we develop from requirements? You've listened to users, you abstracted them into personas and their requirements into user stories, and you developed an application based on that. You're convinced your personas would love your app, and your implementation answers the needs defined by the user stories. After spending a fair bit of time and money, you now have an app that you can demo to real users... and they don't like it. It's not at all what they envisioned. What went wrong? What you've just done, asking users for their opinion on the app, is _validation_: checking if what you specified is what users want. This is different from _verification_, which is checking if your app correctly does what you specified. One key to successful software is to do validation early and often, rather than leaving it until the end. If what you're building isn't what users want, you should know as soon as possible, instead of wasting resources building something nobody will use. To do this validation, you will need to build software in a way that can be described by users, using a _common language_ with them and _integrating_ them into the process so they can give an opinion. We will see two ways to do this. First, you need a _common language_ with your users, as summarized by Eric Evans in his 2003 book "Domain-Driven Design". Consider making some candy: you could ask people in advance whether they want some candy containing NaCl, $C_{24}$ $H_{36}$ $O_{18}$, $C_{36}$ $H_{50}$ $O_{25}$, $C_{125}$ $H_{188}$ $O_{80}$, and so on. This is a precise definition that you could give to chemists, who would then implement it. However, it's unlikely an average person will understand until your chemists actually build it. Instead, you could ask people if they want candy with "salted caramel". This is less precise, as one can imagine different kinds of salted caramel, but much more understandable by the end users. You don't need to create salted caramel biscuits for people to tell you whether they like the idea or not, and a discussion about your proposed candy will be much more fruitful using the term "salted caramel" than using any chemical formula. In his book, Evans suggests a few specific terms that can be taught to users, such as "entity" for objects that have an identity tied to a specific property, "value object" for objects that are data aggregates without a separate identity, and so on. The point is not which exact terms you use, but the idea that you should design software in a way that can be easily described to users. Consider what a user might call a "login service", which identifies users by what they know as "email addresses". A programmer used to the technical side of things might call this a `PrincipalFactory`, since "principals" is one way to call a user identity, and a "factory" is an object that creates objects. The identifiers could be technically called "IDs". However, asking a user "What should happen when the ID is not found? Should the principal returned by the factory be `null`?" will yield puzzled looks. Most users do not know any of these terms. Instead, if the object in the code is named `LoginService`, and takes in objects of type `Email` to identify users, the programmer can now ask the user "What should happen when the email is not found? Should the login process fail?" and get a useful answer. Part of using the _right_ vocabulary to discuss with people is also using _specific_ vocabulary. Consider the term "person". If you ask people at a university what a "person" is, they will mumble some vague answer about people having a name and a face, because they do not deal with general "people" in their jobs. Instead, they deal with specific kinds of people. For instance, people in the financial service deal with "employees" and "contractors", and could happily teach you exactly what those concepts are, how they differ, what kind of attributes they have, what operations are performed on their data, and so on. Evans calls this a "bounded context": within a specific business domain, specific words have specific meanings, and those must be reflected in the design. Imagine trying to get a financial auditor, a cafeteria employee, and a professor to agree on what a "person" is, and to discuss the entire application using a definition of "person" that includes all possible attributes. It would take forever, and everyone would be quite bored. Instead, you can talk to each person separately, represent these concepts separately in code, and have operations to link them together via a common identity, such as one function `get_employee(email)`, one function `get_student(email)`, and so on. Once you have a common language, you can also write test scenarios in a way users can understand. This is _behavior-driven development_, which can be done by hand or with the help of tools such as [Cucumber](https://cucumber.io/) or [Behave](https://behave.readthedocs.io/). The idea is to write test scenarios as three steps: "_given ... when ... then ..._", which contain an initial state, an action, and a result. For instance, here is a Behave example from their documentation: ``` Scenario Outline: Blenders Given I put <thing> in a blender, when I switch the blender on then it should transform into <other thing> Examples: Amphibians | thing | other thing | | Red Tree Frog | mush | Examples: Consumer Electronics | thing | other thing | | iPhone | toxic waste | | Galaxy Nexus | toxic waste | ``` Using this text, one can write functions for "putting a thing in a blender", "switching on the blender", and "checking what is in the blender", and Behave will run the functions for the provided arguments. Users don't have to look at the functions themselves, only at the text, and they can then state whether this is what they expected. Perhaps only blue tree frogs, not red ones, need to turn into mush. Or perhaps the test scenario is precisely what they need, and developers should go implement the actual feature. The overall workflow is as follows: 1. Discuss with users to get their requirements 2. Translate these requirements into user stories 3. Define test scenarios based on these user stories 4. Get feedback on these scenarios from users 5. Repeat as many times as needed until users are happy, at which point implementation can begin #### Exercise What language would you use to discuss a course registration system at a university (or any other system you use frequently), and what test scenarios could you define? <details> <summary>Example solutions (click to expand)</summary> <p> A course registration system could have students, which are entities identified by a university e-mail who have a list of courses and grades associated with the courses, and lecturers, which are associated with the courses they teach and can edit said courses. Courses themselves might have a name, a code, a description, and a number of credits. Some testing scenarios might be "given that a user is already enrolled in a course, when the user tries to enroll again, then that has no effect", or "given that a lecturer is in charge of a course, when the lecturer sets grades for a student in the course, then that student's grade is updated". </p> </details> ## What implicit requirements do audiences have? Software engineers design systems for all kinds of people, from all parts of the world, with all kinds of needs. Often some people have requirements that are _implicit_, yet are just as required as the requirements they will explicitly tell you about. Concretely, we will see _localization_, _internationalization_, and _accessibility_. Sometimes these are shortened to "l10n", "i18n", and "a11y", each having kept their start and end letter, with the remaining letters being reduced to their number. For instance, there are 10 letters between "l" and "n" in "localization", thus "l10n". _Localization_ is all about translations. Users expect all text in programs to be in their language, even if they don't explicitly think about it. Instead of `print("Hello " + user)`, for instance, your code should use a constant that can be changed per language. It is tempting to have a `HELLO_TEXT` constant with the value `"Hello "` for English, but this does not work for all languages because text might also come after the user name, not only before. The code could thus use a function that takes care of wrapping the user name with the right text: `print(hello_text(user))`. Localization may seem simple, but it also involves double-checking assumptions in your user interface and your logic. For instance, a button that can hold the text "Log in" may not be wide enough when the text is the French "Connexion" instead. A text field that is wide enough for each of the words in "Danube steamship company captain" might overflow with the German "Donaudampfschifffahrtsgesellschaftkapitän". Your functions that provide localized text may need more information than you expect. English nouns have no grammatical gender, so all nouns can use the same text, but French has two, German has three, and Swahili has [eighteen](https://en.wikipedia.org/wiki/Swahili_grammar#Noun_classes)! English nouns have one "singular" and one "plural" form, and so do many languages such as French, but this is not universal; Slovenian, for instance, has one ending for 1, one for 2, one for 3 and 4, and one for 5 and more. Translations can have bugs just like software can. For instance, the game Champions World Class Soccer's German translation infamously has a bug in which "shootout" is not, as it should, translated to "schiessen", but instead to "scheissen", which has an entirely different meaning despite being one letter swap apart. Another case of German issues is [in the game Grandia HD](https://www.nintendolife.com/news/2019/08/random_amazingly_grandia_hds_translation_gaffe_is_only_the_second_funniest_german_localisation_mistake): missing an attack displays the text "fräulein", which is indeed "miss" but in an entirely different context. Localization is not something you can do alone unless you are translating to your native language, since nobody knows all features of all languages. Just like other parts of software, localization needs testing, in this case by native speakers. _Internationalization_ is all about cultural elements other than language. Consider the following illustration: <p align="center"><img alt="Illustration of (from left to right) a dirty t-shirt, a washing machine, a clean t-shirt" src="images/washing.svg" width="50%" /></p> What do you see? Since you're reading English text, you might think this is an illustration of a t-shirt going from dirty to clean through a washing machine. But someone whose native language is read right to left, such as Arabic, might see the complete opposite: a t-shirt going from clean to dirty through the machine. This is rather unfortunate, but it is the way human communication works: people have implicit expectations that are sometimes at odds. Software thus needs to adapt. Another example is putting "Vincent van Gogh" in a list of people sorted by last name. Is Vincent under "G" for "Gogh" or under "V" for "van Gogh"? That depends on who you ask: Dutch people expect the former, Belgians the latter. Software needs to adapt, otherwise at least one of these two groups will be confused. Using the culture-specific format for dates is another example: "10/01" mean very different dates to an American and to someone from the rest of the world. One important part of localization is people's names. Many software systems out there are built with odd assumptions about people's names, such as "they are composed entirely of letters", or "family names have at least 3 letters", or simply "family names are something everyone has". In general, [programmers believe many falsehoods about names](https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/), which leads to a lot of pain for people who have names that do not comply to those falsehoods, such as people with hyphens or apostrophes in their names, people whose names are one or two letters long, people from cultures that do not have a concept of family names, and so on. Remember that _a person's name is never invalid_. Like localization, internationalization is not something you can do alone. Even if you come from the region you are targeting, that region is likely to contain many people from many cultures. Internationalization needs testing. _Accessibility_ is a property software has when it can be used by everyone, even people who cannot hear, cannot see, do not have hands, and so on. Accessibility features include closed captions, text-to-speech, dictation, one-handed keyboards, and so on. User interface frameworks typically have accessibility features documented along with their other features. These are not only useful to people who have permanent disabilities, but also to people who are temporarily unable to use some part of their body. For instance, closed captions are convenient for people in crowded trains who forgot their headphones. Text-to-speech is convenient for people who are doing something else while using an app on their phone. Features designed for people without hands are convenient for parents holding their baby. Accessibility is not only a good thing to do from a moral standpoint: it is often legally required, especially in software for government agencies. It is also good even from a selfish point of view: a more accessible app has more potential customers. ## Are all requirements ethical? We've talked about requirements from users under the assumption that you should do whatever users need. But is that always the case? Sometimes, requirements conflict with your ethics as an engineer, and such conflicts should not be brushed aside. Just because "a computer is doing it" does not mean the task is acceptable or that it will be performed without any biases. The computer might be unbiased, but it is executing code written by a human being, which replicates that human's assumptions and biases, as well as all kinds of issues in the underlying data. For instance, there have been many variants of "algorithms to predict if someone will be a criminal", using features such as people's faces. If someone were to go through a classroom and tell every student "you're a criminal" or "you're not a criminal", one would reasonably be upset and suspect all kinds of bad reasons for these decisions. The same must go for a computer: there is no magical "unbiased", "objective" algorithm, and as a software engineer you should always be conscious of ethics. ## Summary In this lecture, you learned: - Defining and formalizing user needs with requirements, personas, and user stories - Developing based on requirements through domain-driven design and behavior-driven development - Understanding implicit requirements such as localization, internationalization, accessibility, and ethics You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Performance Producing correct results is not the only goal of software. Results must be produced in reasonable time, otherwise users may not wait for a response and give up. Providing a timely response is made harder by the interactions between software components and between software and hardware, as well as the inherent conflicts between different definitions of performance. As a software engineer, you will need to find out what kind of performance matters for your code, measure the performance of your code, define clear and useful performance goals, and ensure the code meets these goals. You will need to keep performance in mind when designing and writing code, and to debug the performance issues that cause your software to not meet its goals. ## Objectives After this lecture, you should be able to: - Contrast different metrics and scales for performance - Create benchmarks that help you achieve performance objectives - Profile code to find performance bottlenecks - Optimize code by choosing the right algorithms and tradeoffs for a given scenario ## What is performance? There are two key metrics for performance: _throughput_, the number of requests served per unit of time, and _latency_, the time taken to serve one request. In theory, we would like latency to be constant per request and throughput constant over time, but in practice, this is usually never the case. Some requests fundamentally require more work than others, such ordering a pizza with 10 toppings compared to a pizza with only cheese and tomatoes. Some requests go through different code paths because engineers made tradeoffs, such as ordering a gluten-free pizza taking more time because instead of maintaining a separate gluten-free kitchen, the restaurant has to clean its only kitchen. Some requests compete with other requests for resources, such as ordering a pizza right after a large table has placed an order in a restaurant with only one pizza oven. Latency thus has many sub-metrics in common use: mean, median, 99th percentile, and even latency just for the first request, i.e., the time the system takes to start. Which of these metrics you target depends on your use case, and has to be defined in collaboration with the customer. High percentiles such as the 99th percentile make sense for large systems in which many components are involved in any request, as [Google describes](https://research.google/pubs/pub40801/) in their "Tail at Scale" paper. Some systems actually care about the "100th percentile", i.e., the _worst-case execution time_, because performance can be a safety goal. For instance, when an airplane pilot issues a command, the plane must reply quickly. It would be catastrophic for the plane to execute the command minutes after the pilot has issued it, even if the execution is semantically correct. For such systems, worst-case execution time is typically over-estimated through manual or automated analysis. Some systems also need no variability at all, i.e., _constant-time_ execution. This is typically used for cryptographic operations, whose timing must not reveal any information about secret keys or passwords. In a system that serves one request at a time, throughput is the inverse of mean latency. In a system that serves multiple requests at a time, there is no such correlation. For instance, one core of a dual-core CPU might process a request in 10 seconds while another core has served 3 requests in that time, thus the throughput was 4 requests per 10 seconds but the latency varied per request. We used "time" as an abstract concept above, but in practice you will use concrete units such as minutes, seconds, or even as low as nanoseconds. Typically, you will care about the _bottleneck_ of the system: the part that takes the most time. There is little point in discussing other parts of the system since their performance is not key. For instance, if it takes 90 seconds to cook a pizza, it is not particularly useful to save 0.5 seconds when adding cheese to the pizza, or to save 10 nanoseconds in the software that sends the order to the kitchen. If you're not sure of how long a nanosecond is, check out [Grace Hopper's thought-provoking illustration](https://www.youtube.com/watch?v=gYqF6-h9Cvg) (the video has manually-transcribed subtitles you can enable). Grace Hopper was a pioneer in programming languages. With her team, she designed COBOL, the first language that could execute English-like commands. As she [recalled](https://www.amazon.com/Grace-Hopper-Admiral-Computer-Contemporary/dp/089490194X) it, "_I had a running compiler and nobody would touch it. They told me computers could only do arithmetic_". Thankfully, she ignored the naysayers, or we wouldn't be programming in high-level languages today! _Amdahl's law_ states that the speedup achieved by optimizing one component is at most that component's share of overall execution time. For instance, if a function takes 2% of total execution time, it is not possible to speed up the system more than 2% by optimizing that function, even if the function itself is made orders of magnitude faster. As you can tell, the word "performance" hides a lot of details, and "improving performance" is usually too abstract a goal. Optimizing a system requires clear goals defined in terms of specific workloads and metrics, and an understanding of which parts of the system currently take the most time. Performance objectives for services used by customers are typically defined in terms of _Service Level Indicators_, which are measures such as "median request latency", _Service Level Objectives_, which define goals for these measures such as "under 50ms", and _Service Level Agreements_, which add consequences to objectives such as "or we reimburse 20% of the customer's spending that month". Picking useful objectives is a key first step. "As fast as possible" is usually not useful since it requires too many tradeoffs, as [pizza chain Domino's found out](https://www.nytimes.com/1993/12/22/business/domino-s-ends-fast-pizza-pledge-after-big-award-to-crash-victim.html) after their promise of reimbursing late pizzas led to an increase in car crashes for their drivers. Systems should be fast enough, not perfect. What "enough" is depends on the context. Some software systems have specific performance requirements. Other times the performance requirements are implicit, making them harder to define. For instance, in 2006 Google [found](http://glinden.blogspot.com/2006/11/marissa-mayer-at-web-20.html) that traffic dropped 20% if their search results took 0.9s to show instead of 0.4s. In 2017, Akamai [found](https://www.akamai.com/uk/en/about/news/press/2017-press/akamai-releases-spring-2017-state-of-online-retail-performance-report.jsp) that even a 100ms increase in page load time could lead to a 7% drop in sales. In general, if users feel that an interface is "too slow", they won't like it, and if they have another choice they may use it instead. ## How can one measure performance? The process of measuring performance is called _benchmarking_, and it is a form of testing for performance. Like tests, benchmarks are usually automated, and come with issues such as how to isolate a specific component rather than always benchmark the entire system. Benchmarks for individual functions are typically called _microbenchmarks_, while benchmarks for entire systems are "end to end". In theory, benchmarking is a simple process: start a timer, perform an action, stop the timer. But in practice, there are many tricky parts. How precise is the timer? What's the timer's resolution? How variable is the operation? How many measurements should be taken for the results to be valid? Should outliers be discarded? What's the best API on each OS to time actions? How to avoid "warm up" effects? And caching effects? Are compiler optimizations invalidating the benchmark by changing the code? You should never write your own benchmarking code. (Unless you become an expert in benchmarking, at which point you will know you can break this rule.) Instead, use an existing benchmarking framework, such as JMH for Java, BenchmarkDotNet for .NET, or pytest-benchmark for Python. In practice, to benchmark some code, you first need to define the workload you will use, i.e., the inputs, and the metric(s) you care about. Then you need a _baseline_ for your benchmark. Absolute performance numbers are rarely useful, instead one usually compares to some other numbers, such as the performance of the previous version of the software. For low-level code or when benchmarking operations that take very little time, you may also need to set up your system in specific ways, such as configuring the CPU to not vary its frequency. It is very easy to accidentally write benchmark code that is meaningless in a non-obvious way. Always ask your colleagues to review your benchmark code, and provide the code whenever you provide the results. Try small variations of the code to see if you get small variations in the benchmark results. If you have any, reproduce previous results to ensure that your overall setup works. Beware of the "small input problem": it is easy to miss poorly-performing algorithms by only benchmarking with small inputs. For instance, if an operation on strings is in `O(n^3)` of the string length and you only use a string of size 10, that is 1000 operations, which is instantaneous on any modern CPU. And yet the algorithm is likely not great, since `O(n^3)` is usually not an optimal solution. Make sure you are actually measuring what you want to measure, rather than intermediate measurements that may or may not be representative of the full thing. For instance, [researchers found](https://dl.acm.org/doi/abs/10.1145/3519939.3523440) that some garbage collectors for Java had optimized for the time spent in the garbage collector at the expense of the time taken to run an app overall. By trying to minimize GC time at all costs, some GCs actually increased the overall running time. Finally, remember that it is not useful to benchmark and improve code that is already fast enough. While microbenchmarking can be addictive, you should spend your time on tasks that have impact to end users. Speeding up an operation from 100ms to 80ms can feel great, but if users only care about the task taking less than 200ms, they would probably have preferred you spend time on adding features or fixing bugs. ## How can one debug performance? Just like benchmarking is the performance equivalent of testing, _profiling_ is the performance equivalent of debugging. The goal of profiling is to find out how much time each operation in a system takes. There are two main kinds of profilers: _instrumenting_ profilers that add code to the system to record the time before and after each operation, and _sampling_ profilers that periodically stop the program to take a sample of what operation is running at that time. A sampling profiler is less precise, as it could miss some operations entirely if the program happens to never be running them when the profiler samples, but it also has far less overhead than an instrumenting profiler. It's important to keep in mind that the culprit of poor performance is usually a handful of big bottlenecks in the system that can be found and fixed with a profiler. The average function in any given codebase is fast enough compared to those bottlenecks, and thus it is important to profile before optimizing to ensure an engineer's time is well spent. For instance, a hobbyist once managed to [cut loading times by 70%](https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/) in an online game by finding the bottlenecks and fixing them. Both of them were `O(n^2)` algorithms that could be fixed to be `O(n)` instead. There are plenty of profilers for each platform, and some IDEs come with their own. For instance, Java has VisualVM. ## How can one improve performance? The typical workflow is as follows: 1. Double-check that the code is actually correct and that it is slower than what users need (otherwise there is no point in continuing) 2. Identify the bottleneck by profiling 3. Remove any unnecessary operations 4. Make some tradeoffs, if necessary 5. Go to step 1 Identifying the problem always requires measurements. Intuition is often wrong when it comes to performance. See online questions such as ["Why is printing "B" dramatically slower than printing "#"?"](https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing) or ["Why does changing 0.1f to 0 slow down performance by 10x?"](https://stackoverflow.com/questions/9314534/why-does-changing-0-1f-to-0-slow-down-performance-by-10x). Once a problem is found, the first task is to remove any unnecessary operations the code is doing, such as algorithms that can be replaced by more efficient ones without losing anything other than development time. For instance, a piece of code may use a `List` when a `Set` would make more sense because the code mostly checks for membership. Or a piece of code may be copying data when it could use a reference to the original data instead, especially if the data can be made immutable. This is also the time to look for existing faster libraries or runtimes, such as [PyPy](https://www.pypy.org/) for Python, that are usually less flexible but are often enough. If necessary, after fixing obvious culprits that do not need complex tradeoffs, one must make serious tradeoffs. Unfortunately, in practice, performance tradeoffs occur on many axes: latency, throughput, code readability and maintainability, and sub-axes such as specific kinds of latency. ### Separating common cases One common tradeoff is to increase code size to reduce latency by adding specialized code for common requests. Think of how public transport is more efficient than individual cars, but only works for specific routes. Public transport cannot entirely replace cars, but for many trips it can make a huge difference. If common requests can be handled more efficiently than in the general case, it is often worthwhile to do so. ### Caching It is usually straightforward to reduce latency by increasing memory consumption through _caching_, i.e., remembering past results. In fact, the reason why modern CPUs are so fast is because they have multiple levels of caches on top of main memory, which is slow. Beware, however: caching introduces potential correctness issues, as the cache may last too long, or return obsolete data that should have been overwritten with the results of a newer query. ### Speculation and lazy loading You go to an online shop, find a product, and scroll down. "Customers who viewed this item also viewed..." and the shop shows you similar items you might want to buy, even before you make further searches. This is _speculation_: potentially lowering latency and increasing throughput if the predictions are successful, at the cost of increasing resource use and possibly doing useless work if the predictions are wrong. The opposite of speculation is _lazy loading_: only loading data when it is absolutely needed, and delaying any loading until then. For instance, search engines do not give you a page with every single result on the entire Internet for your query, because you will most likely find what you were looking for among the first results. Instead, the next results are only loaded if you need them. Lazy loading reduces the resource use for requests that end up not being necessary, but requires more work for requests that are actually necessary yet were not executed early. ### Streaming and batching Instead of downloading an entire movie before watching it, you can _stream_ it: your device will load the movie in small chunks, and while you're watching the first few chunks the next ones can be downloaded in the background. This massively decreases latency, but it also decreases throughput since there are more requests and responses for the same amount of overall data. The opposite of streaming is _batching_: instead of making many requests, make a few big ones. For instance, the postal service does not come pick up your letters every few minutes, since most trips would be a waste; instead, they come once or twice a day to pick up all of the letters at once. This increases throughput, at the expense of increasing latency. ## Summary In this lecture, you learned: - Defining performance: latency, throughput, variability, and objectives - Benchmarking and profiling: measuring and understanding performance and bottlenecks - Tradeoffs to improve performance: common cases, caching, speculation vs lazy loading, and streaming vs batching You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Debugging > **Prerequisite**: You are _strongly_ encouraged, though not strictly required, to use an IDE for the exercises about debugging in this lecture. > Alternatively, you can use Java's built-in command-line debugger, `jdb`, but it is far less convenient than a graphical user interface. Writing code is only one part of software engineering; you will often spend more time _reading_ code than writing code. This may be to understand a piece of code so you can extend it, or _debug_ existing code by finding and fixing bugs. These tasks are a lot easier if you write code with readability and debuggability in mind, and if you know how to use debugging tools. ## Objectives After this lecture, you should be able to: - Develop _readable_ code - Use a _debugger_ to understand and debug code - Isolate the _root cause_ of a bug - Develop _debuggable_ code ## What makes code readable? Take a look at [planets.py](exercises/lecture/planets.py) in the in-lecture exercise folder. Do you find it easy to read and understand? Probably not. Did you spot the fact that sorting doesn't work because the code uses a function that returns the sorted list, but does not use its return value, rather than an in-place sort? It's a lot harder to spot that bug when you have to use so much brain power just to read the code. Unfortunately, hard-to-read code doesn't only happen in exercises within course lecture notes. Consider the following snipped from the ScalaTest framework: ```scala package org.scalatest.tools object Runner { def doRunRunRunDaDoRunRun(...): Unit } ``` What does this method do? The method name isn't going to help you. It's a reference to [a song from 1963](https://en.wikipedia.org/wiki/Da_Doo_Ron_Ron). Sure, it's a funny reference, but wouldn't you rather be reading a name that told you what the method does? Worse, [the method has 21 parameters](https://github.com/scalatest/scalatest/blob/282da2aff8f439906fe5e7d9c3112c84019545e7/jvm/core/src/main/scala/org/scalatest/tools/Runner.scala#L1044-L1066). You can of course understand what the method does if you spend enough time on it, but should you have to? Let's talk about five components of code readability: naming, documentation, comments, formatting, and consistency. ### Names First, an example of _naming_ without even using code: measurement errors. If you measure the presence of something that's absent, that's a `type I error`. If you measure the absence of something that's present, that's a `type II error`. These kinds of errors happen all the time in, for instance, tests to detect viruses. However, it's easy to forget which is type `I` and which is type `II`. And even if you remember, a typo duplicating a character can completely change the meaning of a sentence. Instead, you can use `false positive` and `false negative`. These names are easier to understand, easier to remember, and more resilient to spelling mistakes. Names in code can also make the difference between code that's easy to understand and code that's hard to even mentally parse. A variable named `isUserOnline` in Java is fine... as long as it really is for an "is the user online?" boolean variable, that is. If it's an integer, it's a lot more confusing. And if you're writing Python instead, it's also a problem since Python uses underscores to separate words, a.k.a. "snake case", so it should be `is_user_online`. A variable named `can_overwrite_the_data` is quite a long name, which isn't a problem by itself, but it's redundant: of course we're overwriting "data", the name is too vague. Names are not only about variable, method, or class names. Consider the following method call: ```java split("abc", "a", true, true) ``` What does this method do? Good question. What if the call looked like this instead, with constants or enums? ```java split("abc", "a", SplitOptions.REMOVE_EMPTY_ENTRIES, CaseOptions.IGNORE_CASE) ``` This is the same method call, but we've given names instead of values, and now the meaning is clearer. These constants are only a workaround for Java's lack of named parameters, though. In Scala, and other languages like C#, you could call the method like this: ```scala split("abc", separator = "a", removeEmptyEntries = true, ignoreCase = true) ``` The code is now much more readable thanks to explicit names, without having to write extra code. A cautionary tale in good intentions with naming is _Hungarian notation_. Charles Simonyi, a Microsoft engineer from Hungary, had the good idea to start his variable names with the precise data type the variables contained, such as `xPosition` for a position on the X axis, or `cmDistance` for a distance in centimeters. This meant anyone could easily spot the mistake in a like such as `distanceTotal += speedLeft / timeLeft`, since dividing speed by time does not make a distance. This became known as "Hungarian notation", because in Simonyi's native Hungary, names are spelled with the family name first, e.g., "Simonyi Károly". Unfortunately, another group within Microsoft did not quite understand what Simonyi's goal was, and instead thought it was about the variable type. So they wrote variable names such as `cValue` for a `char` variable, `lIndex` for a `long` index, and so on, which makes the names harder to read without adding any more information than is already in the type. This became known as "Systems Hungarian", because the group was in the operating systems division, and unfortunately Systems Hungarian made its way throughout the "Win32" Windows APIs, which were the main APIs for Windows until recently. Lots of Windows APIs got hard-to-read names because of a misunderstanding! Once again, naming is not the only way to solve this issue, only one way to solve it. In the F# programming language, you can declare variables with units, such as `let distance = 30<cm>`, and the compiler will check that comparisons and computations make sense given the units. --- #### Exercise The following names all look somewhat reasonable, why are they poor? - `pickle` (in Python) - `binhex` (in Python) - `LinkedList<E>` (in Java's `java.util`) - `vector<T>` (in C++'s `std`) - `SortedList` (in C#'s `System.Collections`) <details> <summary>Answers (click to expand)</summary> <p> `pickling` is a rather odd way to refer to serializing and deserializing data as "preserving" it. `binhex` sounds like a name for some binary and hexadecimal utilities, but it's actually for a module that handles an old Mac format. A linked list and a doubly linked list are not the same thing, yet Java names the latter as if it was the former. A vector has a specific meaning in mathematics; C++'s `vector` is really a resizeable array. `SortedList` is an acceptable name for a sorted list class. But the class with that name is a sorted map! </p> </details> --- Overall, names are a tool to make code clear and succinct, as well as consistent with other code so that readers don't have to explicitly think about names. ### Documentation _Documentation_ is a tool to explain _what_ a piece of code does. Documentation is the main way developers learn about the code they use. When writing code, developers consult its documentation comments, typically within an IDE as tooltips. Documentation comments should thus succinctly describe what a class or method does, including information developers are likely to need such as whether it throws exceptions, or whether it requires its inputs to be in some specific format. ### Comments _Comments_ are a tool to _why_ a piece of code does what it does. Importantly, comments should not say _how_ a piece of code does what it does, as this information already exists in the code itself. Unfortunately, not all code is "self-documenting". Comments are a way to explain tricky code. Sometimes, code has to be written in a way that looks overly complicated or wrong because the code is working around some problem in its environment, such as a bug in a library, or a compiler that only produces fast assembly code in specific conditions. Consider the following good example of a comment, taken from an old version of the Java development kit's `libjsound`: ```c /* Workaround: 32bit app on 64bit linux gets assertion failure trying to open ports. Until the issue is fixed in ALSA (bug 4807) report no midi in devices in the configuration. */ if (jre32onlinux64) { return 0; } ``` This is a great example of an inline comment: it explains what the external problem is, what the chosen solution is, and refers to an identifier for the external problem. This way, a future developer can look up that bug in ALSA, a Linux audio system, and check if was fixed in the meantime so that the code working around the bug can be deleted. Inline comments are a way to explain code beyond what code itself can do, which is often necessary even if it ideally should not be. This explanation can be for the people who will review your code before accepting your proposed changes, or for colleagues who will read your code when working on the codebase months later. Don't forget that one of these "colleagues" is likely "future you". No matter how clear you think a piece of code is right now, future you will be grateful for comments that explain the non-obvious parts. ### Formatting Formatting code is all about making it easier to read code. You don't notice good formatting, but you do notice bad formatting, and it makes it harder to focus. Here is a real world example of bad formatting: ```c if (!update(&context, &params)) goto fail; goto fail; ``` Did you spot the problem? The code looks like the second `goto` is redundant, because it's formatted that way. But this is C. The second `goto` is actually outside of the scope of the `if`, and is thus always executed. This was a real bug that triggered [a vulnerability](https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/) in Apple products. Some languages enforce at least some formatting consistency, such as Python and F#. But as you saw with the `planets.py` exercise earlier, that does not mean it's impossible to format one's code poorly. ### Consistency Should you use `camelCase` or `snake_case` for your names? 4 or 8 spaces for indentation? Or perhaps tabs? So many questions. This is what _conventions_ are for. The entire team decides, once, what to do. Then every member of the team accepts the decisions, and benefits from a consistent code style without having to explicitly think about it. Beware of a common problem called _bikeshedding_ when deciding on conventions. The name comes from the story illustrating it: a city council meeting has two items on the agenda, the maintenance of a nuclear power plant and the construction of a bike shed. The council quickly approves the nuclear maintenance, which is very expensive, because they all agree that this maintenance is necessary to continue to provide electricity to the city. Then the council spends an hour discussing the plans for the bike shed, which is very cheap. Isn't it still too expensive? Surely the cost can be reduced a bit, a bike shed should be even cheaper. Should it be blue or red? Or perhaps gray? How many bikes does it need to contain? It's easy to spend lots of time on small decisions that ultimately don't matter much, because it's easy to focus on them. But that time should be spent on bigger decisions that are more impactful, even if they are harder to discuss. Once you have agreed on a convention, you should use tools to enforce it, not manual efforts. Command-line tools exist, such as `clang-format` for C code, as well as tools built into IDEs, which can be configured to run whenever you save a file. That way, you no longer have to think about what the team's preferences are, tools do it for you. ## How can one efficiently debug a program? Your program just got a bug report from a user: something doesn't work as expected. Now what? The presence of a bug implies that the code's behavior doesn't match the intent of the person who wrote it. The goal of _debugging_ is to find and fix the _root cause_ of the bug, i.e., the problem in the code that is the source of the bug. This is different from the _symptoms_ of the bug, in the same way that symptoms of a disease such as loss of smell are different from a root cause such as a virus. You will find the root cause by repeatedly asking "_why?_" when you see symptoms until you get to the root cause. For instance, let's say you have a problem: you arrived late to class. Why? Because you woke up late. Why? Because your alarm didn't ring. Why? Because your phone had no battery. Why? Because you forgot to plug your phone before going to sleep. Aha! That's the cause of the bug. If you had stopped at, say, "your alarm didn't ring", and tried to fix it by adding a second phone with an alarm, you would simply have two alarms that didn't ring, because you would forget to plug in the second phone as well. But now that you know you forgot to plug in your phone, you can attack the root cause, such as by putting a post-it above your bed reminding you to charge your phone. You could in theory continue asking "why?", but it stops being helpful after a few times. In this case, perhaps the "real" root cause is that you forget things often, but you cannot easily fix that. At a high level, there are three steps to debugging: reproduce the bug, isolate the root cause, and debug. Reproducing the bug means finding the conditions under which it appears: - What environment? Is it on specific operating systems? At specific times of the day? In specific system languages? - What steps need to be taken to uncover the bug? These could be as simple as "open the program, click on the 'login' button, the program crashes", or more complex, such as creating multiple users with specific properties and then performing a sequence of tasks that trigger a bug. - What's the expected outcome? That is, what do you expect to happen if there is no bug? - What's the actual outcome? This could be simply "a crash", or it could be something more complex, such as "the search results are empty even though there is one item matching the search in the database" - Can you reproduce the bug with an automated test? This makes it easier and less error-prone to check if you have fixed the bug or not. Isolating the bug means finding roughly where the bug comes from. For instance, if you disable some of your program's modules by commenting out the code that uses them, does the bug still appear? Can you find which modules are necessary to trigger the bug? You can also isolate using version control: does the bug exist in a previous commit? If so, what about an even older commit? Can you find the one commit that introduced the bug? If you can find which commit introduced the bug, and the commit is small enough, you have drastically reduced the amount of code you need to look at. Finally, once you've reproduced and isolated the bug, it's time to debug: see what happens and figure out why. You could do this with print statements: ```c printf("size: %u, capacity: %u\n", size, capacity); ``` However, print statements are not convenient. You have to write potentially a lot of statements, especially if you want to see the values within a data structure or an object. You may not even be able to see the values within an object if they are private members, at which point you need to add a method to the object just to print some of its private members. You also need to manually remove prints after you've fixed the bug. Furthermore, if you realize while executing the program that you forgot to print a specific value, using prints forces you to stop the program, add a print, and run it again, which is slow. Instead of print statements, use a tool designed for debugging: a debugger! ### Debuggers A debugger is a tool, typically built into an IDE, that lets you pause the execution of a program wherever you want, inspect what the program state is and even modify the state, and generally look at what a piece of code is actually doing without having to modify that piece of code. One remark about debuggers, and tools in general: some people think that not using a tool, and doing it the "hard" way instead, somehow makes them better engineers. This is completely wrong, it's the other way around: knowing what tools are available and using them properly is key to being a good engineer. Just like you would ignore people telling you to not take a flashlight and a bottle of water when going hiking in a cave, ignore people who tell you to not use a debugger or any other tool you think is useful. Debuggers also work for software that runs on other machines, such as a server, as long as you can launch a debugging tool there, you can run the graphical debugger on your machine to debug a program on a remote machine. There are also command-line debuggers, such as `jdb` for Java or `pdb` for Python, though these are not as convenient since you must manually input commands to, e.g., see what values variables have. The one prerequisite debuggers have is a file with _debug symbols_: the link between the source code and the compiled code. That is, when the program executes a specific line of assembly code, what line is it in the source code? What variables exist at that point, and in which CPU registers are they? This is of course not necessary for interpreted languages such as Python, for which you have the source code anyway. It is technically possible to run a debugger without debug symbols, but you then have to figure out how the low-level details map to high-level concepts yourself, which is tedious. Let's talk about five key questions you might ask yourself while debugging, and how you can answer them with a debugger. _Does the program reach this line?_ Perhaps you wonder if the bug triggers when a particular line of code executes. To answer this question, use a _breakpoint_, which you can usually do by right-clicking on a line and selecting "add a breakpoint" from the context menu. Once you have added a breakpoint, run the program in debug mode, and execution will pause once that line is reached. Debuggers typically allow more advanced breakpoints as well, such as "break only if some condition holds", or "break once every N times this line is executed". You can even use breakpoints to print things instead of pausing execution. Wait, didn't we just say prints weren't a good idea? The reason why printing breakpoints are better is that you don't need to edit the code, and thus don't need to revert those edits later, and you can change what is printed where while the program is running. _What's the value of this variable?_ You've added a breakpoint, the program ran to it and paused execution, now you want to see what's going on. In an IDE, you can typically hover your mouse over a variable in the source code to see its value while the program is paused, as well as view a list of all local variables. This includes the values within data structures such as arrays, and the private members in classes. You can also execute code to ask questions, such as `n % 12 == 0` to see if `n` is currently a multiple of 12, or `IsPrime(n)` if you have an `IsPrime` method and want to see if what it returns for `n`. _What if instead...?_ You see that a variable has a value you didn't expect, and wonder if the bug would disappear if it had a different value. Good news: you can try exactly that. Debuggers typically have some kind of "command" window where you can write lines such as `n = 0` to change the value of `n`, or `lst.add("x")` to add `"x"` to the list `lst`. _What will happen next?_ The program state looks fine, but maybe the next line is what causes the problem? "Step" commands let you execute the program step-by-step, so that you can look at the program state after executing each step to see when something goes awry. "Step into" will let you enter any method that is called, "step over" will go to the next line instead of entering a method, and "step out" will finish executing the current method. Some debuggers have additional tools, such as a "smart" step that only goes inside methods with more than a few lines. Depending on the programming language and the debugger, you might even be able to change the instruction pointer to whichever line of code you want, and edit some code on the fly without having to stop program execution. Note that you don't have to use the mouse to run the program and run step by step: debuggers typically have keyboard shortcuts, such as using F5 to run, F9 to step into, and so on, and you can usually customize those. Thus, your workflow will be pressing a key to run, looking at the program state after the breakpoint is hit, then pressing a key to step, looking at the program state, stepping again, and so on. _How did we get here?_ You put a breakpoint in a method, the program reached it and paused execution, but how did the program reach this line? The _call stack_ is there to answer this: you can see which method called you, which method called that one, and so on. Not only that, but you can view the program state at the point of that call. For instance, you can see what values were given as arguments to the method who called the method who called the method you are currently in. _What happened to cause a crash?_ Wouldn't it be nice if you could see the program state at the point at which there was a crash on a user's machine? Well, you can! The operating system can generate a _crash dump_ that contains the state of the program when it crashes, and you can load that crash dump into a debugger, along with the source code of the program and the debugging symbols, to see what the program state was. This is what happens when you click on "Report the problem to Microsoft" after your Word document crashed. Note that this only works with crashes, not with bugs such as "the behavior is not what I expect" since there is no automated way to detect such unexpected behavior. ### Debugging in practice When using a debugger to find the root cause of a bug, you will add a breakpoint, run the program until execution pauses to inspect the state, optionally make some edits to the program given your observations, and repeat the cycle until you have found the root cause. However, sometimes you cannot figure out the problem on your own, and you need help. This is perfectly normal, especially if you are debugging code written by someone else. In this case, you can ask a colleague for help, or even post on an Internet forum such as [StackOverflow](https://stackoverflow.com). Come prepared, so that you can help others help you. What are the symptoms of the bug? Do you have an easy way to reproduce the bug? What have you tried? Sometimes, you start explaining your problem to a colleague, and during your explanation a light bulb goes off in your head: there's the problem! Your colleague then stares at you, happy that you figured it out, but a bit annoyed to be interrupted. To avoid this situation, start by _rubber ducking_: explaining your problem to a rubber duck, or to any other inanimate object. Talk to the object as if it was a person, explaining what your problem is. The reason this works is that when we explain a problem to someone else, we typically explain what is actually happening, rather than what we wish was happening. If you don't understand the problem while explaining it to a duck, at least you have rehearsed how you will explain the bug, and you will be able to better explain it to a human. There is only one way to get better at debugging: practice doing it. Next time you encounter a bug, use a debugger. The first few times, you may be slower than you would be without one, but after that your productivity will skyrocket. --- #### Exercise Run the code in the [binary-tree](exercises/lecture/binary-tree) folder. First, run it. It crashes! Use a debugger to add breakpoints and inspect what happens until you figure out why, and fix the bugs. Note that the crash is not the only bug. <details> <summary>Solution (click to expand)</summary> <p> First, there is no base case to the recursive method that builds a tree, so you should add one to handle the `list.size() == 0` case. Second, the bounds for sub-lists are off: they should be `0..mid` and `mid+1..list.size()`. There is a correctness bug: the constructor uses `l` twice, when it should set `right` to `r`. This would not have happened if the code used better names! We provide a [corrected version](exercises/solutions/lecture/BinaryTree.java). </p> </details> ## What makes code debuggable? The inventor [Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage) once said about a machine of his "_On two occasions, I have been asked 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?'_ _I am not able to rightly apprehend the kind of confusion of ideas that could provoke such a question._" It should be clear that a wrong input cannot lead to a correct output. Unfortunately, often a wrong input leads to a wrong output _silently_: there is no indication that anything wrong happened. This makes it hard to find the root cause of a bug. If you notice something is wrong, is it because the previous operation did something wrong? Or because the operation 200 lines of code earlier produced garbage that then continued unnoticed until it finally caused a problem? [Margaret Hamilton](https://en.wikipedia.org/wiki/Margaret_Hamilton_\(software_engineer\)), who coined the term "software engineering" to give software legitimacy based on her experience developing software for early NASA missions, [said](https://www.youtube.com/watch?v=ZbVOF0Uk5lU) of her early work "we learned to spend more time up front [...] so that we wouldn't waste all that time debugging". We will see three methods to make code debuggable: defensive programming, logging, and debug-only code. ### Defensive programming Bugs are attacking you, and you must defend your code and data! That's the idea behind _defensive programming_: make sure that problems that happen outside of your code cannot corrupt your state or cause you to return garbage. These problems could for instance be software bugs, humans entering invalid inputs, humans deliberately trying to attack the software, or even hardware corruption. It may seem odd to worry about hardware corruption, but it happens more often than one thinks; for instance, a single bit flip can turn `microsoft.com` into `microsfmt.com`, since `o` is usually encoded as `01101101` in binary, which can flip to `01101111`, the encoding for `m`. Software that intends to talk to `microsoft.com` could thus end up receiving data from `microsfmt.com` instead, which may be unrelated, specifically set up for attacks, or [an experiment to see how much this happens](http://dinaburg.org/bitsquatting.html). Instead of silently producing garbage, code should fail as early as possible. The closest a failure is to its root cause, the easier it is to debug. The key tool to fail early is _assertions_. An assertion is a way to check whether the code actually behaves in the way the engineer who wrote it believes it should. For instance, if a piece of code finds the `index` of a `value` in an `array`, an engineer could write the following immediately after finding `index`: ```java if (array[index] != val) { throw new AssertionError(...); } ``` If this check fails, there must be a bug in the code that finds `index`. The "isolate the bug" step of debugging is already done by the assertion. What should be done if the check fails, though? Crash the program? This depends on the program. Typically, if there is a way to cut off whatever caused the problem from the rest of the program, that's a better idea. For instance, the current _request_ could fail. This could be a request made to a server, for instance, or an operation triggered by a user pressing a button. The software can then display a message stating an error occurred, enabling the user to either retry or do something else. However, some failures are so bad that it is not reasonable to continue. For instance, if the code loading the software's configuration fails an assertion, there is no point in continuing without the configuration. An assertion that must hold when calling a method is a _precondition_ of that method. For instance, an `int pickOne(int[] array)` method that returns one of the array's elements likely has as precondition "the array isn't `null` and has at least `1` element". The beginning of the method might look like this: ```java int pickOne(int[] array) { if (array == null || array.length == 0) { throw new IllegalArgumentException(...); } // ... } ``` If a piece of code calls `pickOne` with a null or empty array, the method will throw an `IllegalArgumentException`. Why bother checking this explicitly when the method would fail early anyway if the array was null or empty, since the method will dereference the array and index its contents? The type of exception thrown indicates _whose fault it is_. If you call `pickOne` and get a `NullPointerException`, it is reasonable to assume that `pickOne` has a bug, because this exception indicates the code of `pickOne` believes a given reference is non-null, since it dereferences it, yet in practice the reference is null. However, if you call `pickOne` and get an `IllegalArgumentException`, it is reasonable to assume that your code has a bug, because this exception indicates you passed an argument whose value is illegal. Thus, the type of exception helps you find where the bug is. An assertion that must hold when a method returns is a _postcondition_ of that method. In our example, the postcondition is "the returned value is some value within the array", which is exactly what you call `pickOne` to get. If `pickOne` returns a value not in the array, code that calls it will yield garbage, because the code expected `pickOne` to satisfy its contract yet this did not happen. It isn't reasonable to insert assertions every time one calls a method to check that the returned value is acceptable; instead, it's up to the method to check that it honors its postcondition. For instance, the end of `pickOne` might look like this: ```java int result = ... if (!contains(array, result)) { throw new AssertionError(...); } return result; ``` This way, if `result` was computed incorrectly, the code will fail before corrupting the rest of the program with an invalid value. Some assertions are both pre- and postconditions for the methods of an object: _object invariants_. An invariant is a condition that always hold from the outside. It may be broken during an operation, as long as this is not visible to the outside world because it is restored before the end of the operation. For instance, consider the following fields for a stack: ```java class Stack { private int[] values; private int top; // top of the stack within `values` } ``` An object invariant for this class is `-1 <= top < values.length`, i.e., either `top == -1` which means the stack is empty, or `top` points to the top value of the stack within the array. One way to check invariants is to write an `assertInvariants` method that asserts them and call it at the end of the constructor and the beginning and end of each method. All methods of the class must preserve the invariant so that they can also rely on it holding when they get called. This is one reason encapsulation is so useful: if anyone could modify `values` or `top` without going through the methods of `Stack`, there would be no way to enforce this invariant. Consider the following Java method: ```java void setWords(List<String> words) { this.words = words; } ``` It seems trivially correct, and yet, it can be used in the following way: ``` setWords(badWords); badWords.add("Bad!"); ``` Oops! Now the state of the object that holds `words` has been modified from outside of the object, which could break any invariants the object is supposed to have. To avoid this and protect one's state, _data copies_ are necessary when dealing with mutable values: ```java void setWords(List<String> words) { this.words = new ArrayList<>(words); } ``` This way, no changes can occur to the object's state without its knowledge. The same goes for reads, with `return this.words` being problematic and `return new ArrayList<>(this.words)` avoiding the problem. Even better, if possible the object could use an _immutable_ list for `words`, such as Scala's default `List[A]`. This fixes the problem without requiring data copies, which slow down the code. --- #### Exercise Check out the code in the [stack](exercises/lecture/stack) folder, which contains an `IntStack` class and a usage example. Add code to `IntStack` to catch problems early, and fix any bugs you find in the process. First, look at what the constructor should do. Once you've done that, add an invariant and use it, and a precondition for `push`. Then fix any bugs you find. <details> <summary>Solution (click to expand)</summary> <p> First, the constructor needs to throw if `maxSize < 0`, since that is invalid. Second, the stack should have the invariant `-1 <= top < values.length`, as discussed above. After adding this invariant, note that `top--` in `pop` can break the invariant since it is used unconditionally. The same goes for `top++` in `push`. These need to be changed to only modify `top` if necessary. To enable the users of `IntStack` to safely call `push`, one can expose an `isFull()` method, and use it as a precondition of `push`. We provide a [corrected version](exercises/solutions/lecture/Stack.java). </p> </details> ### Logging _What happened in production?_ If there was a crash, then you can get a crash dump and open it in a debugger. But if it's a more subtle bug where the outcome "looks wrong" to a human, how can you know what happened to produce this outcome? This is where _logging_ comes in: recording what happens during execution so that the log can be read in case something went wrong. One simple way to log is print statements: ```python print("Request: " + request) print("State: " + state) ``` This works, but is not ideal for multiple reasons. First, the developer must choose what to log at the time of writing the program. For instance, if logging every function call is considered too much for normal operation, then the log of function calls will never be recorded, even though in some cases it could be useful. Second, the developer must choose how to log at the time of writing the program. Should the log be printed to the console? Saved to a file? Both? Perhaps particular events should send an email to the developers? Third, using the same print function for every log makes it hard to see what's important and what's not so important. Instead of using a specific print function, logging frameworks provide the abstraction of a log with multiple levels of importance, such as Python's logging module: ```python logging.debug("Detail") logging.info("Information") logging.warning("Warning") logging.error("Error") logging.critical("What a Terrible Failure") ``` The number of log levels and their name changes in each logging framwork, but the point is that there are multiple ones and they do not imply anything about where the log goes. Engineers can write logging calls for everything they believe might be useful, using the appropriate log level, and decide _later_ what to log and where to log. For instance, by default, "debug" and "info" logs might not even be stored, as they are too detailed and not important enough. But if there is currently a subtle bug in production, one can enable them to see exactly what is going on, without having to restart the program. It may make sense to log errors with an email to the developers, but if there are lots of errors the developers are already aware of, they might decide to temporarily log errors to a file instead, again without having to restart the program. It is important to think about privacy when writing logging code. Logging the full contents of every request, for instance, might lead to logging plain text passwords for a "user creation" function. If this log is kept in a file, and the server is hacked, the attackers will have a nice log of every password ever set. ### Debug-only code What about defensive programming checks and logs that are too slow to reasonably enable in production? For instance, if a graph has as invariant "no node has more than 2 edges", but the graph typically has millions of nodes, what to do? This is where _debug-only_ code comes in. Programming languages, their runtimes, and frameworks typically offer ways to run code only in debug mode, such as when running automated tests. For instance, in Python, one can write an `if __debug__:` block, which will execute only when the code is not optimized. It's important to double-check what "debug" and "optimized" mean in any specific context. For instance, in Python `__debug__` is `True` by default, unless the interpreter is run with the `-O` switch, for "optimize". In Java, assertions are debug-only code but they are disabled by default, and can be enabld with the `-ea` switch. Scala has multiple levels of debug-only code that are all on by default but can be selectively disabled with the `-Xelide-below` switch. Even more important, before writing debug-only code, think hard about what is "reasonable" to enable in production given the workloads you have. Spending half a second checking an invariant is fine in a piece of code that will take seconds to run because it makes many web requests, for instance, even though half a second is a lot in CPU time. Keep in mind what [Tony Hoare](https://en.wikipedia.org/wiki/Tony_Hoare), one of the pioneers of computer science and especially programming languages and verification, once said in his ["Hints on Programming Language Design"](https://dl.acm.org/doi/abs/10.5555/63445.C1104368): "_It is absurd to make elaborate security checks on debugging runs, when no trust is put in the results,_ _and then remove them in production runs, when an erroneous result could be expensive or disastrous._ _What would we think of a sailing enthusiast who wears his life-jacket when training on dry land_ _but takes it off as soon as he goes to sea?_" ## Summary In this lecture, you learned: - How to write readable code: naming, formatting, comments, conventions - How to debug code: reproducing bugs, using a debugger - How to write debuggable code: defensive programming, logging, debug-only code You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Asynchrony You're writing an app and want it to download data and process it, so you write some code: ```java data = download(); process(data); ``` This works fine if both of these operations finish in the blink of an eye... but if they take more than that, since these operations are all your code is doing, your user interface will be frozen, and soon your users will see the dreaded "application is not responding" dialog from the operating system. Even if your app has no user interface and works in the background, consider the following: ```java firstResult = computeFirst(); secondResult = computeSecond(); compare(firstResult, secondResult); ``` If `computeFirst` and `computeSecond` are independent, the code as written is likely a waste of resources, since modern machines have multiple CPU cores and thus your app could have computed them in parallel before executing the comparison on both results. Even if you have a single CPU core, there are other resources, such as the disk: ```java for (int i = 0; i < 100; i++) { chunk = readFromDisk(); process(chunk); } ``` As written, this code will spend some of its time reading from the disk, and some of its time processing the data that was read, but never both at the same time, which is a waste of resources and time. These examples illustrate the need for _asynchronous code_. For instance, an app can start a download in the background, show a progress bar while the download is ongoing, and process the data once the download has finished. Multiple computations can be executed concurrently. A disk-heavy program can read data from the disk while it is processing data already read. ## Objectives After this lecture, you should be able to: - Understand _asynchrony_ in practice - Build async code with _futures_ - Write _tests_ for async code - _Design_ async software components ## What are async operations? Asynchronous code is all about starting an operation without waiting for it to complete. Instead, one schedules what to do after the completion. Asynchronous code is _concurrent_, and if resources are available it can also be _parallel_, though this is not required. There are many low-level primitives you could use to implement asynchrony: threads, processes, fibers, and so on. You could then use low-level interactions between those primitives, such as shared memory, locks, mutexes, and so on. You could do all of that, but low-level concurrency is _very hard_. Even experts who have spent years understanding hardware details regularly make mistakes. This gets even worse with multiple kinds of hardware that provide different guarantees, such as whether a variable write is immediately visible to other threads or not. Instead, we want a high-level goal: do stuff concurrently. An asynchronous function is similar to a normal function, except that it has two points of return: synchronously, to let you know the operation has started, and asynchronously, to let you know the operation has finished. Just like a synchronous function can fail, an asynchronous function can fail, but again at two points: synchronously, to let you know the operation cannot even start, perhaps because you gave an invalid argument, and asynchronously, to let you know the operation has failed, perhaps because there was no Internet connection even after retrying in the background. We would like our asynchronous operations to satisfy three goals: they should be composable, they should be completion-based, and they should minimize shared state. Let's see each of these three. ### Composition When baking a cake, the recipe might tell you "when the melted butter is cold _and_ the yeast has proofed, _then_ mix them to form the dough". This is a kind of composition: the recipe isn't telling you to stand in front of the melted butter and watch it cool, rather it lets you know what operations must finish for the next step and what that next step is. You are free to implement the two operations however you like; you could stand in front of the butter, or you could go do something else and come back later. Composition is recursive: once you have a dough, the next step might be "when the dough has risen _and_ the filling is cold, _then_ fill the dough". Again, this is a composition of asynchronous operations into one big operation representing making a filled dough. The two previous examples were _and_, but _or_ is also a kind of composition. The recipe might tell you "bake for 30 minutes, _or_ until golden brown". If the cake looks golden brown after 25 minutes, you take it out of the oven, and forget about the 30 minutes. One important property of composition is that errors must implicitly compose, too. If the ripe strawberries you wanted to use for the filling splash on the floor, your overall "bake a cake" operation has failed. The recipe doesn't explicitly tell you that, because it's a baking convention that if any step fails, you should stop and declare the whole operation a failure, unless you can re-do the failed operation from scratch. Maybe you have other strawberries you can use instead. ### Completion If you have a cake you'd like to bake, you could ask a baker "please let me know when you've finished baking the cake", which is _completion-based_. Alternatively, you could ask them "please let me know when the oven is free" and then bake it yourself, which is a bit lower level and gives you more control. This is _readiness-based_, and some older APIs, such as those found on Unix, were designed that way. The problem with readiness-based operations is that they lead to inefficiencies due to concurrent requests. The baker just told you the oven was ready, but unbeknownst to you, another person has put their cake in the oven before you've had time to get there. Now your "put the cake in the oven" operation will fail, and you have to ask the baker to let you know when the oven is free again, at which point the same problem could occur. ### Minimizing shared state Multiple asynchronous operations might need to read and write to the same shared state. For instance, the task of counting all elements in a large collection that satisfy some property could be parallelized by dividing the collection into chunks and processing multiple chunks in parallel. Each sub-task could then increment a global counter after every matching element it sees. However, shared state introduces an exponential explosion in the number of paths through a piece of software. There is one path in which the code of sub-task 1 accesses the shared state first, and one in which sub-task 2 accesses it first, and so on for each sub-task and for each shared state access. Even with a simple counter, one already needs to worry about atomic updates. With more complex shared state, one needs to worry about potential bugs that only happen with specific "interleavings" of sub-task executions. For instance, there may be a crash only if sub-task 3 accessed shared state first, followed by 2, followed by 3 again, followed by 1. This may only happen to a small fraction of users. Then one day, a developer speeds up the code of sub-task 3, and now the bug happens more frequently because the problematic interleaving is more common. The next day, a user gets an operating system update which slightly changes the scheduling policy of threads in the kernel. Now the bug happens all the time for this user, because the operating system happens to choose an order of execution that exposes the bug on that user's machine. Asynchronous operations must minimize shared state, for instance by computing a local result, then merging all local results into a single global result at the end. One extreme form of minimizing state is _message passing_: operations send each other messages rather than directly accessing the same state. For instance, operations handling parts of a large collection could do their work and then send their local result as a message to another "monitor" operation which is responsible for merging these results. Message passing is the standard way to communicate for operations across machines already, so it can make sense to do it even on a single machine. One interesting use of this is the [Multikernel](https://www.sigops.org/s/conferences/sosp/2009/papers/baumann-sosp09.pdf), an operating system that can run on multiple local CPUs each of a different architecture, because it uses only message passing and never shared memory, thus what each local thread runs on is irrelevant. ## How can we write maintainable async code? A simple and naïve way to write asynchronous code is with _callbacks_. Instead of returning a value, functions take an additional callback argument that is called with the value once it's ready: ```java void send(String text, Consumer<String> callback); send("hello", reply -> { System.out.println(reply); }); ``` One can call an asynchronous function within a callback, leading to nested callbacks: ```java send("hello", reply -> { send("login", reply2 -> { // ... }); }); ``` But this becomes rather messy. And we haven't even discussed errors yet, which need another callback: ```java void send( String text, Consumer<String> callback, Consumer<Exception> errorCallback ); ``` Code that uses callbacks frequently ends in "callback hell": ```java send("hello", reply -> { send("login", reply2 -> { send("join", reply3 -> { send("msg", reply4 -> { send("msg", reply5 -> { send("logout", reply6 -> { // ... }); }); }); }); }); }); ``` This code is hard to read and to maintain, because callbacks are _too_ simple and low-level. They do not provide easy ways to be composed, especially when dealing with errors as well. The resulting code is poorly structured. Just because something is simple does not mean it is good! Instead of overly-simple callbacks, modern code uses _futures_. A future is an object that represents an operation in one of three states: in progress, finished successfully, or failed. In Java, futures are represented with the `CompletableFuture<T>` class, where T is the type of the result. Since `void` is not a type, Java has the type `Void` with a capital `V` to indicate no result, thus an asynchronous operation that would return `void` if it was synchronous instead returns a `CompletableFuture<Void>`. `CompletableFuture`s can be composed with synchronous operations and with asynchronous operations using various methods. ### Composing `CompletableFuture`s The `thenAccept` method creates a future that composes the current one with a synchronous operation. If the current future fails, so does the overall future; but if it succeeds, the overall future represents applying the operation to the result. And if the operation fails, the overall future has failed: ```java CompletableFuture<String> future = // ... return future.thenAccept(System.out::println); ``` Sometimes a failure can be replaced by some kind of "backup" value, such as printing the error message if there is one instead of not printing anything. The `exceptionally` method returns a future that either returns the result of the current future if there is one, or transforms the future's exception into a result: ```java return future.exceptionally(e -> e.getMessage()) .thenAccept(System.out::println); ``` One may wish to not potentially wait forever, such as when making a network request if the server is very slow or the network connectivity is just good enough to connect but not good enough to transmit data at a reasonable rate. Implementing timeouts properly is difficult, but thankfully the Java developers provided a method to do it easily: ```java return future.orTimeout(5, TimeUnit.SECONDS) .exceptionally(e -> e.getMessage()) .thenAccept(System.out::println); ``` The returned combined future represents: - Printing the result of the original future, if it completes successfully within 5s - Printing the failure of the original future, if it fails within 5s - Printing the message from the timeout error, if the original future takes more than 5s Futures can be composed with asynchronous operations too, such as with `thenCompose`: ```java CompletableFuture<String> getMessage(); CompletableFuture<Void> log(String text); return getMessage().thenCompose(log); ``` The returned future represents first getting the message, then logging it, or failing if either of these operations fail. Composing futures in parallel and doing something with both results can be done with the `thenCombine` method: ```java CompletableFuture<String> computeFirst(); CompletableFuture<String> computeSecond(); return computeFirst().thenCombine(computeSecond(), (a, b) -> a + b); ``` The resulting future in this example represents doing both operations concurrently and returning the concatenation of their results, or failing if either future fails or if the combination operation fails. One can compose more than two futures into one that executes them all concurrently with a method such as allOf: ``` CompletableFuture<Void> uploads = ...; for (int n = 0; n < uploads.length; n++) { uploads[n] = ... } return CompletableFuture.allOf(uploads); ``` In the loop, each upload will start, and by the time the loop has ended, some of the uploads may have finished while others may still be in progress. The resulting future represents the combined operation. One can also use `anyOf` to represent the operation of waiting for any one of the futures to finish and ignoring the others. Refer to the [Javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/CompletableFuture.html) for the exact semantics of these operations on failures. _A quick warning about rate limits._ We have just seen code that allows one to easily upload a ton of data at the same time. Similar code can be written with an operation to download data, or to call some API that triggers an operation. However, in practice, many websites will rate limit users to avoid one person using too many resources. For instance, at the time of this writing, GitHub allows 5000 requests per hour. Doing too many operations in a short time may get you banned from an API, so look at the documentation of any API you're using carefully before starting hundreds of futures representing API calls. ### Creating `CompletableFuture`s One can create a future and complete it after some work in a background thread like so: ```java var future = new CompletableFuture<String>(); new Thread(() -> { // ... do some work ... future.complete("hello"); }).start(); return future; ``` Instead of `complete`, one can use `completeExceptionally` to fail the future instead, giving the exception that caused the failure as an argument instead of the result. This code forks execution into two logical threads: one that creates `future`, creates and starts the threads, and returns `future`; and one that contains the code in the `Thread` constructor. By the time `return future` executes, the future may already have been completed, or it may not. The beauty of futures is that the code that obtains the returned future doesn't have to care. Instead, it will use composition operations, which will do the right thing whether the future is already completed, still in progress, or will fail. Creating a Future representing a background operation is common enough that there is a helper method for it: ```java return CompletableFuture.supplyAsync(() -> { // ... do some work ... return "hello"; // or throw an exception to fail the Future }); ``` Sometimes one wants to create a future representing an operation that is already finished, perhaps because the result was cached. There is a method for that too: ```java return CompletableFuture.completedFuture("hello"); ``` However, creating futures is a low-level operation. Most code composes futures created by lower-level layers. For instance, a TCP/IP stack might create futures. Another reason to create futures is when adapting old asynchronous code that uses other patterns, such as callbacks. --- #### Exercise Take a look at the four methods in [`Basics.java`](exercises/lecture/src/main/java/Basics.java), and complete them one by one, based on the knowledge you've just acquired. You can run `App.java` to see if you got it right. <details> <summary>Suggested solution (click to expand)</summary> <p> - Printing today's weather is done by composing `Weather.today` with `System.out.println` using `thenAccept` - Uploading today's weather is done by composing `Weather.today` with `Server.upload` using `thenCompose` - Printing either weather is done using `acceptEither` on two individual futures, both of which use `thenApply` to prefix their results, with `System.out.println` as the composition operation - Finally, `Weather.all` should be composed with `orTimeout` and `exceptionallyCompose` to use `Weather.today` as a backup We provide a [solution example](exercises/solutions/lecture/src/main/java/Basics.java). </p> </details> --- ### Sync over async Doing the exercise above, you've noticed `App.java` uses `join()` to block until a future finishes and either return the result or throw the error represented by the future. There are other such "sync over async" operations, such as `isDone()` and `isCompletedExceptionallly()` to check a future's status. "Sync over async" operations are useful specifically to use asynchronous operations in a context that must be synchronous, typically because you are working with a framework that expects a synchronous operation. Java's `main()` method must be synchronous, for instance. JUnit also expects `@Test`s to be synchronous. This is not true of all frameworks, e.g., C# can have asynchronous main methods, and most C# testing frameworks support running asynchronous test methods. You might also need to use methods such as `isDone()` if you are implementing your own low-level infrastructure code for asynchronous functions, though that is a rare scenario. In general, everyday async functions must _not_ use `join()` or any other method that attempts to synchronously wait for or interact with an asynchronous operation. If you call any of these methods on a future outside of a top-level method such as `main` or a unit test, you are most likely doing something wrong. For instance, if in a button click handler you call `join()` on a `CompletableFuture` representing the download of a picture, you will freeze the entire app until the picture is downloaded. Instead, the button click handler should compose that future with the operation of processing the picture, and the app will continue working while the download and processing happen in the background. ### Sync errors Another form of synchrony in asynchronous operations is synchronous errors, i.e., signalling that an asynchronous operation could not even be created. Unlike asynchronous errors contained in Futures, which in Java are handled with methods such as `exceptionally(...)`, synchronous errors are handled with the good old `try { ... } catch { ... }` statement. Thus, if you call a method that could fail synchronously or asynchronously and you want to handle both cases, you must write the error handling code twice. Only use sync errors for bugs, i.e., errors that are not recoverable and indicate something has gone wrong such as an `IllegalArgumentException`: ```java CompletableFuture<Void> send(String s) { if (s == null) { // pre-condition violated, the calling code has a bug throw new IllegalArgumentException(...); } ... } ``` You will thus not have to duplicate error handling logic, because you will not handle unrecoverable errors. **Never** do something like this in Java: ```java CompletableFuture<Void> send(String s) { if (internetUnavailable) { // oh well, we already know it'll fail, we can fail synchronously...? throw new IOError(...); } ... } ``` This forces all of your callers to handle both synchronous and asynchronous exceptions. Instead, return a `CompletableFuture` that has failed already: ```java if (internetUnavailable) { return CompletableFuture.failedFuture(new IOError(...)); } ``` This enables your callers to handle that exception just like any other asynchronous failure: with future composition. Another thing you should **never** do is return a `null` future: ```java if (s.equals("")) { // nothing to do, might as well do nothing...? return null; } ``` While Java allows any value of a non-primitive type to be `null`, ideally `CompletableFuture` would disallow this entirely, as once again this forces all of your callers to explicitly handle the `null` case. Instead, return a `CompletableFuture` that is already finished: ```java if (s.equals("")) { return CompletableFuture.completedFuture(null); } ``` ### Cancellation One form of failure that is expected is _cancellation_: a future might fail because it has been explicitly canceled. Canceling futures is a common operation to avoid wasting resources. For instance, if a user has navigated away from a page which was still loading pictures, there is no point in finishing the download of these pictures, decoding them from raw bytes, and displaying them on a view that is no longer on screen. Cancellation is not only about ignoring a future's result, but actually stopping whatever operation was still ongoing. One may be tempted to use a method such as `Thread::stop()` in Java, but this method is obsolete for a good reason: forceful cancellation is dangerous. The thread could for instance be holding a lock when it is forcefully stopped, preventing any other thread from ever entering the lock. (`CompletableFuture` has a `cancel` method with a `mayInterruptIfRunning` parameter, but this parameter only exists because the method implements the more general interface `CompletionStage`; as the documentation explains, the parameter is ignored because forcefully interrupting a computation is not a good idea in general) Instead, cancellation should be _cooperative_: the operation you want to cancel must be aware that cancellation is a possibility, and provide a way to cancel at well-defined points in the operation. Some frameworks have built-in support for cancellation, but in Java you have to do it yourself. One way to do it is to pass around an `AtomicBoolean` value, which serves as a "box" to pass by reference a flag indicating whether a future should be canceled. Because this is shared state, you must be disciplined in its use: only write to it outside of the future, and only read from it inside of the future. The computation in the future should periodically check whether it should be canceled, and if so throw a cancellation exception instead of continuing: ```java for (int step = 0; step < 100; step++) { if (cancelFlag.get()) { throw new CancellationException(); } ... } ``` ### Progress If you've implemented cancellation and let your users cancel ongoing tasks, they might ask themselves "should I cancel this or not?" after a task has been running for a while. Indeed, if a task has been running for 10 minutes, one may want to cancel it if it's only 10% done, whereas if it's 97% done it's probably be better to wait. This is where _progress_ indication comes in. You can indicate progress in units that make sense for a given operation, such as "files copied", "bytes downloaded", or "emails sent". Some frameworks have built-in support for progress, but in Java you have to do it yourself. One way to do it is to pass around an `AtomicInteger` value, which serves as a "box" to pass by reference a counter indicating the progress of the operation relative to some maximum. Again, because this is shared state, you must be disciplined in its use, this time the other way around: only read from it outside of the future, and only write to it from inside of the future. The computation in the future should periodically update the progress: ```java for (int step = 0; step < 100; step++) { progress.set(step); ... } progress.set(100); ``` It is tempting to define progress in terms of time, such as "2 minutes remaining". However, in practice, the duration of most operations cannot be easily predicted. The first 10 parts of a 100-part operation might take 10 seconds, and then the 11th takes 20 seconds on its own; how long will the remaining 89 take? Nobody knows. This leads to poor estimates. One way to show something to users without committing to an actual estimate is to use an "indeterminate" progress bar, such as a bar that continuously moves from left to right. This lets users know something is happening, meaning the app has not crashed, and is typically enough if the operation is expected to be short so users won't get frustrated waiting. --- #### Exercise Take a look at the three methods in [`Advanced.java`](exercises/lecture/src/main/java/Advanced.java), and complete them one by one, based on the knowledge you've just acquired. Again, you can run `App.java` to see if you got it right. <details> <summary>Suggested solution (click to expand)</summary> <p> - `Server.uploadBatch` should be modified to support cancellation as indicated above, and then used in a way that sets the cancel flag if the operation times out using `orTimeout` - Converting `OldServer.download` can be done by creating a `CompletableFuture<String>` and passing its `complete` and `completeExceptionally` methods as callbacks - Reliable downloads can be implemented in the equivalent of a recursive function: `download` composed with `reliableDownload` if it fails, using `exceptionallyCompose` We provide a [solution example](exercises/solutions/lecture/src/main/java/Advanced.java). </p> </details> --- ### In other languages We have seen futures in Java as `CompletableFuture`, but other languages have roughly the same concept with different names such as `Promise` in JavaScript, `Task<T>` in C#, and `Future` in Rust. Importantly, operations on these types don't always have the exact same semantics, so be sure to read their documentation before using them. Some languages have built-in support for asynchronous operations. Consider the following C# code: ```csharp Task<string> GetAsync(string url); async Task WriteAsync() { var text = await GetAsync("epfl.ch"); Console.WriteLine(text); } ``` `Task<T>` is C#'s future equivalent, so `GetAsync` is an asynchronous operation that takes in a string and returns a string. `WriteAsync` is marked `async`, which means it is an asynchronous operation. When it calls `GetAsync`, it does so with the `await` operator, which is a way to compose futures while writing code that looks and feels synchronous. To be clear, `WriteAsync` is an asynchronous operation and does not block. It is equivalent to explicitly returning `GetAsync("epfl.ch")` composed with `Console.WriteLine`, C#'s equivalent of `System.out.println`. But because the language supports it, the compiler does all of the future composition, an engineer can write straightforward asynchronous code without having to explicitly reason about future composition. It is still possible to explicitly compose futures, such as with `Task.WhenAll` to compose many futures into one. Handling failures is also easier: ```csharp try { var text = await GetAsync("epfl.ch"); Console.WriteLine(text); } catch (Exception) { ... } ``` Whether `GetAsync` fails synchronously or asynchronously, the handling is in the `catch` block, and the compiler takes care of transforming this code into code that composes futures in the expected way. Similarly, Kotlin uses "coroutines", a form of lightweight threads, which can be suspended by `suspend` functions: ```kotlin suspend fun getAsync(url: String): String suspend fun writeAsync() { val content = getAsync("epfl.ch") println(content) } ``` Once again, this code is fully asynchronous: when `writeAsync` calls `getAsync`, it can get _suspended_, and the language runtime will then schedule another coroutine that is ready to run, such as one that updates the user interface with a progress bar. Kotlin can also handle both kinds of failures with a `catch` block. ### Futures as functions Now that we've seen different kinds of futures, let's take a step back and think of what a future is at a high level. There are two fundamental operations for futures: (1) turning a value, or an error, to a future; and (2) combining a future with a function handling its result into a new future. The first operation, creation, is two separate methods in Java's `CompletableFuture`: `completedFuture` and `failedFuture`. The second operation, transformation, is the `thenCompose` method in Java, which takes a future and a function from the result to another future and returns the aggregate future. You may have already seen this pattern before. Consider Java's `Optional<T>`. One can create a full or empty optional with the `of` and `empty` methods, and transform it with the `flatMap` method. In the general case, there are two operations on a "value of T" type: create a `Value<T>` from a `T`, and map a `Value<T>` with a `T -> Value<U>` function to a `Value<U>`. Mathematically-inclined folks use different names for these. "Create" is called "Return", "Map" is called "Bind", and the type is called a _monad_. What's the use of knowing about monads? You can think of monads as a kind of design pattern, a "shape" for abstractions. If you need to represent some kind of "box" that can contain values, such as an optional, a future, or a lists, you already know many useful methods you should provide: the ones you can find on optionals, futures, and lists. Consider the following example from the exercises: ```java return Weather.today() .thenApply(w -> "Today: " + w) .acceptEither( Weather.yesterday() .thenApply(w->"Yesterday: " + w), System.out::println ); ``` You know this code operates on futures because you've worked with the codebase and you know what `Weather.today()` and `Weather.yesterday()` return. But what if this was a different codebase, one where these methods return optionals instead? The code still makes sense: if there is a weather for today, transform it and print it, otherwise get the weather for yesterday, transform it and print it. Or maybe they return lists? Transform all elements of today's prediction, and if there are none, use the elements of yesterday's predictions instead, transformed; then print all these elements. ## How should we test async code? Consider the following method: ```java void printWeather() { getString(...) .thenApply(parseWeather) .thenAccept(System.out::println); } ``` How would you test it? The problem is that immediately after calling the method, the `getString` future may not have finished yet, so one cannot test its side effect yet. It might even never finish if there is an infinite loop in the code, or if it expects a response from a server that is down. One commonly used option is to sleep via, e.g., `Thread.sleep`, and then assume that the operation must have finished. **Never, ever, ever, ever sleep in tests for async code**. It slows tests down immensely since one must sleep the whole duration regardless of how long the operation actually takes, it is brittle since a future version of the code may be slower, and most importantly it's unreliable since the code could sometimes take more time due to factors out of your control, such as continuous integration having fewer resources because many pull requests are open and being tested. The fundamental problem with the method above is its return value, or rather the lack of a return value. Tests cannot access the future, they cannot even name it, because the method does not expose it. To be testable, the method must be refactored to expose the future: ```java CompletableFuture<Void> printWeather() { return getString(...) .thenApply(parseWeather) .thenAccept(System.out::println); } ``` It is now possible to test the method using the future it returns. One option to do so is this: ```java printWeather().thenApply(r -> { // ... test? ... }); ``` However, this is a bad idea because the lambda will not run if the future fails or if it never finishes, so the test will pass even though the future has not succeeded. In fact, the test does not even wait for the future to finish, so the test may pass even if the result is wrong because the lambda will execute too late! To avoid these problems, one could write this instead: ```java printAnswer().join(); // ... test ... ``` But this leaves one problem: if the code is buggy and the future never completes, `join()` will block forever and the tests will never complete. To avoid this problem, one can use the timeout method we saw earlier: ```java printWeather() .orTimeout(5, TimeUnit.SECONDS) .join(); // ... test ... ``` There is of course still the issue unrelated to asynchrony that the method has an implicit dependency on the standard output stream, which makes testing difficult. You can remove this dependency by returning the `CompletableFuture<String>` directly instead of printing it, which makes tests much simpler: ```java String weather = getWeather() .orTimeout(5, TimeUnit.SECONDS) .join(); // ... test weather ... ``` Exposing the underlying future is the ideal way to test asynchronous operations. However, this is not always feasible. Consider an app for which we want to test a button click "end-to-end", i.e., by making a fake button click and testing the resulting changes in the user interface. The button click handler must typically have a specific interface, including a `void` return type: ```java @Override void onClick(View v) { ... } ``` One cannot return the future here, since the `void` return type is required to comply with the button click handler interface. Instead, one can add an explicit callback for tests: ```java @Override void onClick(View v) { // ... callback.run(); } public void setCallback(...) { ... } ``` Tests can then set a callback and proceed as usual: ```java setCallback(() -> { // ... can we test here? }); // ... click the button ... ``` However, this now raises another problem: how to properly test callback-based methods? One way would be to use low-level classes such as latches or barriers to wait for the callback to fire. But this is a reimplementation of the low-level code the authors of `CompletableFuture` have already written for us, so we should be reusing that instead! ```java var future = new CompletableFuture<Void>(); setCallback(() -> future.complete(null)); // ... click the button ... future.orTimeout(5, TimeUnit.SECONDS) .join(); ``` We have reduced the problem of testing callbacks to a known one, testing futures, which can then be handled as usual. --- #### Exercise Take a look at the three tests in [`WeatherTests.java`](exercises/lecture/src/test/java/WeatherTests.java), and complete them one by one, based on the knowledge you've just acquired. <details> <summary>Suggested solution (click to expand)</summary> <p> - As we did above, call `orTimeout(...)` then `join()` on `Weather.today()`, then assert that its result is `"Sunny"` - Create a `CompletableFuture<Void>`, call its `complete` method in the callback of `WeatherView`, then wait for it with a timeout after executing `WeatherView.clickButton()`, and test the value of `WeatherView.weather()` - There are multiple ways to do the last exercise; one way is to return the combination of the two futures with `allOf` in `printWeather`, and replace `System.out::println` with a `Consumer<String>` parameter, then test it with a consumer that adds values to a string; another would be a more thorough refactoring of `printWeather` that directly returns a `CompletableFuture<List<String>>` We provide a [solution example](exercises/solutions/lecture/src/test/java/WeatherTests.java). </p> </details> --- ## How does asynchrony interact with software design? Which operations should be sync and which should be async, and why? This is a question you will encounter over and over again when engineering software. One naïve option is to make everything asynchronous. Even `1 + 1` could be `addAsync(1, 1)`! This is clearly going too far. It's important to remember that _asynchrony is viral_: if a method is async, then the methods that call it must also be async, though it can itself call sync methods. A sync method that calls an async method is poor design outside of the very edges of your system, typically tests and the main method, because it will need to block until the async method is done, which can introduce all kinds of issues such as UI freezes or deadlocks. This also applies to inheritance: if a method might be implemented in an asynchronous way, but also has other synchronous implementations, it must be async. For instance, while fetching the picture for an album in a music player may be done from a local cache in a synchronous way, it will also sometimes be done by downloading the image from the Internet. Thus, you should make operations async if they are expected to be implemented in an asynchronous way, typically I/O operations. One policy example is the one in the [Windows Runtime APIs](https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/concurrency#asynchronous-operations-and-windows-runtime-async-functions), which Microsoft introduced with Windows 8. Any operation that has the potential to take more than 50 milliseconds to complete returns a future instead of a synchronous result. 50ms may not be the optimal threshold for everything, but it is a reasonable and clear position to take that enables engineers to decide whether any given operation should be asynchronous. Remember the "YAGNI" principle: "_You Aren't Gonna Need It". Don't make operations async because they might perhaps one day possibly maybe need to be async. Only do so if there is a clear reason to. Think of how painful, or painless, it would be to change from sync to async if you need it later. One important principle is to be consistent. Perhaps you are using an OS that gives you asynchronous primitives for reading and writing to files, but only a synchronous primitive to delete it. You could expose an interface like this: ```java class File { CompletableFuture<String> read(); CompletableFuture<Void> write(String text); void delete(); } ``` However, this is inconsistent and surprising to developers using the interface. Instead, make everything async, even if deletion has to be implemented by returning an already-completed future after synchronously deleting the file: ```java class File { CompletableFuture<String> read(); CompletableFuture<Void> write(String text); CompletableFuture<Void> delete(); } ``` This offers a predictable and clear experience to developers using the interface. What if you need to asynchronously return a sequence of results? For instance, what should the return type of a `downloadImagesAsync` method be? It could be `CompletableFuture<List<Image>>`, if you want to batch the results. Or it could be `List<CompletableFuture<Image>>`, if you want to parallelize the downloads. But if you'd like to return "a sequence of asynchronous operations", what should you return? Enter "reactive" programming, in which you react to events such as downloads, clicks, or requests, each of which is an asynchronous event. For instance, if you have a "flow" of requests, you could `map` it to a flow of users and their data, then `filter` it to remove requests from users without the proper access right, and so on. In other words, it's a monad! Thus, you already mostly know what operations exist and how to use it. Check out [ReactiveX.io](https://reactivex.io) if you're interested, with libraries such as [RxJava](https://github.com/ReactiveX/RxJava). ## Summary In this lecture, you learned: - Asynchrony: what it is, how to use it, and when to use it - Maintainable async code by creating and combining futures - Testable async code with reliable and useful tests You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Infrastructure > **Prerequisites**: Before following this lecture, you should: > - Install Git. On Windows, use [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) as Git is designed mostly for Linux. > On macOS, see [the git documentation](https://git-scm.com/download/mac). On Linux, Git may already be installed, or use your distribution's package manager. > If you have successfully installed Git, running `git --version` in the command line should show a version number. > - Create a GitHub account (you do not have to use an existing GitHub account, you can create one just for this course if you wish) > - Set up an SSH key for GitHub by following [their documentation](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account) > - Tell Git who you are by running `git config --global user.name 'your_name'` with your name and `git config --global user.email 'your_email'` with the e-mail you used for GitHub > - Choose an editor Git will open to write a summary of your changes with `git config --global core.editor 'your_editor'`, since Git defaults to `vi` which is hard to use for newcomers. > On Windows with WSL you can use `notepad.exe`, which will open Windows's Notepad. > On macOS you can use `open -e -W -n` which will open a new TextEdit window. > On Linux you can use your distribution's built-in graphical text editor, or `nano`. > > If you use Windows with WSL, note that running `explorer.exe .` from the Linux command line will open Windows's Explorer in the folder your command-line is, which is convenient. > > Optionally, you may want to set the Git config setting `core.autocrlf` to `true` on Windows and `input` on Linux and macOS, > so that Git converts between Unix-style line endings (`\n`) and Windows-style line separators (`\r\n`) automatically. Where do you store your code, and how do you make changes to it? If you're writing software on your own, this is not a problem, as you can use your own machine and change whichever files you want whenever you want. But if you're working with someone else, it starts being problematic. You could use an online cloud service where you store files, and coordinate who changes which file and when. You could email each other changes to sets of files. But this does not work so well when you have more people, and it is completely unusable when you have tens or hundreds of people working on the same codebase. This is where infrastructure comes in. ## Objectives - Contrast old and new _version control_ systems - Organize your code with the _Git_ version control system - Write useful descriptions of code changes - Avoid mistakes with _continuous integration_ ## What is version control? Before we talk about how to manage your code using a version control system, we must define some terms. A _repository_ is a location in which you store a codebase, such as a folder on a remote server. When you make a set of changes to a repository, you are _pushing_ changes. When you retrieve the changes that others have made from the repository, you are _pulling_ changes. A set of changes is called a _commit_. Commits have four main components: who, what, when, and why. "Who" is the author of the commit, the person who made the changes. "What" is the contents of the commit, the changes themselves. "When" is the date and time at which the commit was made. This can be earlier than when the commit was actually pushed to a repository. "Why" is a message associated with the commit that explains why the changes were made, such as detailing why there was a bug and why the new code fixes the bug. The "why" is particularly important because you will often have to look at old changes later and understand why they were made. Sometimes, a commit causes problems. Perhaps a commit that was supposed to improve performance also introduces a bug. Version control systems allow you to _revert_ this commit, which creates a new commit whose contents are the reverse of the original one. That is, if the original commit replaced "X" by "Y", then the revert commit replaces "Y" with "X". Importantly, the original commit is not lost or destroyed, instead a new revert commit is created. Commits are put together in a _history_ of changes. Initially, a repository is empty. Then someone adds some content in a commit, then more content in another commit, and so on. The history of a repository thus contains all the changes necessary to go from nothing to the current state. Some of these changes could be going back and forth, such as revert commits, or commits that replace code that some previous commit added. At any time, any developer with access to the repository can look at the entire history to see who made what changes when and why. _1st generation_ version control systems were essentially a layer of automation on manual versioning. As we mentioned earlier, if you are developing with someone else, you might put your files somewhere and coordinate who is changing what and when. A 1st generation system helps you do that with fewer mistakes, but still fundamentally uses the same model. With 1st generation version control, if Alice wants to work on file A, she "checks out" the file. At that point, the file is locked: Alice can change it, but nobody else can. If Bob wants to also check out file A, the system will reject his attempt. Bob can, however, check out file B if nobody else is using it. Once Alice is done with her work, she creates a commit with her changes, and releases the lock. At that point, Bob can check out file A and make his changes. 1st generation version control systems thus act as locks at the granularity of files. They prevent developers from making parallel changes to the same file, which prevents some mistakes but isn't very convenient. For instance, Alice might want to modify function X in file A, while Bob wants to modify function Y in file A. These changes won't conflict, but they still cannot do them in parallel, because locks in 1st generation version control are at the file granularity. Developers moved on from 1st generation systems because they wanted more control over _conflicts_. When two developers want to work on the same file at the same time, they should be able to, as long as they can then _merge_ their changes into one unified version. Merging changes isn't always possible automatically. If two developers changed the same function in different ways, for instance, they probably need to have a chat to decide which changes should be kept. Another feature that makes sense if a system can handle conflicts and merges is _branches_. Sometimes, developers want to work on multiple copies of the codebase in parallel. For instance, you might be working on some changes that improve performance, when a customer comes in with a bug report. You could fix the bug and commit it with your performance changes, but the resulting commit is not convenient. If you later need to revert the performance changes, for instance, you would also revert the bugfix because it's in the same commit. Instead, you create a branch for your performance changes, then you switch to a branch for the bugfix, and you can work on both in parallel. When your bugfix is ready, you can _merge_ it into the "main" branch of the repository, and the same goes for the performance changes. One common use of branches is for versions: you can release version 1.0 of your software, for instance, and create a branch representing the state of the repository for that version. You can then work on the future version 2.0 in the "main" branch. If a customer reports a bug in version 1.0, you can switch to the branch for version 1.0, fix the bug, release the fix, then go back to working on version 2.0. Your changes for version 1.0 did not affect your main branch, because you made them in another branch. The typical workflow with branches for modern software is that you will create a branch starting from the main branch of the repository, then add some commits to the branch to fix a bug or add a feature or perform whatever task the branch is for, and then ask a colleague to review it. If the colleague asks for some changes, such as adding more code comments, you can add a commit to the branch with these changes. Once your colleague is happy, you can merge the branch's commits into the main branch. Then you can create another branch to work on something else, and so on. Your colleagues are themselves also working on their own branches. This workflow means everyone can push whatever commits they want on their branch without conflicting with others, even if their work isn't quite finished yet. Often it is a good idea to _squash_ a branch's commits into a single commit and merge the resulting commit into the main branch. This combines all of the branch's changes into one clean commit in the history of the main branch, rather than having a bunch of commits that do a few small changes each but make no sense without each other. In the case of branches that represent versions, one sometimes needs to apply the same changes to multiple branches. For instance, while developing version 2.0 in the main branch, you may find a bug, and realize that the bug also exists in version 1.0. You can make a commit fixing the bug in version 2.0, and then _cherry pick_ the commit into the branch for version 1.0. As long as the change does not conflict with other changes made in the version 1.0 branch, the version control system can copy your bugfix commit into a commit for another branch. _2nd generation_ version control systems were all about enabling developers to handle conflicts. Alice can work on file A without the need to lock it, and Bob can also work on file A at the same time. If Alice pushes her changes first, the system will accept them, and when Bob then wants to apply his changes, two things can happen. One possibility is that the changes can be merged automatically, for instance because the changes are on two different parts of the file. The other possibility is that the changes conflict and must be merged manually. Bob then has to choose what to do, perhaps by asking Alice, and produce one "merged" version of the file that can be pushed. The main remaining disadvantage of 2nd generation version control is its centralization. There is one repository that developers work with, hosted on one server. Committing changes requires an Internet connection to that server. This is a problem if the server is down, or a developer is in a place without access to the Internet, or any other issue that prevents a developer from reaching the server. _3rd generation_ version control systems are all about decentralization. Every machine has its own repository. It is not a "backup" or a "replica" of some "main" repository, but just another clone of the repository. Developers can make commits locally on their own repository, then push these commits to other clones of the repository, such as on a server. Developers can also have multiple branches locally, with different commits in each, and push some or all of these branches to other clones of the repository. This all works as long as the repositories have compatible histories. That is, one cannot push a change to a repository that isn't based on the same history as one's local repository. In practice, teams typically agree on one "main" repository that they will all push commits to, and work locally on their clone of that repository. While from the version control system's point of view all repository clones are equal, it is convenient for developers to agree on one place where everyone puts their changes. The main version control system in use today is _Git_. Git was invented by Linus Torvalds, who invented Linux, because he was tired of the problems with the previous version control system he used for Linux. There are also other 3rd generation version control systems such as Mercurial and Bazaar, but Git is by far the most used. Many developers use public websites to host the "main" repository clone of their projects. The most famous these days is GitHub, which uses Git but isn't technically related to it. GitHub not only stores a repository clone, but can also host a list of "issues" for the repository, such as bugs and feature requests, as well as other data such as a wiki for documentation. There are also other websites with similar features such as GitLab and BitBucket, though they are not as popular. An example of a project developed on GitHub is [the .NET Runtime](https://github.com/dotnet/runtime), which is developed mainly by Microsoft employees and entirely using GitHub. Conversations about bugs, feature requests, and code reviews happen in the open, on GitHub. ## How does one use Git? Now that we've seen the theory, let's do some practice! You will create a repository, make some changes, and publish it online. Then we'll see how to contribute to an existing online repository. Git has a few basic everyday commands that we will see now, and many advanced commands we won't discuss here. You can always look up commands on the Internet, both basic and advanced ones. You will eventually remember the basics after using them enough, but there is no shame at all in looking up what to do. We will use Git on the command line for this tutorial, since it works the same everywhere. However, for everyday tasks you may prefer using graphical user interfaces such as [GitKraken](https://www.gitkraken.com/), [GitHub Desktop](https://desktop.github.com/), or the Git support in your favorite IDE. Start by creating a folder and _initializing_ a repository in that folder: ```sh ~$ mkdir example ~$ cd example ~/example$ git init ``` Git will tell you that you have initialized an empty Git repository in `~/example/.git/`. This `.git/` folder is a special folder Git uses to store metadata. It is not part of the repository itself, even though it is in the repository folder. Let's create a file: ```sh $ echo 'Hello' > hello.txt" ``` We can now ask Git what it thinks is going on: ```sh $ git status ... Untracked files: hello.txt ``` Git tells us that it sees we added `hello.txt`, but this file isn't tracked yet. That is, Git won't include it in a commit unless we explicitly ask for it. So let's do exactly that: ```sh $ git add -A ``` This command asks Git to include all current changes in the repository for the next commit. If we make more changes, we will have to ask for these new changes to be tracked as well. But for now, let's ask Git what it thinks: ```sh $ git status ... Changes to be committed: new file: hello.txt ``` Now Git knows we want to commit that file. So let's commit it: ```sh $ git commit ``` This will open a text editor for you to type the commit message in. As we saw earlier, the commit message should be a description of _why_ the changes were made. Often the very first commit in a repository sets up the basic file structure as an initial commit, so you could write `Initial commit setting up the file` or something similar. You will then see output like this: ```sh [...] Initial commit. 1 file changed, 1 insertion(+) create mode 100644 hello.txt ``` Git repeats the commit message you put, here `Initial commit.`, and then tells you what changes happened. Don't worry about that `mode 100644`, it's more of an implementation detail. Let's now make a change by adding one line: ```sh $ echo 'Goodbye' >> hello.txt ``` We can ask git for the details of what changes we did: ```sh $ git diff ``` This will show a detailed list of the differences between the state of the repository as of the latest commit and the current state of the repository, i.e., we added one line saying `Goodbye`. Let's track the changes we just made: ```sh $ git add -A ``` What happens if we ask for a list of differences again? ```sh $ git diff ``` ...Nothing! Why? Because `diff` by default shows differences that are not tracked for the next commit. There are three states for changes to files in Git: modified, staged, and committed. By default changes are modified, then with `git add -A` they are staged, and with `git commit` they are committed. We have been using `-A` with `git add` to mean "all changes", but we could in fact add only specific changes, such as specific files or even parts of files. In order to see staged changes, we have to ask for them: ```sh $ git diff --staged ``` We can now commit our changes. Because this is a small commit that does not need much explanation, we can use `-m` to write the commit message directly in the command: ```sh $ git commit -m 'Say goodbye' ``` Let's now try out branches, by creating a branch and switching to it: ```sh git switch -c feature/today ``` The slash in the branch name is nothing special to Git, it's only a common naming convention to distinguish the purpose of different branches. For instance, you might have branches named `feature/delete-favorites` or `bugfix/long-user-names`. But you could also name your branch `delete-favorites` or `bugfix/long/user/names` if you'd like, as long as everybody using the repository agrees on a convention for names. Now make a change to the single line in the file, such as changing "Hello" to "Hello today". Then, track the changes and commit them: ```sh $ git add -A && git commit -m 'Add time' ``` You will notice that Git tells you there is `1 insertion(+), 1 deletion (-)`. This is a bit odd, we changed one line, why are there two changes? The reason is that Git tracks changes at the granularity of lines. When you edit a line, Git sees this as "you deleted the line that was there, and you added a new line". The fact that the "deleted" and the "added" lines are similar is not relevant. If you've already used Git before, you may have heard of the `-a` to `git commit`, which could replace the explicit `git add -A` in our case. The reason we aren't using it here, and the reason why you should be careful if using it, is that `-a` only adds changes to existing files. It does not add changes to new files or deleted files. This makes it very easy to accidentally forget to include some new or deleted files in the commit, and to then have to make another commit with just these files, which is annoying. Anyway, we've made a commit on our `feature/today` branch. In case we want to make sure that we are indeed on this branch, we can ask Git: ```sh $ git branch ``` This will output a list of branches, with an asterisk `*` next to the one we are on. Let's now switch to our main branch. Depending on your Git version, this branch might have different names, so look at the output of the previous command and use the right one, such as `master` or `main`: ```sh $ git switch main ``` To see what happens when two commits conflict, let's make a change to our `hello.txt` file that conflicts with the other branch we just made. For instance, replace "Hello" with "Hello everyone". Then, track the change and commit it as before. At this point, we have two branches, our main branch and `feature/today`, that have diverged: they both have one commit that is not in the other. Let's ask Git to merge the branches, that is, add the commits from the branch we specify into the current branch: ```sh $ git merge feature/today ``` Git will optimistically start with `Auto-merging hello.txt`, but this will soon fail with a `Merge conflict in hello.txt`. Git will ask us to fix conflicts and commit the result manually. What does `hello.txt` look like now? ```sh $ cat hello.txt <<<<<<< HEAD Hello everyone ======= Hello today >>>>>>> feature/today Goodbye ``` Let's take a moment to understand this. The last line hasn't changed, because it's not a part of the conflict. The first line has been expanded to include both versions: between the `<<<` and `===` is the version in `HEAD`, that is, the "head", the latest commit, in the current branch. Indeed, on our main branch the first line was `Hello everyone`. Between the `===` and the `>>>` is the version in `feature/today`. What we need to do is manually merge the changes, i.e., edit the file to replace the conflict including the `<<<`, `===`, and `>>>` lines with the merged changes we want. For instance, we could end up with a file containing the following: ```sh $ cat hello.txt Hello everyone today Goodbye ``` This is one way to merge the file. We could also have chosen `Hello today everyone`, or perhaps we would rather discard one of the two changes and keep `Hello everyone` or `Hello today`. Or perhaps we want yet another change, we could have `Hello hello` instead. Git does not care, it only wants us to decide what the merged version should be. Once we have made our merge changes, we should add the changes and commit as before: ```sh $ git add -A && git commit -m 'Merge' ``` Great. Wait, no, actually, not so great. That's a pretty terrible commit message. It's way too short and not descriptive. Thankfully, _because we have not published our changes to another clone of the repository yet_, we can make changes to our commits! This is just like how a falling tree makes no sound if there's no one around to hear it. If nobody can tell, it did not happen. We can change our commit now, and when we push it to another clone the clone will only see our modified commit. However, if we had already pushed our commit to a clone, our commit would be visible, so we could not change it any more as the clone would get confused by a changing commit since commits are supposed to be immutable. To change our commit, which again should only be done if the commit hasn't been pushed yet, we "amend" it: ```sh $ git commit --amend -m 'Merge the feature/today branch' ``` We have only modified the commit message here, but we could also modify the commit contents, i.e., the changes themselves. Sometimes we make changes we don't actually want, for instance temporary changes while we debug some code. Let's make a "bad" change: ```sh $ echo 'asdf' >> hello.txt ``` We can restore the file to its state as of the latest commit to cancel this change: ```sh $ git restore hello.txt ``` Done! Our temporary changes have disappeared. You can also use `.` to restore all files in the current directory, or any other path. However, keep in mind that "disappeared" really means disappeared. It's as if we never changed the file, as the file is now in the state it was after the latest commit. Do not use `git restore` unless you actually want to lose your changes. Sometimes we accidentally add files we don't want. Perhaps a script went haywire, or perhaps we copied some files by accident. Let's make a "bad" new file: ```sh $ echo 'asdf' > mistake.txt ``` We can ask Git to "clean" the repository, which means removing all untracked files and directories. However, because this will delete files, we'd better first run it in "dry run" mode using `-n`: ```sh $ git clean -fdn ``` This will show a list of files that _would_ be deleted if we didn't include `-n`. If we're okay with the proposed deletion, let's do it: ```sh $ git clean -fd ``` Now our `mistake.txt` is gone. Finally, before we move on to GitHub, one more thing: keep in mind that Git only tracks _files_, not _folders_. Git will only keep track of folders if they are a part of a file's path. So if we create a folder and ask Git what it sees, it will tell us there is nothing, because the folder is empty: ```sh $ mkdir folder $ git status ``` If you need to include an "empty" folder in a Git repository for some reason, you should add some empty file in it so that Git can track the folder as part of that file. Let's now publish our repository. Go to [GitHub](https://github.com) and create a repository using the "New" button on the home page. You can make it public or private, but do not create files such as "read me" files or anything else, just an empty repository. Then, follow the GitHub instructions for an existing repository from the command line. Copy and paste the commands GitHub gives you. These commands will add the newly-created GitHub repository as a "remote" to your local repository, which is to say, another clone of the repository that Git knows about. Since it will be the only remote, it will also be the default one. The default remote is traditionally named `origin`. The commands GitHub provide will also push your commits to this remote. Once you've executed the commands, you can refresh the page on your GitHub repository and see your files. Now make a change to your `hello.txt`, track the change, and commit it. You can then sync the commit with the GitHub repository clone: ```sh $ git push ``` You can also get commits from GitHub: ```sh $ git pull ``` Pulling will do nothing in this case, since nobody else is using the repository. In a real-world scenarios, other developers would also have a clone of the repository on their machine and use GitHub as their default remote. They would push their changes, and you would pull them. Importantly, `git pull` only synchronizes the current branch. If you would like to sync commits from another branch, you must `git switch` to that branch first. Similarly, `git push` only synchronizes the current branch, and if you create a new branch you must tell it where to push with `-u` by passing both the remote name and the branch name: ```sh $ git switch -c example $ git push -u origin example ``` Publishing your repository online is great, but sometimes there are files you don't want to publish. For instance, the binary files compiled from source code in the repository probably should not be in the repository, since they can be recreated easily and would only take up space. Files that contain sensitive data such as passwords should also not be in the repository, especially if it's public. Let's simulate a sensitive file: ```sh $ echo '1234' > password.txt ``` We can tell Git to pretend this file doesn't exist by adding a line with its name to a special file called `.gitignore`: ```sh $ echo 'password.txt' >> .gitignore ``` Now, if you try `git status`, it will tell you that `.gitignore` was created but ignore `password.txt` since you told Git to ignore it. You can also ignore entire directories. Note that this only works for files that haven't been committed to the repository yet. If you had already made a commit in which `password.txt` exists, adding its name to `.gitignore` will only ignore future changes, not past ones. If you accidentally push to a public repository a commit with a file that contains a password, you should assume that the password is compromised and immediately change it. There are bots that scan GitHub looking for passwords that have been accidentally committed, and they will find your password if you leave it out there, even for a few seconds. Now that you have seen the basics of Git, time to contribute to an existing project! You will do this through a _pull request_, which is a request that the maintainers of an existing project pull your changes into their project. This is a GitHub concept, as from Git's perspective it's merely syncing changes between clones of a repository. Go to <https://github.com/sweng-example/hello> and click on the "Fork" button. A _fork_ is a clone of the repository under your own GitHub username, which you need here because you do not have write access to `sweng-example/hello` so you cannot push changes to it. Instead, you will push changes to your fork, to which you have write access, and then ask the maintainers of `sweng-example/hello` to accept the change. You can create branches within a fork as well, as a fork is just another clone of the repository. Typically, if you are a collaborator of a project, you will use a branch in the project's main repository, while if you are an outsider wanting to propose a change, you will create a fork first. Now that you have a forked version of the project on GitHub, click on the "Code" button and copy the SSH URL, which should start with `git@github.com:`. Then, ask Git to make a local clone of your fork, though you should go back to your home directory first, since creating a repository within a repository causes issues: ```sh $ cd ~ $ git clone git@github.com:... ``` Git will clone your fork locally, at which point you can make a change, commit, and push to your fork. Once that's done, if you go to your fork on GitHub, there should be a banner above the code telling you that the branch in your fork is 1 commit ahead of the main branch in the original repository. Click on the "Contribute" button and the "Open pull request" button that shows up, then confirm that you want to open a pull request, and write a description for it. Congratulations, you've made your first contribution to an open source project! The best way to get used to Git is to use it a lot. Use Git even for your own projects, even if you do not plan on using branches. You can use private repositories on GitHub as backups, so that even if your laptop crashes you will not lose your code. There are many advanced features in Git that can be useful in some cases, such as `bisect`, `blame`, `cherry-pick`, `stash`, and many more. Read the [official documentation](https://git-scm.com/docs/) or find online advanced tutorials for more if you're curious! ## How does one write good commit messages? Imagine being an archaeologist and having to figure out what happened in the past purely based on some half-erased drawings, some fossils, and some tracks. You will eventually figure out something that could've happened to cause all this, but it will take time and you won't know if your guess is correct. Wouldn't it be nice if there was instead a journal that someone made, describing everything important they did and why they did it? This is what commit messages are for: keep track of what you do and why you did it, so that other people will know it even after you're done. Commit messages are useful to people who will review your code before approving it for merging in the main branch, and to your colleagues who investigate bugs months after the code was written. Your colleagues in this context include "future you". No matter how "obvious" or "clear" the changes seems to you when you make them, a few months later you won't remember why you did something the way you did it. The typical format of a commit message is a one-line summary followed by a blank line and then as many lines as needed for details. For instance, this is a good commit message: ``` Fix adding favorites on small phones The favorites screen had too many buttons stacked on the same row. On phones with small screens, there wasn't enough space to show them all, and the "add" button was out of view. This change adds logic to use multiple rows of buttons if necessary. ``` As we saw earlier, "squashing" commits is an option when merging your code into the main branch, so not all commits on a branch need to have such detailed messages. Sometimes a commit is just "Fix a typo" or "Add a comment per the review feedback". These commits aren't important to understand the changes, so their messages will be dropped once the branch is squashed into a single commit while being merged. The one-line summary is useful to get an overview of the history without having to see every detail. You can see it on online repositories such as GitHub, but also locally. Git has a `log` command to show the history, and `git log --oneline` will show only the one-line summary of each commit. A good summary should be short and in the imperative mood. For instance: - "Fix bug #145" - *Add an HD version of the wallpaper" - "Support Unicode 14.0" The details should describe _what_ the changes do and _why_ you did them, but not _how_. There is no point in describing how because the commit message is associated with the commit contents, and those already describe how you changed the code. ## How can we avoid merging buggy code? Merging buggy code to the main branch of a repository is an annoyance for all contributors to that repository. They will have to fix the code before doing the work they actually want to do, and they may not all fix it in the same way, leading to conflicts. Ideally, we would only accept pull requests if the resulting code compiles, is "clean" according to the team's standards, and has been tested. Different teams have different ideas of what "clean" code is, as well as what "testing" means since it could be manual, automated, performed on one or multiple machines, and so on. When working in an IDE, there will typically be menu options to analyze the code for cleanliness, to compile the code, to run the code, and to run automated tests if the developers wrote some. However, not everyone uses the same IDE, which means they may have different definitions of what these operations mean. The main issue with using operations in an IDE to check properties about the code is that humans make mistakes. On a large enough projects, human mistakes happen all the time. For instance, it's unreasonable to expect hundreds of developers to never forget even once to check that the code compiles and runs. Checking for basic mistakes also a poor use of people's time. Reviewing code should be about the logic of the code, not whether every line is syntactically valid, that's the compiler's job. We would instead like to _automate_ the steps we need to check code. This is done using a _build system_, such as CMake for C++, MSBuild for C#, or Gradle for Java. There are many build systems, some of which support multiple languages, but they all fundamentally provide the same feature: build automation. A build system can invoke the compiler on the right files with the right flags to compile the code, invoke the resulting binary to run the code, and even perform more complex operations such as downloading dependencies based on their name if they have not been downloaded already. Build systems are configured with code. They typically have a custom declarative language embedded in some other language such as XML. Here is an example of build code for MSBuild: ```xml <Project Sdk="Microsoft.NET.Sdk"> <ItemGroup> <PackageReference Include="Microsoft.Z3" Version="4.10.2" /> </ItemGroup> </Project> ``` This code tells MSBuild that (1) this is a .NET project, which is the runtime typically associated with C#, and (2) it depends on the library `Microsoft.Z3`, specifically its version `4.10.2`. One can then run MSBuild with this file from the command line, and MSBuild will compile the project after first downloading the library it depends on if it hasn't been downloaded already. In this case, the library name is associated with an actual library by looking up the name on [NuGet](https://www.nuget.org/), the library catalog associated with MSBuild. Build systems remove the dependency on an IDE to build and run code, which means everyone can use the editor they want as long as they use the same build system. Most IDEs can use build system code as the base for their own configuration. For instance, the file above can be used as-is by Visual Studio to configure a project. Build systems enable developers to build, run, and check their code anywhere. But it has to be somewhere, so which machine or machines should they use? Once again, using a developer's specific machine is not a good idea because developers customize their machine according to their personal preferences. The machines developers use may not be representatives of the machines the software will actually run on when used by customers. Just as we defined builds using code through a build system, we can define environments using code! Here is an example of environment definition code for the Docker container system, which you do not need to understand: ``` FROM node:12-alpine RUN apk add python g++ make COPY . . RUN yarn install CMD ["node", "src/index.js"] EXPOSE 3000 ``` This code tells Docker to use the `node:12-alpine` base environment, which has Node.js preinstalled on an Alpine Linux environment. Then, Docker should run `apk add` to install specific packages, including `make`, a build system. Docker should then copy the current directory inside of the container, and run `yarn install` to invoke Node.js's `yarn` build system to pre-install dependencies. The file also tells Docker the command to run when starting this environment and the HTTP port to expose to the outside world. Defining an environment using code enables developers to run and test their code in specific environments that can be customized to match customers' environments. Developers can also define multiple environments, for instance to ensure their software can run on different operating systems, or on operating systems in different languages. We have been using the term "machine" to refer to the environment code runs in, but in practice it's unlikely to be a physical machine as this would be inefficient and costly. Pull requests and pushes happen fairly rarely given that modern computers can do billions of operations per second. Provisioning one machine exclusively for one project would be a waste. Instead, automated builds use _virtual machines_ or _containers_. A virtual machine is a program that emulates an entire machine inside it. For instance, one can run an Ubuntu virtual machine on Windows. From Windows's perspective, the virtual machine is just another program. But for programs running within the virtual machine, it looks like they are running on real hardware. This enables partitioning resources: a single physical machine can run many virtual machines, especially if the virtual machines are not all busy at the same time. It also isolates the programs running inside the virtual machine, meaning that even if they attempt to break the operating system, the world outside of the virtual machine is not affected. However, virtual machines have overhead, especially when running many of them. Even if 100 virtual machines all run the exact same version of Windows, for instance, they must all run an entire separate instance of Windows including the Windows kernel. This is where _containers_ come in. Containers are a lightweight form of virtual machines that share the host operating system's kernel instead of including their own. Thus, there is less duplication of resources, at the cost of less isolation. Typically, services that allow anyone to upload code will use virtual machines to isolate it as much as possible, whereas private services can use containers since they trust the code they run. Using build systems and virtual machines to automatically compile, run, and check code whenever a developer pushes commits is called _continuous integration_, and it is a key technique in modern software development. When a developer opens a pull request, continuous integration can run whatever checks have been configured, such as testing that the code compiles and passes some static analysis. Merging can then be blocked unless continuous integration succeeds. Thus, nobody can accidentally merge broken code into the main branch, and developers who review pull requests don't need to manually check that the code works. Importantly, whether a specific continuous integration run succeeds or fails means that there exists a machine on which the code succeeds or fails. It is possible that code works fine on the machine of the developer who wrote it, yet fails in continuous integration. A common response to this is "but it works on my machine!", but that is irrelevant. The goal of software is not to work on the developer's machine but to work for users. Problems with continuous integration typically stem from differences between developers' machines and the virtual machines configured for continuous integration. For instance, a developer may be testing a phone app on their own phone, with a test case of "open the 'create item' page and click the 'no' button", which they can do fine. But their continuous integration environment may be set up with a phone emulator that has a small screen with few pixels, and the way the app is written means the 'no' button is not visible: <p align="center"><img alt="Illustration of the phones example." src="images/phones.svg" width="50%" /></p> The code thus does not work in the continuous integration environment, not because of a problem with continuous integration, but because the code does not work on some phones. The developer should fix the code so that the "No" button is always visible, perhaps below the "Yes" button with a scroll bar if necessary. --- #### Exercise: Add continuous integration Go back to the GitHub repository you created, and add some continuous integration! GitHub includes a continuous integration service called GitHub Actions, which is free for basic use. Here is a basic file you can use, which should be named `.github/workflows/example.yml`: ```yaml on: push jobs: example: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: echo "Hello!" ``` After pushing this file to the GitHub repository and waiting for a few seconds, you should see a yellow circle next to the commit indicating GitHub Actions is running, which you can also see in the "Actions" tab of the repository. This is a very basic action that only clones the repository and prints text. In a real-world scenario, you would at least invoke a build system. GitHub Actions is quite powerful, as you can read on [the GitHub Actions documentation](https://docs.github.com/en/actions). --- Version control, continuous integration, and other such tasks were typically called "operations", and were done by a separate team from the "development" team. However, nowadays, these concepts have combined into "DevOps", in which the same team does both, which makes it easier for developers to configure exactly the operations they want. ## Summary In this lecture, you learned: - Version control systems, and the differences between 1st, 2nd, and 3rd generation - Git: how to use it for basic scenarios, and how to write good commit messages - Continuous integration: build systems, virtual machines, and containers You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Design Imagine if, in order to display "Hello, World!" on a screen, you had to learn how everything worked. You'd need to learn all about LED lights and their physics. And then you'd need to read the thousands of pages in CPU data sheets to know what assembly code to write. Instead, you can write `print("Hello, World!")` in a language like Scala or Python, and that's it. The language's runtime does all the work for you, with the help of your operating system, which itself contains drivers for hardware. Even those drivers don't know about LED lights, as the screen itself exposes an interface to display data that the drivers use. Python itself isn't a monolith either: it contains sub-modules such as a tokenizer, a parser, and an interpreter. Unfortunately, it's not easy to write large codebases in a clean way, and this is where _design_ comes in. ## Objectives After this lecture, you should be able to: - Apply _modularity_ and _abstraction_ in practice - Compare ways to handle _failures_ - Organize code with _design patterns_ - Use common patterns for modern applications ## How can one design large software systems? [Barbara Liskov](https://en.wikipedia.org/wiki/Barbara_Liskov), one of the pioneers of computer science and programming language design in particular, once [remarked](https://infinite.mit.edu/video/barbara-liskov) that "_the basic technique we have for managing the complexity of software is modularity_". Modularity is all about dividing and sub-dividing software into independent units that can be separately maintained and be reused in other systems: _modules_. Each module has an _interface_, which is what the module exposes to the rest of the system. The module _abstracts_ some concept and presents this abstraction to the world. Code that uses the module does not need to know or care about how the abstraction is implemented, only that it exists. For instance, one does not need to know woodworking or textiles to understand how to use a sofa. Some sofas can even be customized by customers, such as choosing whether to have a storage compartment or a convertible bed, because the sofas are made of sub-modules. In programming, a module's interface is typically called an "API", which is short for "Application Programming Interface". APIs contain objects, functions, errors, constants, and so on. This is _not_ the same thing as the concept of an `interface` in programming languages such as Java. In this lecture, we will talk about the high-level notion of an interface, not the specific implementation of this concept in any specific language. Consider the following Java method: ```java static int compute(String expr) { // ... } ``` This can be viewed as a module, whose interface is the method signature: `int compute(String expr)`. Users of this module do not need to know how the module computes expressions, such as returning `4` for `2 + 2`. They only need to understand its interface. A similar interface can be written in a different technology, such as Microsoft's COM: ```cpp [uuid(a03d1424-b1ec-11d0-8c3a-00c04fc31d2f)] interface ICalculator : IDispatch { HRESULT Compute([in] BSTR expr, [out] long* result); }; ``` This is the interface of a COM component, which is designed to be usable and implementable in different languages. It fundamentally defines the same concept as the Java one, except it has a different way of defining errors (exceptions vs. `HRESULT` codes) and of returning data (return values vs. `[out]` parameters). Anyone can use this COM module given its interface, without having to know or care about how it is implemented and in which language. Another kind of cross-program interface is HTTP, which can be used through server frameworks: ```java @Get("/api/v1/calc") String compute(@Body String expr) { // ... } ``` The interface of this HTTP server is `HTTP GET /api/v1/calc` with the knowledge that the lone parameter should be passed in the body, and the return value will be a string. The Java method name is _not_ part of the interface, because it is not exposed to the outside world. Similarly, the name of the parameter `expr` is not exposed either. These three interfaces could be used in a single system that combines three modules: an HTTP server that internally calls a COM component that internally calls a Java method. The HTTP server doesn't even have to know the Java method exists if it goes through the COM component, which simplifies its development. However, this requires some discipline in enforcing boundaries. If the Java method creates a file on the local disk, and the HTTP server decides to use that file, then the modularity is broken. This problem also exists at the function level. Consider the same Java method as above, but this time with an extra method: ```java static int compute(String expr); static void useReversePolishNotation(); ``` The second method is intended to configure the behavior of the first. However, it creates a dependency between any two modules that use `compute`, since they have to agree on whether to call `useReversePolishNotation` or not, as the methods are `static`. If a module tries to use `compute` assuming the default infix notation, but another module in the system has chosen to use reverse polish notation, the former will fail. Another common issue with modules is voluntarily exposing excess information, usually because it makes implementation simpler in the short term. For instance, should a `User` class with a `name` and a `favoriteFood` also have a Boolean property `fetchedFromDatabase`? It may make sense in a specific implementation, but the concept of tracking users' favorite foods is completely unrelated to a database. The maintainers of code using such a `User` class would need to know about databases any time they deal with users, and the maintainers of the `User` class itself could no longer change the implementation of `User` to be independent of databases, since the interface mandates a link between the two concepts. Similarly, at the package level, a "calc" package for a calculator app with a `User` class and a `Calculator` class probably should not have a `UserInterfaceCheckbox` class, as it is a much lower level concept. --- #### Exercise What would a `Student` class's interface look like... - ... for a "campus companion" app? - ... for a course management system? - ... for an authentication system? How will they differ and why? <details> <summary>Proposed solution (click to expand)</summary> <p> A campus companion app could view students as having a name and preferences such as whether to display vegetarian menus first or in what order to display the user's courses. The campus companion does not care about whether the student has paid their fee for the current semester, which is something a course management system might care about, along with what major the student is in. Neither the campus companion nor the course management should know what the user's password is, or even the concept of passwords since the user might log in using biometric data or two-factor authentication. Those concepts are what the authentication system cares about for students. </p> </details> ## What does modularity require in practice? It is all too easy to write software systems in which each "module" is a mishmash of concepts, modules depend on each other without any clear pattern. Maintaining such a system requires reading and understanding most of the system's code, which doesn't scale to large systems. We have seen the theoretical benefits and pitfalls of modularity, now let's see how to design modular systems in practice. We will talk about the _regularity_ of interfaces, _grouping_ and _layering_ modules, and organizing modules by _abstraction level_. ### Regularity Consider fractals such as this one: <p align="center"><img alt="A rendering of the Mandelbrot fractal" src="images/mandelbrot.png" width="50%" /></p> This image may look complex, but because it is a fractal, it is very regular. It can be [formally defined](https://en.wikipedia.org/wiki/Mandelbrot_set#Formal_definition) with a short mathematical equation and a short sentence. Contrast it to this image: <p align="center"><img alt="Random noise" src="images/noise.png" width="50%" /></p> This is random noise. It has no regularity whatsoever. The only way to describe it is to describe each pixel in turn, which takes a long time. The idea that things should be regular and have short descriptions applies to code as well. Consider the following extract from Java's `java.util` package: ```java class Stack { /** Returns the 1-based position where an object is on this stack. */ int search(Object o); } ``` For some reason, `search` returns a 1-based position, even though every other index in Java is 0-based. Thus, any description of `search` must include this fact, and a cursory glance at code that uses `search` may not spot a bug if the index is accidentally used as if it was 0-based. One should follow the "principle of least surprise", i.e., things should behave in the way most people will expect them to, and thus not have exceptions to common rules. Another example from Java is the `URL` class's `equals` method. One would expect that, like any other equality check in Java, `URL::equals` checks the fields of both objects, or perhaps some subset of them. However, what it [actually does](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/net/URL.html#equals(java.lang.Object)) is to check whether the two URLs resolve to the same IP address. This means the result depends on whether the two URLs happen to point to the same IP at that particular point in time, and even whether the machine the code is running on has an Internet connection. It also takes time to resolve IP addresses, which is orders of magnitude slower than usual `equals` methods that check for field equality. A more formal way to view regularity is [Kolmogorov complexity](https://en.wikipedia.org/wiki/Kolmogorov_complexity): how many words do you need to describe something? For instance, the fractal above has low Kolmogorov complexity because it can be described in very few words. One can write a short computer program to produce it. In comparison, the random noise above has high Kolmogorov complexity because it can only be described with many words. A program to produce it has to produce each pixel individually. Any module whose description must include "and..." or "except..." has higher Kolmogorov complexity than it likely needs to. ### Grouping What do the following classes have in common? `Map<K, V>, Base64, Calendar, Formatter, Optional<T>, Scanner, Timer, Date`. Not much, do they? Yet they are all in the same `java.util` package in Java's standard library. This is not a good module interface: it contains a bunch of unrelated things! If you see that a Java program depends on `java.util`, you don't gain much information, because it is such a broad module. Now what do the following classes have in common? `Container, KeysView, Iterable, Sequence, Collection, MutableSet, Set, AsyncIterator`. This is much more straightforward: they are all collections, and indeed they are in the Python collections module. Unfortunately, that module is named `collections.abc`, because it's a fun acronym for "abstract base classes", which is not a great name for a module. But at least if you see a Python program depends on `collections.abc`, after looking up the name, you now know that it uses data structures. The importance of _grouping_ related things together explains why global variables are such a problem. If multiple modules all access the same global variable, then they all effectively form one module since a programmer needs to understand how each of them uses the global variable to use any of them. The grouping done by global variables is accidental, and thus unlikely to produce useful groups. ### Layering You may already know the networking stack's layers: the application layer uses the transport layer, which uses the network layer, and so on until the physical layer at the bottom-most level. The application layer does not use the network layer directly, nor does it even know there is a network layer. The network layer doesn't know there is an application or a transport layer, either. Layering is a way to define the dependencies between modules in a minimal and manageable way, so that maintaining a module can be done without knowledge of most other modules. There can be more than one module at a given layer: for instance, an app could use mobile and server modules, which form the layer below the app module. The server module itself may depend on an authentication module and a database module, which form the layer below, and so on. Thus, layer `N` depends _only_ on layer `N-1`, and the context for layer `N`'s implementation is the interface of layer `N-1`. By building layers in a tall stack, one minimizes the context of each layer's implementation. Sometimes, however, it is necessary to have one layer take decisions according to some higher-level logic, such as what comparison to use in a sorting function. Hardcoding knowledge about higher-level items in the sorting function would break layering and make it harder to maintain the sorting function. Instead, one can inject a "comparison" function as a parameter of the sort function: ```scala def sort(items, less_than) = { ... if (less_than(items(i), items(j)) ... } ``` The higher-level layers can thus pass a higher-level comparison function, and the sorting function does not need to explicitly depend on any layer above it, solving the problem. This can also be done with objects by passing other objects as constructor parameters, and even with packages in languages that permit it such as [Ada](https://en.wikipedia.org/wiki/Ada_(programming_language)). Layering also explains the difference between _inheritance_, such as `class MyApp extends MobileApp`, and _composition_, such as `class MyApp { private MyApp app; }`. The former requires `MyApp` to expose all of the interface of `MobileApp` in addition to its own, whereas the latter lets `MyApp` choose what to expose and optionally use `MobileApp` to implement its interface: <p align="center"><img alt="Visual representation of the layers from inheritance or composition of MyApp and MobileApp" src="images/layers.svg" width="50%" /></p> In most cases, composition is the appropriate choice to avoid exposing irrelevant details to higher-level layers. However, inheritance can be useful if the modules are logically in the same layer, such as `LaserPrinter` and `InkjetPrinter` both inheriting from `Printer`. ### Abstraction levels An optical fiber cable provides a very low-level abstraction, which deals with light to transmit individual bits. The Ethernet protocol provides a higher-level abstraction, which deals with MAC addresses and transmits bytes. A mobile app provides provides a high-level abstraction, which deals with requests and responses to transmit information such as the daily menus in cafeterias. If you had to implement a mobile app, and all you had available was an optical fiber cable, you would spend most of your time re-implementing intermediate abstractions, since defining a request for today's menu in terms of individual bits is hard. On the other hand, if you had to implement an optical fiber cable extension, and all you had available was the high-level abstraction of daily cafeteria menus, you would not be able to do your job. The high-level abstraction is convenient for high-level operations, but voluntarily hides low-level details. When designing a module, think about its _abstraction level_: where does it stand in the spectrum from low-level to high-level abstractions? If you provide an abstraction of a level higher than what is needed, others won't be able to do their work because they cannot access the low-level information they need. If you provide an abstraction of a level lower than what is needed, others will have to spend lots of time reinventing the high-level wheel on top of your low-level abstraction. You do not always have to choose a single abstraction level: you can expose multiple ones. For instance, a library might expose a module to transmit bits on optical fiber, a module to transmit Ethernet packets, and a module to make high-level requests. Internally, the high-level request module might use the Ethernet module, which might use the optical fiber module. Or not; there's no way for your customers to know, and there's no reason for them to care, as long as your modules provide working implementations of the abstractions they expose. A real-world example of differing abstraction levels is displaying a triangle using a GPU, which is the graphics equivalent of printing the text "Hello, World!". Using a high-level API such as [GDI](https://en.wikipedia.org/wiki/Graphics_Device_Interface) displaying a triangle requires around 10 lines of code. You can create a window object, create a triangle object, configure these objects' colors, and show them. Using a lower-level API such as [OpenGL](https://en.wikipedia.org/wiki/OpenGL), displaying a triangle requires around 100 lines of code, because you must explicitly deal with vertexes and shaders. Using an even lower-level API such as [Vulkan](https://en.wikipedia.org/wiki/Vulkan), displaying a triangle requires around 1000 lines of code, because you must explicitly deal with all of the low-level GPU concepts that even OpenGL abstracts away. Every part of the graphics pipeline must be configured in Vulkan. But this does not make Vulkan a "bad" API, only one that is not adapted to high-level tasks such as displaying triangles. Instead, Vulkan and similar APIs such as [Direct3D 12](https://en.wikipedia.org/wiki/Direct3D#Direct3D_12) are intended to be used for game engines and other "intermediate" abstractions that themselves provide higher-level abstractions. For instance, OpenGL can be implemented as a layer on top of Vulkan. Without such low-level abstractions, it would be impossible to implement high-level abstractions efficiently, and indeed performance was the main motivation for the creation of APIs such as Vulkan. When implementing an abstraction on top of a lower-level abstraction, be careful to avoid _abstraction leaks_. An abstraction leak is when a low-level detail "pops out" of a high-level abstraction, forcing users of the abstraction to understand and deal with lower-level details than they care about. For instance, if the function to show today's menu has the signature `def showMenu(date: LocalDate, useIPv4: Boolean)`, anyone who wants to write an application that shows menus must explicitly think about whether they want to use IPv4, a lower-level detail that should not be relevant at all in this context. Note that the terminology "abstraction leak" is not related to the security concept of "information leak", despite both being leaks. One infamous abstraction leak is provided by the former C standard library function `char* gets(char* str)`. "Former" function because it is the only one that was considered so bad it had to be removed from the C standard library, breaking compatibility with previous versions. What `gets` does is to read a line of input on the console and store it in the memory pointed to by `str`. However, there's a mismatch in abstraction levels: `gets` tries to provide the abstraction of "a line of text", yet it uses the C concept of "a pointer to characters". Because the latter has no associated length, this abstraction leak is a security flaw. No matter how large the buffer pointed to by `str` is, the user could write more characters than that, at which point `gets` would overwrite whatever is next in memory with whatever data the user typed. ### Recap Design systems such that individual modules have a regular API that provides one coherent abstraction. Layer your modules so that each module only depends on modules in the layer immediately below, and the layers are ordered by abstraction level. For instance, here is a design in which the green module provides a high-level abstraction and depends on the yellow modules, which provide abstractions of a lower level, and themselves depend on the red modules and their lowest-level abstractions: <p align="center"><img alt="A module diagram as explained in text" src="images/system.svg" width="50%" /></p> One way to do this at the level of individual functions is to write the high-level module first, with a high-level interface, and an implementation that uses functions you haven't written yet. For instance, for a method that predicts the weather: ```java int predictWeather(LocalDate date) { var past = getPastWeather(date); var temps = extractTemperatures(past); return predict(temps); } ``` After doing this, you can implement `getPastWeather` and others, themselves in terms of lower-level interfaces, until you either implement the lowest level yourself or reuse existing code for it. For instance, `getPastWeather` will likely be implemented with some HTTP library, while `extractTemperature` will likely be custom-made for the format of `past`. --- #### Exercise Look at `App.java` in the [`calc`](exercises/lecture/calc) project. It mixes all kinds of concepts together. Modularize it! Think about what modules you need, and how you should design the overall system. First off, what will the new `main` method look like? <details> <summary>Suggested solution (click to expand)</summary> <p> Create one function for obtaining user input, one for parsing it into tokens, one for evaluating these tokens, and one for printing the output or lack thereof. The evaluation function can internally use another function to execute each individual operator, so that all operators are in one place and independent of input parsing. See the [solution file](exercises/solutions/lecture/Calc.java) for an example, which has the following structure: ```mermaid graph TD A[main] B[getInputl] C[parseInput] D[compute] E[execute] F[display] A --> B A --> C A --> D A --> F D --> E ``` </p> </details> --- At this point, you may be wondering: how far should you go with modularization? Should your programs consist of thousands of tiny modules stacked hundreds of layers high? Probably not, as this would cause maintainability issues just like having a single big module for everything does. But where to stop? There is no single objective metric to tell you how big or small a module should be, but here are some heuristics. You can estimate _size_ using the number of logical paths in a module. How many different things can the module do? If you get above a dozen or so, the module is probably too big. You can estimate _complexity_ using the number of inputs for a module. How many things does the module need to do its job? If it's more than four or five, the module is probably too big. Remember the acronym _YAGNI_, for "You Aren't Gonna Need It". You could split that module into three even smaller parts that hypothetically could be individually reused, but will you need this? No? You Aren't Gonna Need It, so don't do it. You could provide ten different parameters for one module to configure every detail of what it does, but will you need this? No? You Aren't Gonna Need It, so don't do it. One way to discuss designs with colleagues is through the use of diagrams such as [UML class diagrams](https://en.wikipedia.org/wiki/Class_diagram), in which you draw modules with their data and operations and link them to indicate composition and inheritance relationships. Keep in mind that the goal is to discuss system design, not to adhere to specific conventions. As long as everyone agrees on what each diagram element means, whether or not you adhere to a specific convention such as UML is irrelevant. Beware of the phenomenon known as "[cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming)". The idea of a "cargo cult" originated in remote islands used by American soldiers as bases during wars. These islands were home to native populations who had no idea what planes were, but who realized that when Americans did specific gestures involving military equipment, cargo planes full of supplies landed on the islands. They naturally hypothesized that if they, the natives, could replicate these same gestures, more planes might land! Of course, from our point of view we know this was useless because they got the correlation backwards: Americans were doing landing gestures because they knew planes were coming, not the other way around. But the natives did not know that, and tried to get cargo planes to land. Some of these cults lasted for longer than they should have, and their modern-day equivalent in programming is engineers who design their system "because some large company, like Google or Microsoft, does it that way" without the knowledge nor the understanding of why the large company does it that way. Typically, big system in big companies have constraints that do not apply to the vast majority of systems, such as dealing with thousands of requests per second or having to provide extreme availability guarantees. ## How can one mitigate the impact of failures? What should happen when one part of a system has a problem? [Margaret Hamilton](https://en.wikipedia.org/wiki/Margaret_Hamilton_(software_engineer)), who along with her team wrote the software that put spaceships in orbit and people on the Moon, recalled [in a lecture](https://www.youtube.com/watch?v=ZbVOF0Uk5lU) how she tried persuading managers to add a safety feature to a spaceship. She had brought her young daughter to work one day, and her daughter tried the spaceship simulator. Surprisingly, the daughter managed to crash the software running in the simulator. It turned out that the software was not resilient to starting one operation while the spaceship was supposed to be in a completely different phase of flight. Hamilton tried to persuade her managers that the software should be made resilient to such errors, but as she recalls it: "_[the managers] said 'this won't ever happen, astronauts are well-trained, they don't make mistakes... the very next mission, Apollo 8, this very thing happened [...] it took hours to get [data] back_". The lack of a check for this condition was an _error_, i.e., the team who programmed the software chose not to consider a problem that might happen in practice. Other kinds of errors involve forgetting to handle a failure case, or writing code that does not do what the programmer think it does. Errors cause _defects_ in the system, which can be triggered by external inputs, such as an astronaut pressing the wrong button. If defects are not handled, they cause _failures_, which we want to avoid. Errors are inevitable in any large system, because systems involve humans and humans are fallible. "Just don't make errors" is not a realistic solution. Even thinking about all possible failure cases is hard; consider the "[Cat causes login screen to hang](https://bugs.launchpad.net/ubuntu/+source/unity-greeter/+bug/1538615)" in Ubuntu. Who would have thought that thousands of characters in a username input field was a realistic possibility from a non-malicious user? Preventing failures thus requires preventing defects from propagating through the system, i.e., _mitigating_ the impact of defects. We will see four ways to do it, all based on modules: isolating, repairing, retrying, and replacing. How much effort you should put into tolerating defects depends on what is at stake. A small script you wrote yourself to fetch cartoons should be tolerant to temporary network errors, but does not need advanced recovery techniques. On the other hand, the [barrier over the Thames river](https://www.youtube.com/watch?v=eY-XHAoVEeU) that prevents mass floods needs to be resilient against lots of possible defects. ### Isolating Instead of crashing an entire piece of software, it is desirable to _isolate_ the defect and crash only one module, as small and close to the source of the defect as possible. For instance, modern Web browsers isolate each tab into its own module, and if the website inside the tab causes a problem, only that tab needs to crash, not the entire browser. Similarly, operating systems isolate each program such that only the program crashes if it has a defect, not the entire operating system. However, only isolate if the rest of the program can reasonably function without the failed module. For instance, if the module responsible for drawing the overall browser interface crashes, the rest of the browser cannot function. On the other hand, crashing only a browser tab is acceptable, as the user can still use other tabs. ### Repairing Sometimes a module can go into unexpected states due to defects, at which point it can be _repaired_ by switching to a well-known state. This does not mean moving from the unexpected state in some direction, since the module does not even know where it is, but replacing the entirety of the module's state with a specific "backup" state that is known to work. An interesting example of this is [the "top secret" room](https://zelda-archive.fandom.com/wiki/Top_Secret_Room) in the video game _The Legend of Zelda: A Link to the Past_. If the player manages to get the game into an unknown state, for instance by switching between map areas too quickly for the game to catch up, the game recognizes that it is confused and drops the player into a special room, and pretends that this is intentional and the player has found a secret area. One coarse form of repair is to "turn it off and on again", such as restarting a program, or rebooting the operating system. The state immediately after starting is known to work, but this cannot be hidden from users and is more of a way to work around a failure. However, only repair if the entirety of a module's state can be repaired to a state known to work. Repairing only part of a module risks creating a Frankenstein abomination that only makes the problem worse. ### Retrying Not all failures are forever. Some failures come from external causes that can fix themselves without your intervention, and thus _retrying_ is often a good idea. For instance, if a user's Internet connection fails, any Web request your app made will fail. But it's likely that the connection will be restored quickly, for instance because the user was temporarily in a place with low cellular connectivity such as a tunnel. Thus, retrying some number of times before giving up avoids showing unnecessary failures to the user. How many times to retry, and how much to wait before retries, is up to you, and depends on the system and its context. However, only retry if a request is _idempotent_, meaning that doing it more than once has the same effect as doing it once. For instance, withdrawing cash from a bank account is not an idempotent request. If you retry it because you didn't get a response, but the request had actually reached the server, the cash will be withdrawn twice. You should also only retry when encountering problems that are _recoverable_, i.e., for which retrying has a chance to succeed because they come from circumstances beyond your control that could fix themselves. For instance, "no internet" is recoverable, and so is "printer starting and not ready yet". This is what Java tried to model as "checked" exceptions: if the exception is recoverable, the language should force the developer to deal with it. On the other hand, problems such as "the desired username is already taken" or "the code has a bug which divided by zero" are not recoverable, because retrying will hit the same issue again and again. ### Replacing Sometimes there is more than one way to perform a task, and some of these ways can serve as backups, _replacing_ the main module if there is a problem. For instance, if a fingerprint reader cannot recognize a user's finger because the finger is too wet, an authentication system could ask for a password instead. However, only replace if you have an alternative that is as robust and tested as the original one. The "backup" module should not be old code that hasn't been run in years, but should be treated with the same care and quality bar as the main module. ## How can one reuse concepts across software systems? When designing a system, the context is often the same as in previous systems, and so are the user requirements. For instance, "cross over a body of water" is a common requirement and context that leads to the natural solution "build a bridge". If every engineer designed the concept of a bridge from scratch every time someone needed to cross a body of water, each bridge would not be very good, as it would not benefit from the knowledge accumulated by building previous bridges. Instead, engineers have blueprints for various kinds of bridges, select them based on the specifics of the problem, and propose improvements when they think of any. In software engineering, these kinds of blueprints are named _design patterns_, and are so common that one sometimes forgets they even exist. For instance, consider the following Java loop: ```java for (int item : items) { // ... } ``` This `for` construct looks perfectly normal and standard Java, but it did not always exist. It was introduced in Java 1.5, alongside the `Iterable<T>` interface, instead of having every collection provide its own way to iterate. This used to be known as "the Iterator design pattern", but nowadays it’s such a standard part of modern programming languages that we do not explicitly think of it as a design pattern any more. Design patterns are blueprints, not algorithms. A design pattern is not a piece of code you can copy-paste, but an overall description of what the solution to a common problem can look like. You can think of it as providing the name of a dish rather than the recipe for it. Have some fish? You could make fish with vegetables and rice, which is a healthy combo. Soy sauce is also a good idea as part of the sauce. How exactly you cook the fish, or which vegetables you choose, is up to you. There are many patterns, and even more descriptions of them online. We provide a [short summary](DesignPatterns.md) of common ones. In this lecture, we will see patterns to separate the user interface of a program, the business logic that is core to the program, and the reusable strategies the program needs such as retrying when a request fails. The problem solved by design patterns for user interfaces is a common one: software engineers must write code for applications that will run on different kinds of systems, such as a desktop app and a mobile app. However, writing the code once per platform would not be maintainable: most of the code would be copy-pasted. Any modification would have to be replicated on all platforms’ code, which would inevitably lead to one copy falling out of sync. Instead, software engineers should be able to write the core logic of the application once, and only write different code per platform for the user interface. This also means tests can be written against the logic without being tied to a specific user interface. This is a requirement in practice for any large application. For instance, Microsoft Office is tens of millions of lines of code; it would be entirely infeasible to have this code duplicated in Office for Windows, Mac, Android, the web, and so on. The business logic is typically called the _model_, and the user interface is called the _view_. We want to avoid coupling them, thus we naturally need something in the middle that will talk to both of them, but what? ### Model-View-Controller (MVC) In the MVC pattern, the view and model are mediated by a controller, with which users interact. A user submits a request to the controller, which interacts with the model and returns a view to the user: <p align="center"><img alt="A diagram illustrating the MVC pattern" src="images/mvc.svg" width="50%" /></p> For instance, in a website, the user's browser sends an HTTP request to the controller, which eventually creates a view using data from the model, and the view renders as HTML. The view and model are decoupled, which is good, but there are also disadvantages. First, users don’t typically talk directly to controllers, outside of the web. Second, creating a new view from scratch every time is not very efficient. ### Model-View-Presenter (MVP) In the MVP pattern, the view and model are mediated by a presenter, but the view handles user input directly. This matches the architecture of many user interfaces: users interact directly with the view, such as by touching a button on a smartphone screen. The view then informs the presenter of the interaction, which talks to the model as needed and then tells the view what to update: <p align="center"><img alt="A diagram illustrating the MVP pattern" src="images/mvp.svg" width="50%" /></p> This fixes two of MVC's problems: users don’t need to know about the intermediary module, they can interact with the view instead, and the view can be changed incrementally. --- #### Exercise Transform the code of `App.java` in the [`weather`](exercises/lecture/weather) project to use the MVP pattern. As a first step, what will the interface of your model and view look like? Once that's set, implement them by moving the existing code around, and think about what the presenter should look like. <details> <summary>Suggested solution (click to expand)</summary> <p> The model should provide a method to get the forecast, and the view should provide a method to show text and one to run the application. Then, move the existing code into implementations of the model and the view, and write a presenter that binds them together. See the [solution file](exercises/solutions/lecture/Weather.java) for an example. </p> </details> --- MVP does have disadvantages. First, the view now holds state, as it is updated incrementally. This pushes more code into the view, despite one of our original goals being to have as little code in the view as possible. Second, the interface between the view and the presenter often becomes tied to specific actions that the view can do given the context, such as a console app, and it's hard to make the view generic over many form factors. ### Model-View-ViewModel (MVVM) Let's take a step back before describing the next pattern. What is a user interface anyway? - Data to display - Commands to execute ...and that's it! At a high-level, at least. The key idea behind MVVM is that the view should observe data changes using the Observer pattern, and thus the intermediary module, the viewmodel, only needs to be a platform-independent user interface that exposes data, commands, and an Observer pattern implementation to let views observe changes. The result is a cleanly layered system, in which the view has little code and is layered on top of the viewmodel, which holds state and itself uses the model to update its state when commands are executed: <p align="center"><img alt="A diagram illustrating the MVVM pattern" src="images/mvvm.svg" width="50%" /></p> The view observes changes and updates itself. It can choose to display the data in any way it wants, as the viewmodel does not tell it how to update, only what to display. The view is conceptually a function of the viewmodel: it could be entirely computed from the viewmodel every time, or it could incrementally change itself as an optimization. This is useful for platforms such as smartphones, in which applications running in the background need to use less memory: the view can simply be destroyed, as it can be entirely re-created from the viewmodel whenever needed. MVVM also enables the code reuse we set out to achieve, as different platforms need different views but the same model and viewmodel, and the viewmodel contains the code that keeps track of state, thus the views are small. ### Middleware You've written an app using an UI design pattern to separate your business logic and your user interface, but now you get a customer request: can the data be cached so that an Internet connection isn't necessary? Also, when there isn't cached data, can the app retry if it cannot connect immediately? You could put this logic in your controller, presenter, or viewmodel, but that would tie it to a specific part of your app. You could put it in a model, but at the cost of making that module messier as it would contain multiple orthogonal concepts. Instead, this is where the _middleware_ pattern comes in, also known as _decorator_. A middleware provides a layer that exposes the same interface as the layer below but adds functionality: <p align="center"><img alt="A diagram illustrating the Middleware pattern" src="images/middleware.svg" width="50%" /></p> A middleware can "short circuit" a request if it wants to answer directly instead of using the layers below. For instance, if a cache has recent data, it could return that data without asking the layer below for the very latest data. One real-world example of middlewares is in [Windows file system minifilters](https://learn.microsoft.com/en-us/windows-hardware/drivers/ifs/filter-manager-concepts), which are middlewares for storage that perform tasks such as virus detection, logging, or replication to the cloud. This design allows programs to add their own filter in the Windows I/O stack without interfering with others. Programs such as Google Drive do not need to know about other programs such as antiviruses. --- #### Exercise You've transformed the [`weather`](exercises/lecture/weather) project to use the MVP pattern already, now add a retrying middleware that retries until the weather is known and not `???`. As a first step, write a middleware that wraps a model and provides the same interface as the model, without adding functionality. Then add the retrying logic to your middleware. <details> <summary>Suggested solution (click to expand)</summary> <p> Your middleware needs to use the wrapped model in a loop, possibly with a limit on retries. See the [solution file](exercises/solutions/lecture/RetryingWeather.java) for an example. </p> </details> --- Beware: just because you _can_ use all kinds of patterns does not mean you _should_. Remember to avoid cargo cults! If "You Aren't Gonna Need It", don't do it. Otherwise you might end up with an "implementation of AspectInstanceFactory that locates the aspect from the BeanFactory using a configured bean name", just in case somebody _could_ want this flexibility. [Really](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.html)! ## Summary In this lecture, you learned: - Abstraction and modularity, and how to use them in practice: regularity, grouping, layering, abstraction levels, and abstraction leaks - Tolerating defects: isolating, retrying, repairing, and replacing - Design patterns, and specifically common ones to decouple user interfaces, business logic, and reusable strategies: MVC, MVP, MVVM, and Middleware You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Design Patterns This document contains a curated list of common design patterns, including context and examples. _These examples are there to concisely illustrate patterns._ _Real code would also include visibility annotations (`public`, `private`, etc.), make fields `final` if possible,_ _provide documentation, and other improvements that would detract from the point being made by each example._ ## Adapter An _adapter_ converts an object of type `X` when it must be used with an interface that accepts only objects of type `X'`, similar but not the same as `X`. For instance, an app may use two libraries that both represent color with four channels, one B/G/R/A and one A/R/G/B. It is not possible to directly use an object from one library with the other library, and that's where you can use an _adapter_: an object that wraps another object and provides a different interface. A real-world example is an electrical adapter, for instance to use a Swiss device in the United States: both plugs fundamentally do the same job, but one needs a passive adapter to convert from one plug type to the other. Example: ```java interface BgraColor { // 0 = B, 1 = G, 2 = R, 3 = A float getChannel(int index); } interface ArgbColor { float getA(); float getR(); float getG(); float getB(); } class BgraToArgbAdapter implements ArgbColor { BgraColor wrapped; BgraToArgbAdapter(BgraColor wrapped) { this.wrapped = wrapped; } @Override public float getA() { return wrapped.getChannel(3); } @Override public float getR() { return wrapped.getChannel(2); } @Override public float getG() { return wrapped.getChannel(1); } @Override public float getB() { return wrapped.getChannel(0); } } ``` ## Builder A _builder_ works around the limitations of constructors when an object must be immutable yet creating it all at once is not desirable. For instance, a `Rectangle` with arguments `width, height, borderThickness, borderColor, isBorderDotted, backgroundColor` is complex, and a constructor with all of these arguments would make code creating a `Rectangle` hard to read. Furthermore, some arguments logically form groups: it is not useful to specify both `borderColor` and `isBorderDotted` if one does not want a border. Creating many rectangles that share all but a few properties is also verbose if one must re-specify all of the common properties every time. Instead, one can create a `RectangleBuilder` object that defines property groups, uses default values for unspecified properties, and has a `build()` method to create a `Rectangle`. Each method defining properties returns `this` so that the builder is easier to use. A special case of builders is when creating an object incrementally is otherwise too expensive, as in immutable strings in many languages. If one wants to create a string by appending many chunks, using the `+` operator will copy the string data over and over again, creating many intermediate strings. For instance, appending `["a", "b", "c", "d"]` without a builder will create the intermediate strings `"ab"` and `"abc"` which will not be used later. In contrast, a `StringBuilder` can internally maintain a list of appended strings, and copy their data only once when building the final string. Example: ```java class Rectangle { public Rectangle(int width, int height, int borderThickness, Color borderColor, boolean isBorderDotted, Color backgroundColor, ...) { ... } } class RectangleBuilder { // width, height are required RectangleBuilder(int width, int height) { ... } // optional, no border by default RectangleBuilder withBorder(int thickness, Color color, boolean isDotted) { ... ; return this; } // optional, no background by default RectangleBuilder withBackgroundColor(Color color) { ... ; return this; } // to create the rectangle Rectangle build() { ... } } // Usage example: new RectangleBuilder(100, 200) .withBorder(10, Colors.BLACK, true) .build(); ``` ## Composite A _composite_ handles a group of objects of the same kind as a single object, through an object that exposes the same interface as each individual object. For instance, a building with many apartments can expose an interface similar to that of a single apartment, with operations such as "list residents" that compose the results of calling the operation on each apartment in the building. Example: ```java interface FileSystemItem { String getName(); boolean containsText(String text); ... } class File implements FileSystemItem { // implementation for a file } class Folder implements FileSystemItem { Folder(String name, List<FileSystemItem> children) { ... } // the implementation of "containsText" delegates to its children // the children could themselves be folders, without Folder having to know or care } ``` ## Facade A _facade_ hides unnecessary details of legacy or third-party code behind a clean facade. It's a kind of adapter whose goal is to convert a hard-to-use interface into an easy-to-use one, containing the problematic code into a single class instead of letting it spill in the rest of the system. This can be used for legacy code that will be rewritten: if the rewritten code has the same interface as the facade, the rest of the program won't need to change after the rewrite. Example: ```java // Very detailed low-level classes, useful in some contexts, but all we want is to read some XML data class BinaryReader { BinaryReader(String path) { ... } } class StreamReader { StreamReader(BinaryReader reader) { ... } } class TextReader { TextReader(StreamReader reader) { ... } } class XMLOptions { ... } class XMLReader { XMLReader(TextReader reader, XMLOptions options) { ... } } class XMLDeserializer { XMLDeserializer(XMLReader reader, bool ignoreCase, ...) { ... } } // So we provide a facade class XMLParser { XMLParser(String path) { // ... creates a BinaryReader, then a StreamReader, ..., and uses specific parameters for XMLOptions, ignoreCase, ... } } ``` ## Factory A _factory_ is a function that works around the limitations of constructors by creating an object whose exact type depends on the arguments, which is not something most languages can do in a constructor. Thus, one creates instead a factory function whose return type is abstract and which decides what concrete type to return based on the arguments provided to the factory. Example: ```java interface Config { ... } class XMLConfig implements Config { ... } class JSONConfig implements Config { ... } class ConfigFactory { static Config getConfig(String fileName) { // depending on the file, creates a XMLConfig or a JSONConfig } } ``` ## Middleware (a.k.a. Decorator) A _middleware_, also known as _decorator_ is a layer that exposes the same interface as the layer directly below it and adds some functionality, such as caching results or retrying failed requests. Instead of bloating an object with code that implements a reusable strategy orthogonal to the object's purpose, one can "decorate" it with a middleware. Furthermore, if there are multiple implementations of an interface, without a middleware one would need to copy-paste the reusable logic in each implementation. A middleware may not always use the layer below, as it can "short circuit" a request by answering it directly, for instance if there is recent cached data for a given request. Example: ```java interface HttpClient { /** Returns null on failure */ String get(String url); } // Implements HTTP 1 class Http1Client implements HttpClient { ... } // Implements HTTP 2 class Http2Client implements HttpClient { ... } class RetryingHttpClient implements HttpClient { HttpClient wrapped; int maxRetries; HttpClientImpl(HttpClient wrapped, int maxRetries) { this.wrapped = wrapped; this.maxRetries = maxRetries; } @Override String get(String url) { for (int n = 0; n < maxRetries; n++) { String result = wrapped.get(url); if (result != null) { return result; } } return null; } } class CachingHttpClient implements HttpClient { ... } // one can now decorate any HttpClient with a RetryingHttpClient or a CachingHttpClient, // and since the interface is the same, one can decorate an already-decorated object, e.g., new CachingHttpClient(new RetryingHttpClient(new Http2Client(...), 5)) ``` ## Null Object A _null object_ is a replacement for "a lack of object", e.g., `null`, that behaves as a "no-op" for all operations, which enables the rest of the code to not have to explicitly handle it. This is useful even in languages that do not directly have `null`, such as Scala with `Option`, since sometimes one may want to run an operation on a potentially missing object without having to explicitly handle `None` everywhere. It's the equivalent of returning an empty list instead of `null` to indicate a lack of results: one can handle an empty list like any other list. Example: ```java interface File { boolean contains(String text); } class RealFile implements File { ... } class NullFile implements File { @Override boolean contains(String text) { return false; } } class FileSystem { static File getFile(String path) { // if the path doesn't exist, instead of returning `null` (or a `None` option in languages like Scala), // return a `NullFile`, which can be used like any other `File` } } ``` ## Observer The _observer_ pattern lets objects be notified of events that happen in other objects, without having to poll for changes. For instance, it would be extremely inefficient for an operating system to constantly ask the keyboard "did the user press a key?", since >99% of the time this is not the case. Instead, the keyboard lets the OS "observe" it by registering for change notifications. Furthermore, the keyboard can implement a generic "input change notifier" interface so that the OS can handle input changes without having to depend on the specifics of any input device. Similarly, the OS can implement a generic "input change observer" interface so that the keyboard can notify the OS of changes without having to depend on the specifics of any OS. Example: ```java interface ButtonObserver { // Typically the object that triggered the event is an argument, so that the observer can distinguish multiple sources // if it has registered to their events void clicked(Button source); } class Button { void registerForClicks(ButtonObserver button) { // handles a list of all observers } // optionally, could provide a way to remove an observer } // One can now ask any Button to notify us when it is clicked // In fact, the Button may implement this by itself observing a lower-level layer, e.g., the mouse, and reporting only relevant events ``` ## Pool A _pool_ keeps a set of reusable objects to amortize the cost of creating these objects, typically because their creation involves some expensive operation in terms of performance. For instance, connecting to a remote server is slow as it requires multiple round-trips to perform handshakes, cryptographic key exchanges, and so on; a connection pool can lower this cost by reusing an existing connection that another part of the program used but no longer needs. As another example, language runtimes keep a pool of free memory that can be used whenever the program allocates memory, instead of asking the operating system for memory each time, which is slow because it involves a system call. The pool still needs to perform a system call to get more memory once it's empty, but that should happen rarely. The pool pattern is typically only necessary for advanced performance optimizations. Example: ```java class ExpensiveThing { ExpensiveThing() { // ... some costly operation, e.g., opening a connection to a server ... } } class ExpensiveThingPool { private Set<ExpensiveThing> objects; ExpensiveThing get() { // ... return an existing instance if `objects` contains one, or create one if the pool is empty ... } // Warning, "releasing" the same thing twice is dangerous! void release(ExpensiveThing thing) { ... } } // Instead of `new ExpensiveThing()`, one can now use a pool ``` ## Singleton A _singleton_ is a global variable by another name, which is typically either a bad idea or a workaround for the limitations of third-party code. A singleton is an object of which there is only one instance, publicly accessible by any other code. There are advanced cases in which a singleton might be justified, such as in combination with a pool to share a pool across libraries, but it should generally be avoided. ## Strategy A _strategy_ lets the callers of a function configure part of the function's logic by passing code as a parameter. For instance, a sorting method needs a way to compare two elements, but the same type of elements might be compared in different ways based on context, such as ascending or descending for integers. The sorting method can take as argument a function that compares two elements, and then call this function whenever it needs a comparison. Thus, the sorting method only cares about implementing an efficient sorting algorithm given a way to compare, and does not hardcode a specific kind of comparison. This also ensures the sorting method does not need to depend on higher-level modules to know how to sort its input, such as what kind of object is being sorted, since the strategy takes care of that. Example: ```java // (De)serializes objects interface Serializer { ... } // Persistent cache for objets, which stores objects on disk // Uses a "serializer" strategy since depending on context one may want different serialization formats, or perhaps even encryption for sensitive data class PersistentCache { PersistentCache(Serializer serializer) { ... } } ``` ## MVC: Model-View-Controller A _controller_ is an object that handles user requests, using a _model_ internally, then creates a _view_ that is rendered to the user. MVC is appropriate when the user interacts with the controller directly, e.g., through an HTTP request. MVC can decouple user interface code and business logic, making them more maintainable, reusable, and testable. Example: ```java // Model class WeatherForecast { WeatherForecast(...) { ... } int getTemperature(...) { ... } } // View // Could be HTML as is the example here, but we could also add a `WeatherView` interface and multiple types of views, // such as a JSON one for automated request (using the HTTP "Accept" header to know what view format the user wants) class HtmlWeatherView { HtmlWeatherView(int temperature, ...) { ... } String toString() { ... } } // Controller class WeatherController { WeatherForecast forecast; WeatherController(...) { // The controller could create its own WeatherForecast object, or have it as a dependency, likely with an interface for it to make it testable forecast = ...; } HtmlWeatherView get(...) { int temperature = forecast.getTemperature(...); return new HtmlWeatherView(temperature, ...); } } // In general, one would use a framework that can be configured to know which HTTP paths correspond to which method on which controller object, // But this can be done manually as well: System.out.println(new WeatherController(...).get(...).toString()); ``` ## MVP: Model-View-Presenter A _presenter_ is an object that is used by a _view_ to respond to user commands, and which uses a _model_ internally, updating the view with the results. MVP is appropriate when the user interacts with the view, such as a mobile app, and has the same goal as MVC: make code more maintainable, reusable, and testable. Example: ```java // Model class WeatherForecast { WeatherForecast(...) { ... } int getTemperature(...) { ... } } // View // Could have an interface if a single Presenter can use multiple Views, e.g., for testing, or for multiple app form factors class WeatherView { WeatherPresenter presenter; WeatherView(WeatherPresenter presenter) { this.presenter = presenter; presenter.setView(this); // ... configure the UI framework to call `onClick` when the user clicks } void start() { /* ... display the user interface ... */ } void onClick(...) { presenter.showTemperature(); } void showTemperature(int temperature) { // ... displays `temperature` ... } } // Presenter class WeatherPresenter { WeatherForecast forecast; WeatherView view; WeatherPresenter(...) { // Same remark as the MVC example concerning injection forecast = ...; } void setView(WeatherView view) { this.view = view; } void showTemperature() { int temperature = forecast.getTemperature(...); view.showTemperature(temperature); } } // Usage example: new WeatherView(new WeatherPresenter(...)).start(); ``` ## MVVM: Model-View-ViewModel A _viewmodel_ is a platform-independent user interface, which defines data, events for data changes using the _observer_ pattern, and commands. The viewmodel internally uses a _model_ to implement operations, and a _view_ can be layered on top of the viewmodel to display the data and interact with the user. MVVM is an evolution of MVP which avoids keeping state in the view, and which emphasizes the idea of a platform-independent user interface, instead of making the presenter/view interface match a specific kind of user interface such as a console app. Example: ```java // Model class WeatherForecast { WeatherForecast(...) { ... } int getTemperature(...) { ... } } // View // There is no need for an interface, because the viewmodel does not interact with the view, // thus there can be many different views for a viewmodel without any shared interface between them class WeatherView { WeatherViewModel viewModel; WeatherView(WeatherViewModel viewModel) { this.viewModel = viewModel; viewModel.registerForTemperatureChanges(showTemperature); // ... configure the UI framework to call `onClick` when the user clicks } void start() { /* ... display the user interface ... */ } void onClick(...) { viewModel.updateTemperature(); } void showTemperature() { // ... displays `this.viewModel.getTemperature()` ... // (or the viewmodel could pass the temperature as an argument directly) } } // ViewModel class WeatherViewModel { // No reference to a view! // Only an observer pattern enabling anyone (views, but also, e.g., unit tests) to register for changes WeatherForecast forecast; int temperature; Runnable temperatureCallback; WeatherViewModel(...) { // Same remark as the MVC example concerning injection forecast = ...; } // Data int getTemperature() { return temperature; } // Data change event void registerForTemperatureChanges(Runnable action) { this.temperatureCallback = action; } // Command void updateTemperature() { // In a real app, this operation would likely be asynchronous, // the viewmodel could perhaps have an "isLoading" property enabling views to show a progress bar int temperature = forecast.getTemperature(...); this.temperature = temperature; if (temperatureCallback != null) { temperatureCallback.run(); } } } // Usage example: new WeatherView(new WeatherViewModel(...)).start(); ```
CS-305: Software engineering
# Teamwork Working on your own typically means engineering a small application, such as a calculator. To design bigger systems, teams are needed, including not only engineers but also designers, managers, customer representatives, and so on. There are different kinds of tasks to do, which need to be sub-divided and assigned to people: requirements elicitation, design, implementation, verification, maintenance, and so on. This lecture is all about teamwork: who does what when and why? ## Objectives After this lecture, you should be able to: - Contrast different software development methodologies - Apply the Scrum methodology in a software development team - Divide tasks within a development team - Produce effective code reviews ## What methodologies exist to organize a project? We will see different methodologies, but let's start with one you may have already followed without giving it a name, _waterfall_. ### Waterfall In Waterfall, the team completes each step of the development process in sequence. Waterfall is named that way because water goes down, never back up. First requirements are written down, then the software is designed, then it is implemented, then it is tested, then it is released and maintained. Once a step is finished, its output is considered done and can no longer be modified, then the next step begins. There is a clear deadline for each task, and a specific goal, such as documents containing requirements or a codebase implementing the design. Waterfall is useful for projects that have a well-defined goal which is unlikely to change, typically due to external factors such as legal frameworks or externally-imposed deadlines. Projects that use Waterfall get early validation of their requirements, and the team is forced to document the project thoroughly during design. However, Waterfall is not a good fit if customer requirements aren't set in stone, for instance because the customers might change their mind, or because the target customers aren't even well-defined. The lack of flexibility can also result in inefficiencies, since steps must be completed regardless of whether their output is actually useful. Waterfall projects also delay the validation of the product itself until the release step, which might lead to wasted work if the software does not match what the customers expected. Typically, a project might use Waterfall if there are clear requirements that cannot change, using mature technologies that won't cause surprises along the way, with a team that may not have enough experience to take decisions on its own. ### Agile Agile is not a methodology by itself but a mindset born out of reaction to Waterfall's rigidity and formality, which is not a good fit for many teams including startups. The [Agile Manifesto](https://agilemanifesto.org/) emphasizes individuals and interactions, working software, customer collaboration, and responding to change, over processes and tools, comprehensive documentation, contract negotiation, and following a plan. In practice, Agile methods are all about iterative development in a way that lets the team get frequent feedback from customers and adjust as needed. ### Scrum Scrum is an Agile method that is all about developing projects in _increments_ during _sprints_. Scrum projects are a succession of fixed-length sprints that each produce a functional increment, i.e., something the customers can try and give feedback on. Sprint are usually a few weeks long; the team chooses at the start how long sprints will be, and that duration remains constant throughout the project. At the start of each sprint, the team assigns to each member tasks to complete for that sprint, and at the end the team meets with the customer to demo the increment. Scrum teams are multi-disciplinary, have no hierarchy, and should be small, i.e., 10 people or fewer. In addition to typical roles such as engineer and designer, there are two Scrum-specific roles: the "Scrum Master" and the "Product Owner". The Scrum Master facilitates the team's work and checks in with everyone to make sure the team is on pace to deliver the expected increment. The Scrum Master is _not_ a manager, they do not decide who does what. In general, a developer takes on the extra role of Scrum Master. The Product Owner is an internal representative for the customers, who formalizes and prioritizes requirements and converts them into a "Product Backlog" of items for the development team. The Product Backlog is a _sorted_ list of items, i.e., the most important are at the top. It contains both user stories and bugs. Because it is constantly sorted, new items might be inserted in any position depending on their priority, and the bottom-most items will likely never get done, because they are not important enough. For instance, the following items might be on a backlog: - "As an admin, I want to add a welcome message on the main page, so that I can keep my users informed" - "Bug: Impossible to connect if the user name has non-ASCII characters" - "As a player, I want to chat with my team in a private chat, so that I can discuss strategies with my team" To plan a sprint, the team starts by taking the topmost item in the Product Backlog and moves it to the "Sprint Backlog", which is the list of items they expect to complete in a sprint. The team then divides the item into development tasks, such as "add an UI to set the welcome message", "return the welcome message as part of the backend API", and "show the welcome message in the app". The team assigns each task a time estimate, dependent on its complexity, a "definition of done", which will be used to know when the task is finished, and a developer to implement the task. The "definition of done" represents specific expectations from the team, so that the person to which the task is assigned knows what they have to do. It can for instance represent a user scenario: "an admin should be able to go to the settings page and write a welcome message, which must be persisted in the database". This avoids misunderstandings between developers, e.g., Alice thought saving the message to the database was part of Bob's task and Bob thought Alice would do it. Tasks implicitly contain testing: whoever writes or modifies a piece of code is in charge of testing it, though the team might make specific decisions on specific kind of tests or test scenarios. During a sprint, the team members each work on their own tasks, and have a "Daily Scrum Meeting" at the start of each day. The Daily Scrum Meeting is _short_: it should last at most 15 minutes, preferably much less, and should only be attended by the development team including the Scrum Master, not by the Product Owner nor by any customer or other person. This meeting is also known as a "standup" meeting because it should be short enough that the team does not need to formally get a room and sit down. The Daily Scrum Meeting consists of each team member explaining what they've done in the previous day, what they plan to do this day, and whether they are blocked for any reason. Any such "blockers" can then be discussed _after_ the meeting is over, with only the relevant people. This way, all team members know each other's status, but they do not need to sit through meetings that are not relevant to them. Any bugs the team finds during the sprint should be either fixed on the spot if they are small enough, or reported to the Product Owner if they need more thought. The Product Owner will then prioritize these bugs in the Product Backlog. It is entirely normal that some bugs may stay for a while in the backlog, or even never be fixed, if they are not considered important enough compared to other things the team could spend time on. Importantly, the Sprint Backlog cannot be modified during a sprint. Once the team has committed to deliver a specific increment, it works only on that increment, in a small-scale version of Waterfall. If a customer has an idea for a change, they communicate it with the Product Owner, who inserts it at the appropriate position in the Product Backlog once the sprint is over. Once the sprint is over, the team demoes the resulting increment to the customer and any relevant stakeholders as part of a "Sprint Review" to get feedback, which can then be used by the Product Owner to add, remove, or edit Product Backlog items. The team then performs a "Sprint Retrospective" without the customer to discuss the development process itself. Once the Review and Retrospective are done, the team plans the next sprint and executes it, and the process starts anew. Scrum does not require all requirements to be known upfront, unlike Waterfall, which gives it flexibility. The team can change direction during development, since each sprint is an occasion to get customer feedback and act on it. The product can thus be validated often with the customer, which helps avoid building the wrong thing. However, Scrum does not impose any specific deadlines for the final product, and requires the existence of customers, or at least of someone who can play the role of customer if the exact customers are not yet known. It also does not fit well with micro-managers or specific external deadlines, since the team is in charge of its own direction. ### Other methodologies There are plenty of other software development methodologies we will not talk about in depth. For instance, the "[V Model](https://en.wikipedia.org/wiki/V-Model)" tries to represent Waterfall with more connections between design and testing, and the "[Spiral model](https://en.wikipedia.org/wiki/Spiral_model)" is designed to minimize risks. [Kanban](https://en.wikipedia.org/wiki/Kanban_(development)) is an interesting methodology that essentially takes Scrum to its logical extreme, centered on a board with tasks in various states that start from a sorted backlog and end in a "done" column. ## How can one effectively work in a team? The overall workflow of an engineer in a team is straightforward: create a branch in the codebase, work on it, then iterate on the work with feedback from the team before integrating the work in the codebase. This raises many questions. How can one form a team? How to be a "good" team member? How to divide tasks among team members? Team formation depends on development methodologies. In Scrum, teams are multi-disciplinary, i.e., there is no "user interface team" or "database team" but rather teams focused on an overall end-to-end product that include diverse specialists. Scrum encourages "two-pizza" teams, i.e., teams that could be fed with two large pizzas, so 4-8 people. Being a good team member requires three skills: communication, communication, and communication. Do you need help because you can't find a solution to a problem? Are you blocked because of factors outside of your control? Communicate! There are no winners on a losing team. It is not useful to write "perfect" code in isolation if it does not integrate with the rest of the team's code, or if there are other more important tasks to be done than the code itself, such as helping a teammate. A bug is never due to a single team member, since it implies the people who reviewed the code also made mistakes by not spotting the bug. Do not try to assign blame within the team for a problem, but instead communicate in a way that is the team vs. the problem. Dividing tasks within a team is unfortunately more of an art than a science, and thus requires practice to get right. If the tasks are too small, the overhead of each task's fixed costs is too high. If the tasks are too big, planning is hard because there are too many unknowns per task. One heuristic for task size is to think in terms of code review: what will the code for the task roughly look like, and how easy will that be to review? If the tasks are estimated to take more time than they really need, the team will run out of work to do and will need to plan again. If the tasks are estimated to take too little time, the team will not honor its deadlines. Estimating the complexity of a task is difficult and comes with experience. One way to do it is with "planning poker", in which team members write down privately their time estimate, then everyone reveals their estimate at once, the team discusses the results, and the process starts again until all team members independently agree. If the tasks are assigned to the wrong people, the team may not finish them on time because members have to spend too much time doing things they are not familiar with or do not enjoy doing. One key heuristic to divide tasks is to maximize parallelism while minimizing dependencies and interactions. If two people have to constantly meet in order to work, perhaps their tasks could be split differently so they need to meet less. Typically, a single task should be assigned to and doable by a single person. An important concept when assigning work within a team is the "bus factor": how many team members can be hit by a bus before the team can no longer continue working? This is a rather morbid way to look at it; one can also think of vacations, illnesses, or personal emergencies. Many teams have a bus factor of 1, because there is at least one member who is the only person with knowledge of some important task, password, or code. If this member leaves the team, gets sick, or is in any way incapacitated, the team grinds to a halt because they can no longer perform key tasks. Thus, tasks should be assigned such that nobody is the only person who ever does specific key tasks. One common mistake is to assign tasks in terms of application layers rather than end-to-end functionality. For instance, the entirety of the database work for a sprint in Scrum could be assigned to one person, the entirety of the UI work to another, and so on. However, if the database person cannot do their work, for instance because of illness, then no matter what other team members do, nothing will work end-to-end. Furthermore, if the same people are continuously assigned to the same layers, the bus factor becomes 1. Instead, team members should be assigned to features, such as one person in charge of user login, one in charge of informational messages, and one in charge of chat. Finally, another common mistake is to make unrealistic assumptions regarding time: everyone will finish on time, and little time is necessary to integrate the code from all tasks into the codebase. Realistically, some tasks will always be late due to incorrect estimations, illnesses, or other external factors. Integrating the code from all tasks also takes time and may require rework, because engineers may realize that they misunderstood each other and that they did not produce compatible code. It is necessary to plan for more time than the "ideal" time per task. ## How can one produce a useful code review? Code reviews have multiple goals. The most obvious one is to review the code for bugs, to stop bugs getting into the main branch of the codebase. Reviewers can also propose alternative solutions that may be more maintainable than the one proposed by the code author. Code review is also a good time for team members to learn about codebase changes. In 2013, [Bacchelli and Bird](https://dl.acm.org/doi/10.5555/2486788.2486882) found that knowledge transfer and shared code ownership were important reasons developers did code reviews in practice, right behind finding defects, improving the code, and proposing alternative solutions. Code reviews are cooperative, not adversarial. The point is not to try and find possible "backdoors" a colleague might have inserted; if you have a malicious colleague, code reviews are not the tool to deal with the problem. That is, unless your "colleague" is not a colleague but a random person on the Internet suggesting a change to your open source software, at which point you need to be more careful. ### Team standards and tools Each team must decide the standards with which it will review code, such as naming and formatting conventions and expected test coverage. Automate as much as possible: do not ask reviewers to check compliance with a specific naming convention if a static analyzer can do it, or to check the code coverage if a tool can run the tests and report the coverage. ### From the author's side To maximize the usefulness of the reviews you get as a code author, first review the code yourself to avoid wasting people's time with issues you could've found yourself, and then choose appropriate reviewers. For instance, you may ask a person who has worked for a while on that part of the codebase to chime in, as well as an expert on a specific subject such as security. Make it clear what you expect from the reviewers. Is this a "draft" pull request that you might heavily change? Is it a fix that must go in urgently and thus should get reviews as soon as possible? You also want to give reviewers a reasonable amount of code to review, ideally a few hundred lines of code at most. It's perfectly acceptable to open multiple pull requests in parallel for independent features, or to open pull requests sequentially for self-contained chunks of a single feature. ### From the reviewer's side Skim the code in its entirety first to understand what is going on, then read it in details with specific goals in mind, adding comments as you go. Finally, make a decision: does the code need changes or should it be merged as-is? If you request changes, perform another review once these are done. Since you might do multiple reviews, don't bother pointing out small issues if you are going to ask for major changes anyway. Sometimes you may also want to merge the code yet create a bug report for small fixes that should be performed later, if merging the code is important to unblock someone else. Evaluate the code in terms of correctness, design, maintainability, readability, and any other bar you think is important. For instance, do you think another developer could easily pick up the code and evolve it? If not, you likely want to explain why and what could be done to improve this aspect. When writing a comment, categorize it: are you requesting an important change? is it a small "nitpick"? is it merely a question for your own understanding? For instance, you could write "Important: this bound should be N+1, not N, because..." or "Question: could this code use the existing function X instead of including its own logic to do Y?". Be explicit: make it clear whether you are actually requesting a change, or merely doing some public brain-storming for potential future changes. Pick your battles: sometimes you may personally prefer one way to do it, but still accept what the author did instead of asking for small changes that don't really matter in the big picture. Remember to comment on _the code_, not _the person who wrote the code_. "Your code is insecure" is unnecessarily personal; "this method is insecure" avoids this problem. If you do not perform a thorough review of all of the code, specify what you did. It's perfectly fine to only check changes to code you already know, or to not be confident in evaluating specific aspects such as security or accessibility, but you must make this clear so that the code author does not get the wrong idea. There are plenty of guidelines available on the Internet that you might find useful, such as [Google's](https://google.github.io/eng-practices/review/reviewer/). ## Summary In this lecture, you learned: - Development methodologies, including Waterfall and especially Scrum - Dividing tasks within a team to maximize productivity and minimize conflicts - What code reviews are for and how to write one You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Testing > **Prerequisite**: Before following this lecture, you should make sure you can build and run the [sample project](exercises/sample-project). It's tempting to think that testing is not necessary if one "just" writes correct code from the first try and double-checks the code before running it. But in practice, this does not work. Humans make mistakes all the time. Even [Ada Lovelace](https://en.wikipedia.org/wiki/Ada_Lovelace), who wrote a correct algorithm to compute Bernoulli numbers for [Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage)'s "[Analytical Engine](https://en.wikipedia.org/wiki/Analytical_Engine)", made a typo by switching two variables in the code transcription of her algorithm. And she had plenty of time to double-check it, since the Analytical Engine was a proposed design by Babbage that was not actually implemented! The "first program ever" already contained a typo. One modern option is computer-aided verification, but it requires lots of time. If Ada Lovelace had lived in the 21st century, she could have written a proof and gotten a computer to check it, ensuring that the proof is correct as long as the prover program is itself correct. This can work in practice, but currently at the cost of high developer effort. The [seL4 operating system kernel](https://sel4.systems/), for instance, required 200,000 lines of proof for its 10,000 lines of code (Klein et al., ["seL4: formal verification of an OS kernel"](https://dl.acm.org/doi/10.1145/1629575.1629596)). Such a method might have worked for Ada Lovelace, an aristocrat with plenty of free time, but is not realistic yet for everyday programmers. Another modern option is to let users do the work, in a "beta" or "early access" release. Users get to use a program ahead of everyone else, at the cost of encountering bugs and reporting them, effectively making them testers. However, this only works if the program is interesting enough, such as a game, yet most programs out there are designed as internal tools for small audiences that are unlikely to want to beta test. Furthermore, it does not eliminate bugs entirely either. Amazon's "New World" game, despite having an "Open Beta" period, [released](https://www.denofgeek.com/games/new-world-bugs-glitches-exploits-list-cyberpunk-2077/) with many glitches including a 7-day delay before respawning. Do we even need tests in the first place? What's the worst that could happen with a bug? In some scenarios, the worst is not that bad comparatively, such as a bug in an online game. But imagine a bug in the course registration system of a university, leaving students wondering whether they are signed up to a course or not. Worse, a bug in a bank could make money appear or disappear at random. Even worse, bugs can be lethal, as in the [Therac-25 radiation therapy machine](https://en.wikipedia.org/wiki/Therac-25) which killed some patients. ## Objectives After this lecture, you should be able to: - Understand the basics of _automated testing_ - Evaluate tests with _code coverage_ - Identify _when_ to write which tests - _Adapt_ code to enable fine-grained testing ## What is a test? Testing is, at its core, three steps: 1. Set up the system 2. Perform an action 3. Check the outcome If the outcome is the one we expect, we gain confidence that the system does the right thing. However, "confidence" is not a guarantee. As [Edsger W. Dijkstra](https://en.wikipedia.org/wiki/Edsger_W._Dijkstra) once said, "_Program testing can be used to show the presence of bugs, but never to show their absence!_". The simplest way to test is manual testing. A human manually performs the workflow above. This has the advantage of being easy, since one only has to perform the actions that would be typically expected of users anyway. It also allows for a degree of subjectivity: the outcome must "look right", but one does not need to formally define what "looking right" means. However, manual testing has many disadvantages. It is slow: imagine manually performing a hundred tests. It is also error-prone: the odds increase with each test that a human will forget to perform one step, or perform a step incorrectly, or not notice that something is wrong. The subjectivity of manual testing is also often a disadvantage: two people may not agree on exactly what "right" or "wrong" is for a given test. Finally, it also makes it hard to test edge cases. Imagine testing that a weather app correctly shows snowfalls when they occur if it's currently sunny outside your home. To avoid the issues of manual testing, we will focus on automated testing. The workflow is fundamentally the same, but automated: 1. Code sets up the system 2. Code performs an action 3. Code checks the outcome These steps are commonly known as "Arrange", "Act", and "Assert". Automated testing can be done quickly, since computers are much faster than human, and do not forget steps or randomly make mistakes. This does not mean automated tests are always correct: if the code describing the test is wrong, then the test result is meaningless. Automated testing is also more objective: the person writing the test knows exactly what will be tested. Finally, it makes testing edge cases possible by programmatically faking the environment of the system under test, such as the weather forecast server for a weather app. There are other benefits to automated testing too: tests can be written once and used forever, everywhere, even on different implementations. For instance, the [CommonMark specification](https://spec.commonmark.org/) for Markdown parsers includes many examples that are used as tests, allowing anyone to use these tests to check their own parser. If someone notices a bug in their parser that was not covered by the standard tests, they can suggest a test that covers this bug for the next version of the specification. This test can then be used by everyone else. The number of tests grows and grows with time, and can reach enormous amounts such as [the SQLite test suite](https://www.sqlite.org/testing.html), which currently has over 90 million lines of tests. On the flip side, automated testing is harder than manual testing because one needs to spend time writing the test code, which includes a formal definition of what the "right" behavior is. ## How does one write automated tests? We will use Java as an example, but automated testing works the same way in most languages. The key idea is that each test is a Java method, and a test failure is indicated by the method throwing an exception. If the method does not throw exceptions, then the test passes. One way to do it using Java's built-in concepts is the following: ```java void test1plus1() { assert add(1, 1) == 2 } ``` If `add(1, 1)` returns `2`, then the assertion does nothing, the method finishes, and the test is considered to pass. But if it returns some other number, the assertion throws an `AssertionError`, which is a kind of exception, and the test is considered to fail. ...or, at least, that's how it should be, but [Java asserts are disabled by default](https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html), unfortunately. So this method does absolutely nothing unless the person running the test remembers to enable assertions. One could mimic the `assert` statement with an `if` and a `throw`: ```java void test1plus1() { if (add(1, 1) != 2) { throw new AssertionError() } } ``` This is a working implementation of a test, which we could run from a `main` method. However, if the test fails, there is no error message, since we did not put one when creating the `AssertionError`. For instance, if the test fails, what did `add(1, 1)` actually return? It would be good to know this. We could write code to store the result in a variable, test against that variable, and then create a message for the exception including that variable. Or we could use [JUnit](https://junit.org/junit5/) to do it for us: ```java @Test void test1plus1() { assertEquals(add(1, 1), 2); } ``` JUnit finds all methods annotated with `@Test` and runs them, freeing us from the need to write the code to do it ourselves, and throws exceptions whose message includes the "expected" and the "actual" value. ...wait, did we do that right? Should we have put the "expected" value first? It's hard to remember. And even if we do that part right, it's hard to make assertion messages useful for tests such as "this list should either be empty or contain `[1, 2, 3]`". We can write code to check that, but if the test fails we will get "expected `true`, but was `false`", which is not useful. Instead, let's use [Hamcrest](https://hamcrest.org/JavaHamcrest/) to write our assertions on top of JUnit: ```java @Test void test1plus1() { assertThat(add(1, 1), is(2)); } ``` This is much clearer! The `is` part is a Hamcrest "matcher", which describes what value is expected. `is` is the simplest one, matching exactly one value, but we can use fancier ones: ```java List<Integer> values = ...; assertThat(values, either(empty()) .or(contains(1, 2, 3))); ``` If this assertion fails, Hamcrest's exception message states "Expected: (an empty collection or iterable containing `[<1>, <2>, <3>]`) but: was `<[42]>`". Sometimes we need to test that a piece of code _fails_ in some circumstances, such as validating arguments properly and throwing an exception of an argument has an invalid value. This is what `assertThrows` is for: ```java var ex = assertThrows( SomeException.class, () -> someOperation(42) ); // ... test 'ex'... ``` The first argument is the type of exception we expect, the second is a function that should throw that type of exception. If the function does not throw an exception, or throws an exception of another type, `assertThrows` will throw an exception to indicate the test failed. If the function does throw an exception of the right type, `assertThrows` returns that exception so that we can test it further if needed, such as asserting some fact about its message. --- #### Exercise It's your turn now! Open [the in-lecture exercise project](exercises/lecture) and test `Functions.java`. Start by testing valid values for `fibonacci`, then test that it rejects invalid values. For `split` and `shuffle`, remember that Hamcrest has many matchers and has documentation. <details> <summary>Example solution (click to expand)</summary> <p> You could test `fibonacci` using the `is` matcher we discussed earlier for numbers such as 1 and 10, and test that it throws an exception with numbers below `0` using `assertThrows`. To test `split`, you could use Hamcrest's `contains` matcher, and for the shuffling function, you could use `arrayContainingInAnyOrder`. We provide some [examples](exercises/solutions/lecture/FunctionsTests.java). </p> </details> --- **Should you test many things in one method, or have many small test methods?** Think of what the tests output will look like if you combine many tests in one method. If the test method fails, you will only get one exception message about the first failure in the method, and will not know whether the rest of the test method would pass. Having big test methods also means the fraction of passing tests is less representative of the overall code correctness. In the extreme, if you wrote all assertions in a single method, a single bug in your code would lead to 0% of passing tests. Thus, you should prefer small test methods that each test one "logical" concept, which may need one or multiple assertions. This does not mean one should copy-paste large blocks of code between tests; instead, share code using features such as JUnit's `@BeforeAll`, `@AfterAll`, `@BeforeEach`, and `@AfterEach` annotations. **How can you test private methods?** You **don't**. Otherwise the tests must be rewritten every time the implementation changes. Think back to the SQLite example: the code would be impossible to change if any change in implementation details required modifying even a fraction of the 90 million lines of tests. **What standards should you have for test code?** The same as for the rest of the code. Test code should be in the same version control repository as other code, and should be reviewed just like other code when making changes. This also means tests should have proper names, not `test1` or `testFeatureWorks` but specific names that give information in an overview of tests such as `nameCanIncludeThaiCharacters`. Avoid names that use vague descriptions such as "correctly", "works", or "valid". ## What metric can one use to evaluate tests? What makes a good test? When reviewing a code change, how does one know whether the existing tests are enough, or whether there should be more or fewer tests? When reviewing a test, how does one know if it is useful? There are many ways to evaluate tests; we will focus here on the most common one, _coverage_. Test coverage is defined as the fraction of code executed by tests compared to the total amount of code. Without tests, it is 0%. With tests that execute each part of the code at least once, it is 100%. But what is a "part of the code"? What should be the exact metric for coverage? One naïve way to do it is _line_ coverage. Consider this example: ```java int getFee(Package pkg) { if (pkg == null) throw ...; int fee = 10; if (pkg.isHeavy()) fee += 10; if (pkg.isInternational()) fee *= 2; return fee; } ``` A single test with a non-null package that is both heavy and international will cover both lines. This may sound great since the coverage is 100% and easy to obtain, but it is not. If the `throw` was on a different line instead of being on the same line as the `if`, line coverage would no longer be 100%. It is not a good idea to define a metric for coverage that depends on code formatting. Instead, the simplest metric for test coverage is _statement_ coverage. In our example, the `throw` statement is not covered but all others are, and this does not change based on code formatting. Still, reaching almost 100% statement coverage based on a single test for the code above seems wrong. There are three `if` statements, indicating the code performs different actions based on a condition, yet we ignored the implicit `else` blocks in those ifs. A more advanced form of coverage is _branch_ coverage: the fraction of branch choices that are covered. For each branch, such as an `if` statement, 100% branch coverage requires covering both choices. In the code above, branch coverage for our single example test is 50%: we have covered exactly half of the choices. Reaching 100% can be done with two additional tests: one null package, and one package that is neither heavy nor international. But let us take a step back for a moment and think about what our example code can do: <p align="center"><img alt="Illustration of the paths in the code above; there are five, one throwing and four returning fee values" src="images/paths.svg" width="50%" /></p> There are five paths throughout the code, one of which fails. Yet, with branch coverage, we could declare victory after only three tests, leaving two paths unexplored. This is where path coverage comes in. Path coverage is the most advanced form of coverage, counting the fraction of paths throughout the code that are executed. Our three tests cover 60% of paths, i.e., 3 out of 5. We can reach 100% by adding tests for the two uncovered paths: a package that is heavy but not international, and one that is the other way around. Path coverage sounds very nice in theory. But in practice, it is often infeasible, as is obvious from the following example: ```java while (true) { var input = getUserInput(); if (input.length() <= 10) break; tellUser("No more than 10 chars"); } ``` The maximum path coverage obtainable for this code is _zero_. That's because there is an infinite number of paths: the loop could execute once, or twice, or thrice, and so on. Since one can only write a finite number of tests, path coverage is blocked at 0%. Even without infinite loops, path coverage is hard to obtain in practice. With just 5 independent `if` statements that do not return early or throw, one must write 32 tests. If 1/10th of the lines of code are if statements, a 5-million-lines program has more paths than there are atoms in the universe. And 5 million lines is well below what some programs have in practice, such as browsers. There is thus a tradeoff in coverage between feasibility and confidence. Statement coverage is typically easy to obtain but does not give that much confidence, whereas path coverage can be impossible to obtain in practice but gives a lot of confidence. Branch coverage is a middle ground. It is important to note that coverage is not everything. We could cover 100% of the paths in our "get fee" function above with 5 tests, but if those 5 tests do not actually check the value returned by the function, they are not useful. Coverage is a metric that should help you decide whether additional tests would be useful, but it does not replace human review. --- #### Exercise Run your tests from the previous exercise with coverage. You can do so either from the command line or from your favorite IDE, which should have a "run tests with coverage" command next to "run tests". Note that using the command line will run the [JaCoCo](https://www.jacoco.org/jacoco/) tool, which is a common way to get code coverage in Java. If you use an IDE, you may use the IDE's own code coverage tool, which could have minor differences in coverage compared to JaCoCo in some cases. ## When to test? Up until now we have assumed tests are written after development, before the code is released. This is convenient, since the code being tested already exists. But it has the risk of duplicating any mistakes found in the code: if an engineer did not think of an edge case while writing the code, they are unlikely to think about it while writing the tests immediately afterwards. It's also too late to fix the design: if a test case reveals that the code does not work because its design needs fundamental alterations, this will likely have to be done quickly under pressure due to a deadline, leading to a suboptimal design. If we simplify a product lifecycle to its development and its release, there are three times at which we could test: <p align="center"><img alt="Product lifecycle with 'development' followed by 'testing', and three times to test: before both, between both, or after both" src="images/lifecycle.svg" width="50%" /></p> The middle one is the one we have seen already. The two others may seem odd at first glance, but they have good reasons to exist. Testing before development is commonly known as **test-driven development**, or _TDD_ for short, because the tests "drive" the development, specifically the design of the code. In TDD, one first writes tests, then the code. After writing the code, one can run the tests and fix any bugs. This forces programmers to think before coding, instead of writing the first thing that comes to mind. It provides instant feedback while writing the code, which can be very gratifying: write some of the code, run the tests, and some tests now pass! This gives a kind of progress indication. It's also not too late to fix the design, since the design does not exist yet. The main downside of TDD is that it requires a higher time investment, and may even lead to missed deadlines. This is because the code under test must be written regardless of what tests are written. If too much time is spent writing tests, there won't be enough time left to write the code. When testing after development, this is not a problem because it's always possible to stop writing tests at any time, since the code already exists, at the cost of fewer tests and thus less confidence in the code. Another downside of TDD is that the design must be known upfront, which is fine when developing a module according to customer requirements but not when prototyping, for instance, research code. There is no point in writing a comprehensive test suite for a program if that program's very purpose will change the next day after some thinking. Let us now walk through a TDD example step by step. You are a software engineer developing an application for a bank. Your first task is to implement money withdrawal from an account. The bank tells you that "users can withdraw money from their bank account". This leaves you with a question, which you ask the bank: "can a bank account have a balance below zero?". The bank answers "no", that is not possible. You start by writing a test: ```java @Test void canWithdrawNothing() { var account = new Account(100); assertThat(account.withdraw(0), is(0)); } ``` The `new Account` constructor and the `withdraw` method do not exist, so you create a "skeleton" code that is only enough to make the tests _compile_, not pass yet: ```java class Account { Account(int balance) { } int withdraw(int amount) { throw new UnsupportedOperationException("TODO"); } } ``` You can now add another test for the "balance below zero" question you had: ```java @Test void noInitWithBalanceBelow0() { assertThrows(IllegalArgumentException.class, () -> new Account(-1)); } ``` This test does not require more methods in `Account`, so you continue with another test: ```java @Test void canWithdrawLessThanBalance() { var account = new Account(100); assertThat(account.withdraw(10), is(10)); assertThat(account.balance(), is(90)); } ``` This time you need to add a `balance` method to `Account`, with the same body as `withdraw`. Again, the point is to make tests compile, not pass yet. You then add one final test for partial withdrawals: ```java @Test void partialWithdrawIfLowBalance() { var account = new Account(10); assertThat(account.withdraw(20), is(10)); assertThat(account.balance(), is(0)); } ``` Now you can run the tests... and see them all fail! This is normal, since you did not actually implement anything. You can now implement `Account` and run the tests every time you make a change until they all pass. Finally, you go back to your customer, the bank, and ask what is next. They give you another requirement they had forgotten about: the bank can block accounts and withdrawing from a blocked account has no effect. You can now translate this requirement into tests, adding code as needed to make the tests compile, then implement the code. Once you finish, you will go back to asking for requirements, and so on until your application meets all the requirements. ---- #### Exercise It's your turn now! In [the in-lecture exercise project](exercises/lecture) you will find `PeopleCounter.java`, which is documented but not implemented. Write tests first then implement the code and fix your code if it doesn't pass the tests, in a TDD fashion. First, think of what tests to write, then write them, then implement the code. <details> <summary>Example tests (click to expand)</summary> <p> You could have five tests: the counter initializes to zero, the "increment" method increments the counter, the "reset" method sets the counter to zero, the "increment" method does not increment beyond the maximum, and the maximum cannot be below zero. We provide [sample tests](exercises/solutions/lecture/PeopleCounterTests.java) and [a reference implementation](exercises/solutions/lecture/PeopleCounter.java). </p> </details> ---- Testing after deployment is commonly known as **regression testing**. The goal is to ensure old bugs do not come back. When confronted with a bug, the idea is to first write a failing test that reproduces the bug, then fix the bug, then run the test again to show that the bug is fixed. It is crucial to run the test before fixing the bug to ensure it actually fails. Otherwise, the test might not actually reproduce the bug, and will "pass" after the bug fix only because it was already passing before, providing no useful information. Recall the SQLite example: all of these 90 million lines of code show that a very long list of possible bugs will not appear again in any future release. This does not mean there are no bugs left, but that many if not all common bugs have been removed, and that the rest are most likely unusual edge cases that nobody has encountered yet. ## How can one test entire modules? Up until now we have seen tests for pure functions, which have no dependencies on other code. Testing them is useful to gain confidence in their correctness, but not all code is structured as pure functions. Consider the following function: ```java /** Downloads the book with the given ID * and prints it to the console. */ void printBook(String bookId); ``` How can we test this? First off, the function returns `void`, i.e., nothing, so what can we even test? The documentation also mentions downloading data, but from where does this function do that? We could test this function by passing a book ID we know to be valid and checking the output. However, that book could one day be removed, or have its contents update, invalidating our test. Furthermore, tests that depend on the environment such as the book repository this function uses cannot easily test edge cases. How should we test what happens if there is a malformed book content? Or if the Internet connection drops after downloading the table of contents but before downloading the first chapter? One could design _end-to-end tests_ for this function: run the function in a custom environment, such as a virtual machine whose network requests are intercepted, and parse its output from the console, or perhaps redirect it to a file. While end-to-end testing is useful, it requires considerable time and effort, and is infrastructure that must be maintained. Instead, let's address the root cause of the problem: the input and output to `printBook` are _implicit_, when they should be _explicit_. Let's make the input explicit first, by designing an interface for HTTP requests: ```java interface HttpClient { String get(String url); } ``` We can then give an `HttpClient` as a parameter to `printBook`, which will use it instead of doing HTTP requests itself. This makes the input explicit, and also makes the `printBook` code more focused on the task it's supposed to do rather than on the details of HTTP requests. Our `printBook` function with an explicit input thus looks like this: ```java void printBook( String bookId, HttpClient client ); ``` This process of making dependencies explicit and passing them as inputs is called **dependency injection**. We can then test it with whatever HTTP responses we want, including exceptions, by creating a fake HTTP client for tests: ```java var fakeClient = new HttpClient() { @Override public String get(String url) { ... } } ``` Meanwhile, in production code we will implement HTTP requests in a `RealHttpClient` class so that we can call `printBook(id, new RealHttpClient(...))`. We could make the output explicit in the same way, by creating a `ConsolePrinter` interface that we pass as an argument to `printBook`. However, we can change the method to return the text instead, which is often simpler: ```java String getBook( String bookId, HttpClient client ); ``` We can now test the result of `getBook`, and in production code feed it to `System.out.println`. Adapting code by injecting dependencies and making outputs explicit enables us to test more code with "simple" tests rather than complex end-to-end tests. While end-to-end tests would still be useful to ensure we pass the right dependencies and use the outputs in the right way, manual testing for end-to-end scenarios already provides a reasonable amount of confidence. For instance, if the code is not printing to the console at all, a human will definitely notice it. This kind of code changes can be done recursively until only "glue code" between modules and low-level primitives remain untestable. For instance, an "UDP client" class can take an "IP client" interface as a parameter, so that the UDP functionality is testable. The implementation of the "IP client" interface can itself take a "Data client" interface as a parameter, so that the IP functionality is testable. The implementations of the "Data client" interface, such as Ethernet or Wi-Fi, will likely need end-to-end testing since they do not themselves rely on other local software. --- #### Exercise It's your turn now! In [the in-lecture exercise project](exercises/lecture) you will find `JokeFetcher.java`, which is not easy to test in its current state. Change it to make it testable, write tests for it, and change `App.java` to match the `JokeFetcher` changes and preserve the original program's functionality. Start by writing an interface for an HTTP client, implement it by moving existing code around, and use it in `JokeFetcher`. Then add tests. <details> <summary>Suggestions (click to expand)</summary> <p> The changes necessary are similar to those we discussed above, including injecting an `HttpClient` dependency and making the function return a `String`. We provide [an example `JokeFetcher`](exercises/solutions/lecture/JokeFetcher.java), [an example `App`](exercises/solutions/lecture/App.java), and [tests](exercises/solutions/lecture/JokeFetcherTests.java). </p> </details> ---- If you need to write lots of different fake dependencies, you may find _mocking_ frameworks such as [Mockito](https://site.mockito.org/) for Java useful. These frameworks enable you to write a fake `HttpClient`, for instance, like this: ```java var client = mock(HttpClient.class); when(client.get(anyString())).thenReturn("Hello"); // there are also methods to throw an exception, check that specific calls were made, etc. ``` There are other kinds of tests we have not talked about in this lecture, such as performance testing, accessibility testing, usability testing, and so on. We will see some of them in future lectures. ## Summary In this lecture, you learned: - Automated testing, its basics, some good practices, and how to adapt code to make it testable - Code coverage as a way to evaluate tests, including statement coverage, branch coverage, and path coverage - When tests are useful, including testing after development, TDD, and regression tests You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Mobile Platforms This lecture's purpose is to give you a high-level picture of what the universe of mobile applications and devices is like. You will read about: * Differences between desktops and mobile devices w.r.t. applications, security, energy, and other related aspects * Challenges and opportunities created by mobile platforms * Brief specifics of the Android stack and how applications are structured * A few ideas for offering users a good experience on their mobile * The ecosystem that mobile apps plug into ## From desktops to mobiles Roughly every decade, a new, lower priced computer class forms, based on a new programming platform, network, and interface. This results in new types of usage, and often the establishment of a new industry. This is known as [Bell's Law](https://en.wikipedia.org/wiki/Bell%27s_law_of_computer_classes). With every new computer class, the number of computers per person increases drastically. Today we have clouds of vast data centers, and perhaps an individual computer, like our laptop, that we use to be productive. On top of that come several computer devices per individual, like phones, wearables, and smart home items, which we use for entertainment, communication, quality of life, and so on. It is in this context that mobile software development becomes super-important. We said earlier that, no matter what job you will have, you will write code. We can add to that: you will likely write code for mobile devices. There are more than 15 billion mobile devices operating worldwide, and that number is only going up. As Gordon Bell said, this leads to new usage patterns. We access the Internet more often from our mobile than our desktop or laptop. Most of the digital content we consume we do so on mobiles. We spend hours a day on our mobile, and the vast majority of that time we spend in apps, not on websites. A simple example of a major change in how we use computing and communication is social media. Most of the world's population uses it. It changes how we work. Even the professional workforce is increasingly dependent on mobiles, for this reason. ### Mobile vs. desktop: Applications There are many differences between how we write applications for a mobile device vs. a desktop computer. On a desktop, applications can do pretty much whatever they want, whereas, on a mobile, each app is super-specialized. On the desktop, users explicitly starts applications; on mobile, the difference between running or not is fluid: apps can be killed anytime, and they need to be ready to restart. On a desktop, you typically have multiple applications active in the foreground, with multiple windows on-screen. The mobile experience is difference: a user's interaction with an app doesn't always begin in the same place, but rather the user's journey often begins non-deterministically. As a result, a mobile app has a more complex structure than a traditional desktop application, with multiple types of components and entry points. The execution model on mobiles is more cooperative than on a desktop. For example, a social media app allows you to compose an email, and does so by reusing the email app. Another example is something like WhatsApp, which allows you to take pictures (and does so by asking the Photo app to do it). In essence, apps request services from other apps, and they build upon the functionality of others, which is fundamentally difference from the desktop application paradigm. ### Mobile vs. desktop: Operating environment One of the biggest differences is in the security model. Think of your parents' PC at home or in an Internet café: there are potentially multiple users that don’t trust each other, each have specific file permissions, every application by default inherits all of a user's permissions, all applications are trusted to run with user's privileges alongside each other. The operating system prevents one application from overwriting others, but does not protect the I/O resources (e.g., files). One could fairly say that security is somewhat of an afterthought on the desktop. A mobile OS has considerably stronger isolation. The assumption here is that users might naively install malicious apps, and the goal is to protect users’ data (and privacy) even when they do stupid things. So, each mobile app is sandboxed separately. When you install a mobile app, it will ask the device for necessary permissions, like access to contacts, camera, microphone, location information, SMS, WiFi, user accounts, body sensors, etc. A mobile device is more constrained, e.g., you don't really get "root" access. It provides strong hardware-based isolation and powerful authentication features (like face recognition). E.g., for iPhone's FaceID, the face scan pattern is encrypted and sent to a secure hardware "enclave" in the CPU, to make sure that stored facial data is inaccessible to any party, including Apple. Power management is a first-class citizen in a mobile OS. While PCs use high-power CPUs and GPUs with heatsinks, smartphones and tablets are typically not plugged in, so they cannot provide sustained high power. On a mobile, the biggest energy hog is typically the screen, whereas in a desktop it is the CPU and GPU. Desktop OSes tend to be generic, whereas mobile OSes specialize for a given set of mobile devices, so they can have strict hardware requirements. This leads to less backward compatibility, and so the latest apps will not run on older versions of the OS, and new versions of a mobile OS won't run on older devices. There is also orders-of-magnitude less storage on mobiles, and orders-of-magnitude less memory. Plus, you cannot easily expand / modify storage and memory. Mobile networking tends to be more intermittent than in-wall connectivity. An Ethernet connections gives you Gbps, while a WiFi connection gives you Mbps. On a desktop, the input comes typically from a keyboard and a mouse, whereas mobiles have small touch keyboards, voice commands, complex gestures, etc. Output is also limited on mobiles, so often they communicate with other devices to achieve their output. We are witnessing today a convergence between desktop and mobile OSes, which will gradually make desktops disappear, and computing will become increasingly more embedded. ### Challenges and opportunities This new world of mobile presents both opportunities and challenges. Users are many more, and are more diverse. They have widely differing computer skills. Developers need to focus on ease of use, internationalization, and accessibility. Platforms are more diverse (think phones, wearables, TVs, cars, e-book readers). Different vendors take different approaches to dealing with this diversity: Apple has the "walled garden" approach, while Android is more like the wild west: Android is open-source, so OEMs (original equipment manufacturers) can customize Android to their devices, so naturally Android runs on tens of thousands of models of devices today. Mobiles get interesting new kinds of inputs, from multi-touch screens, accelerometers, GPS. But they also face serious limitations in terms of screen size, processor power, and battery capacity. Mobile devices need to (and can be) managed more tightly. Today you can remote-lock a device, you can locate the device, and with software like MDM (mobile device management) you can do everything on the device remotely. Some mobile carriers even block users from installing certain apps on their devices. App stores or Play stores are digital storefronts for content consumed on device. Today, the success of a mobile platform depends heavily on its app store, which becomes a central hub for content to be consumed on that particular mobile platform. The operator of the store controls apps published in the store (e.g., disallow sexually explicit content, violence, hate speech, anything illegal), which means that the developer needs to be aware of rules and laws in the places where app will be used. Operators typically use automated tools and human reviewers to check apps for malware and terms-of-service violations. ## How does a mobile operating environment work? A mobile device aims to achieve seemingly contradictory goals: On the one hand, it aims for greater integration than a desktop, to create a more cooperative ecosystem in which to enable apps to provide services to each other. On the other hand, it aims for greater isolation, it wants to offer a stronger sandbox, to protect user data, and to restrict apps from interacting in more complex ways Each mobile OS makes its own choices for how to do this. In this lecture, we chose to focus on Android, for three reasons: * it is open-source, so it's easier to understand what it really does * over 70% of mobiles use Android, there are more than 2.5 billion Android users and more than 3 billion active Android devices, so this is very real * we will use it in the follow-on course [Software Development Project](https://dslab.epfl.ch/teaching/sweng/proj) Android is based on Linux, and things like multi-threading and low-level memory management are all provided by the Linux kernel. There is a layer, called the hardware abstraction layer (HAL), that provides standard interfaces to specific hardware capabilities, such as the camera or the Bluetooth module. Whenever an application makes a call to access device hardware, Android loads a corresponding library module from the HAL for that hardware component. Above the HAL, there is the Android runtime (ART) and the Native C/C++ libraries. The ART provides virtual machines for executing DEX (Dalvik executable) bytecode, which is specially designed to have a minimal memory footprint. Java code gets turned into DEX bytecode, which can run on the ART. Android apps can be written in Kotlin, Java, or even C++. The Android SDK (software development kit) tools compile code + resource files into a so-called Android application package (APK), which is an archive used to install the app. When publishing to the Google Play app store, one generates instead an Android app bundle (ABB), and then Google Play itself generates optimized APKs for the target device that is requesting installation of the app. This is a more practical approach than having the developer produce individual APKs for each device. Each Android app lives in its own security sandbox. In Linux terms, each app gets its own user ID. Permissions for all the files accessed by the app are set so that only the assigned user ID can access them. It is possible for apps to share data and access each other's files, in which case they get the same Linux user ID; the apps however must be from the same developer (i.e., signed with the same developer certificate). Each app runs in its own Linux process. By default, an app can access only the components that it needs to do its work and no more (this follows the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege)). An app can access the device's location, camera, Bluetooth connection, etc. as long as the phone user has explicitly granted it these permissions. Each app has its own instance of the ART, with its own VM to execute DEX bytecode. In other words, apps don't run inside a common VM. In Android, the UI is privileged. Foreground and UI threads get higher priority in CPU scheduling than the other threads. Android uses process containers (a.k.a., [Linux cgroups](https://en.wikipedia.org/wiki/Cgroups)) to allocate a higher percentage of the CPU to them. When users switch between apps, Android keeps non-foreground apps (e.g., not visible to the user) in a cache (in Linux terms, the corresponding processes do not terminate) and, if the user returns to the app, the process is reused, which makes app switching faster. Many core system components (like the ART and HAL) require native libraries written in C/C++. Android provides Java APIs to expose the functionality of these native libraries to apps. This Java APIs framework is layered on top of the ART and native C/C++ libraries. Apps written in C/C++ can use the native libraries directly (this requires the Android native development kit, or NDK). Within the Java API framework, there are a number of Android features provided through APIs written in Java that provide key building blocks for apps. For example, the View System is used for building the UI. E.g., the Resource Manager is used by apps for accessing localized strings or graphics. E.g., the Activity Manager handles the lifecycle of apps and provides a common navigation back stack (more on this below). And, as a final example, Content Providers enable apps to access data from other apps (e.g., a social media app access the Contacts app) or to share their own data. On top of this entire stack are the apps. Android comes with core apps for email, SMS, calendaring, web browsing, contacts, etc. but these apps have no special status, then can be replaced with third-party apps. The point of shipping them with Android is to provide key capabilities to other apps out of the box (e.g., allow multiple apps to have the functionality of sending an SMS without having to write the code for it). An Android app is a collection of components, with each component providing an entry point to the app. There are 4 main components: * An _Activity_ provides an entry point with a UI, for interacting with the user. An activity represents a single screen with a user interface. For example, an email app has an activity to show a list of new emails, another activity to compose an email, another activity to read emails, and so on -- activities work together to form the email app, but each one is independent of the others. Unlike in desktop software, other apps can start any one of these activities if the email app allows it, e.g., the Camera app may start the compose-email activity in order to send a picture by email. * A _Service_ is a general-purpose entry point without a UI. This essentially keeps an app running in the background (e.g., play music in the background while the user is in a different app, or fetch data over the network without blocking user interaction with an activity). A service can also be started by another component. * A _Broadcast Receiver_ enables Android to deliver events to apps out-of-band, e.g., an app may set a timer and ask Android to wakes it up at some point in the future; this way, the app need not run non-stop until then. So broadcasts can be delivered even to apps that aren't currently running. Broadcast events can be initiated by the OS (e.g., the screen turned off, battery is low, picture was taken) or can be initiated by apps (e.g., some data has been downloaded and is available for other apps to use). Broadcast receivers have no UI, but they can create a status bar notification to alert the user. * A _Content Provider_ manages data that is shared among apps. Such data can be local (e.g., file system, SQLite DB) or remote on some server. Through a content provider, apps can query / modify the data (e.g., the Contacts data is a content provider: any app with the proper permissions can get contact info and can write contact info). Remember that any app can cause another app’s component to start. For instance, if WhatsApp wants to take a photo with the camera, it can ask that an activity be started in the Camera app, without the WhatsApp developer having to write the code to take photos--when done, the photo is returned to WhatsApp, and to the user it appears as if the camera is actually a part of WhatsApp. To start a component, Android starts the process for target app (if not already running), instantiates the relevant classes (this is because, e.g., the photo-taking activity runs in the Camera process, not WhatsApp's process). You see here an example of multiple entry points: there is no `main()` like in a desktop app. Then, to activate a component in another app, you must create an _Intent_ object, which is essentially a message that activates either a specific component (explicit intent) or a type of component (implicit intent). For activities and services, the intent defines the action to perform (e.g., view or send something) and specifies the URI of the data to act on (e.g., this is an intent to dial a certain phone number). If the activity returns a result, it is returned in an Intent (e.g., let the user pick a contact and return a URI pointing to it). For broadcast receivers, the intent defines the announcement being broadcast (e.g., if battery is low it includes the BATTERY_LOW string), and a receiver can register for it by filtering on the string. Content providers are not activated by intents but rather when targeted by a request from what's called a Content Resolver, which handles all interaction with the content provider. ## A mobile app: Structure and lifecycle The centerpiece of an Android app is the _activity_. Unlike the kinds of programs you've been writing so far, there is no `main()`, but rather the underlying OS initiates code in an _Activity_ by invoking specific callback methods. An activity provides the window in which the app draws its UI. One activity essentially implements one screen in an app, e.g., 1 activity for a Preferences screen, 1 activity for a Select Photo screen, etc. Apps contain multiple screens, each of which corresponds to an activity. One activity is specified as the main activity, i.e., the first screen to appear when you launch the app. Each activity can then start another activity, e.g., the main activity in an email app may provide the screen that shows your inbox, then you have screens for opening and reasing a message, one for writing, etc. As a user navigates through, out of, back into an app, the activities in the app transition through diff states. Transitioning from one state to another is handled by specific callbacks that must be implemented in the activity. The activity learns about changes and reacts to when the user leaves and re-enters the activity: For example, a streaming video player will likely pause the video and terminate the network connection when the user switches to another app; when the user returns to the app, it will reconnect to the network and allow the user to resume the video from the same spot. To understand the lifecycle of an activity, please see [the Android documentation](https://developer.android.com/guide/components/activities/activity-lifecycle). Another important element are _fragments_. These provide a way to modularize an activity's UI and reuse modules across different activities. This provides a productive and efficient way to respond to various screen sizes, or whether your phone is in portrait or landscape mode, where the UI is composed differently but from the same modules. A fragment may show the list of emails, and another fragment may display an email thread. On a phone, you would display only one at a time, and upon tap switch to the next activity. On a tablet, with the greater screen real estate, you have room for both. By modularizing the UI into fragments, it's easy to adapt the app to the different layouts by rearranging fragments within the same view when the phone switches from portrait to landscape mode. To understand fragments, please see [the Android documentation](https://developer.android.com/guide/fragments). You don't have to use fragments within activities, but such modularization makes the app more flexible and also makes it easier to maintain over time. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. But it cannot live on its own, it needs to be hosted by an activity or another fragment. Android beginners tend to put all their logic inside Activities and Fragments, ending up with "views" that do a lot more than just render the UI. Remember what we said about MVVM and how that maps to how you build an Android app. In the exercise set, we will ask you to go through an MVVM exercise. Android provides a nice ViewModel class to store and manage UI-related data. ## User experience (UX) User experience design (or "UX design") is about putting together an intuitive, responsive, navigable, usable interface to the app. You want to look at the app through the users' perspective to derive what can give them an easy, logical and positive experience. So you must ask who is your audience: Old or young people? Intellectuals or blue-collar workers? Think back to the lecture on personas and user stories. The UI should enable the user to get around the app easily, and to find quickly what they're looking for. To achieve this, several elements and widgets have emerged from the years of experience of building mobile apps. The [hamburger icons](https://en.wikipedia.org/wiki/Hamburger_button) are used for drop-down menus with further details--they avoid clutter. Home buttons give users a shortcut to home base. Chat bubbles offer quick help through context-sensitive messages. Personalization of the UI allows adapting to what the user is interested in, keeping the unrelated content away. For example, in the [EPFL Campus app](https://pocketcampus.org/epfl-en) you can select which features you see on the home screen, and so the home screen of two different users is likely to look different. In order to maximize readability, emphasize simplicity and clarity, choose adequate font size and image size. Avoid having too many elements on the screen, because that leads to confusion. Offer one necessary action per screen. Use [micro UX animations](https://uxplanet.org/ui-design-animations-microinteractions-50753e6f605c), which are little animations that appear when a specific action is performed or a particular item is hovered or touched; this can increase engagement and interactivity. E.g., hovering over a thumbnail shows details about it. E.g., hover zoom for maximizing the view of a specific part of something. Keep however the animations minimal, avoid flashiness, make them subtle and clear as to their intent. Keep in mind _thumb zones_. People use their mobile when they’re standing, walking, riding a bus, so the app should allow them to hold the device and view its screen and provide input in all these situations. So make it easy for the user to reach with their thumb the stuff they do most often. Leverage gesture controls to make it easy for a user to interact with apps--e.g., “holding” an item, “dragging” it to a container, and then “releasing”--but beware to do what users of that device are used to doing, not exotic stuff. Think of augmented reality and voice interaction, depending on the app, they can be excellent ways to interact with the device. ## The mobile ecosystem A modern mobile app, no matter how good it is, can hardly survive without plugging into its ecosystem. Most mobile apps are consists of the phone side of the app and the cloud side. Apps interact with cloud services typically over REST APIs, which is an architectural style that builds upon HTTP and JSON to offer CRUD (copy-read-update-delete) operations on objects that are addressed by a URI. You use HTTP methods to access these resources via URL-encoded parameters. Aside from the split architecture, apps also interact with the ecosystem through Push notifications. These are automated messages sent to the user by the server of the app that’s working in the background (i.e., not currently open). Each OS (e.g., Android, iOS) has its own push notification service with a specific API that apps can use, and they each operate a push engine in the cloud. The app developer enables their app with push notifications, at which point the app can start receiving incoming notifications. When you open the app, unique IDs for both the app and the device are created by the OS and registered with the OS push notification service. IDs are passed back to the app and also sent to the app publisher. The in-cloud service generates the message (either when a publisher produces it, or in response to some event, etc.) which can be targeted at users or a group of users and gets sent to the corresponding mobile. On Android, an incoming notification can create an Activity. A controversial aspect of the ecosystem is the extent to which it track the device and the user of the device. We do not discuss this aspect here in detail, it is just something to be aware of. A key ingredient of "plugging into" the ecosystem is the network. Be aware that your users may experience different bandwidth limitations (e.g., 3G vs. 5G), and the Internet doesn't work as smoothly everywhere in the world as we're used to. In addition to bandwidth issues, there is also the risk of experiencing a noticeable disconnection from the Internet. E.g., a highly interactive, graphic-heavy app will not be appropriate for apps that target Latin America or Africa, or users in rural areas, because today there are still many areas with spotty connectivity. Perhaps a solution can be offered by the new concept of fog computing (as opposed to cloud computing), also called edge computing. It is about the many "peripheral" devices that connect to the periphery of a cloud, and many of these devices will generate lots of raw data (e.g., from sensors). Rather than forward this data to cloud-based servers, one could do as much processing as possible using computing units nearby, so that processed rather than raw data is forwarded to the cloud. As a result, bandwidth requirements are reduced. "The Fog" can support the Internet of Things (IoT), including phones, wearable health monitoring devices, connected vehicle and augmented reality devices. IoT devices are often resource-constrained and have limited computational abilities to perform, e.g., cryptography computations, so a fog node nearby can provide security for IoT devices by performing these cryptographic computations instead. ## Summary In this lecture, you learned: * Several ways in which a desktop app differs from a mobile app * How security, energy, and other requirements change when moving from a desktop to a mobile * How activities and fragments work in Android apps * The basics of good UX * How mobile apps can leverage their ecosystem You can now check out the [exercises](exercises/).
CS-305: Software engineering
# Evolution Imagine you are an architect asked add a tower to a castle. You know what towers look like, you know what castles look like, and you know how to build a tower in a castle. This will be easy! But then you get to the castle, and it looks like this: <p align="center"><img alt="Howl's Moving Castle from the movie of the same name: a messy 'castle' on legs" src="images/castle.jpg" width="50%" /></p> Sure, it's a castle, and it fulfills the same purpose most castles do, but... it's not exactly what you had in mind. It's not built like a standard castle. There's no obvious place to add a tower, and what kind of tower will this castle need anyway? Where do you make space for a tower? How do you make sure you don't break half the castle while adding it? This lecture is all about evolving an existing codebase. ## Objectives After this lecture, you should be able to: - Find your way in a _legacy codebase_ - Apply common _refactorings_ to improve code - Document and quantify _changes_ - Establish solid foundations with _versioning_ ## What is legacy code, and why should we care? "Legacy code" really means "old code that we don't like". Legacy code may or may not have documentation, tests, and bugs. If it has documentation and tests, they may or may not be complete enough; tests may even already be failing. One common reaction to legacy code is disgust: it's ugly, it's buggy, why should we even keep it? If we rewrote the code from scratch we wouldn't have to ask all of these questions about evolution! It certainly sounds enticing. In the short term, a rewrite feels good. There's no need to learn about old code, instead you can use the latest technologies and write the entire application from scratch. However, legacy code works. It has many features, has been debugged and patched many times, and users rely on the way it works. If you accidentally break something, or if you decide that some "obscure" feature is not necessary, you will anger a lot of your users, who may decide to jump ship to a competitor. One infamous rewrite story is [that of Netscape 5](https://www.joelonsoftware.com/2000/04/06/things-you-should-never-do-part-i/). In the '90s, Netscape Navigator was in tough competition with Microsoft's Internet Explorer. While IE became the butt of jokes later, at the time Microsoft was heavily invested in the browser wars. The Netscape developers decided that their existing Netscape 4 codebase was too old, too buggy, and too hard to evolve. They decided to write Netscape 5 from scratch. The result is that it took them three years to ship the next version of Netscape; in that time, Microsoft had evolved their existing IE codebase, far outpacing Netscape 4, and Netscape went bankrupt. Most rewrites, like Netscape, fail. A rewrite means a loss of experience, a repeat of many previous mistakes, and that's just to get to the same point as the previous codebase. There then needs to be time to add features that justify the cost of upgrading to users. Most rewrites run out of time or money and fail. It's not even clear what "a bug" is in legacy code, which is one reason rewrites are dangerous: some users depend on things that might be considered "bugs". For instance, Microsoft Excel [treats 1900 as a leap year](https://learn.microsoft.com/en-us/office/troubleshoot/excel/wrongly-assumes-1900-is-leap-year) even though it is not, because back when it was released it had to compete with a product named Lotus 1-2-3 that did have this bug. Fixing the bug means many spreadsheets would stop working correctly, as dates would become off by one. Thus, even nowadays, Microsoft Excel still contains a decades-old "bug" in the name of compatibility. A better reaction to legacy code is to _take ownership of it_: if you are assigned to a legacy codebase, it is now your code, and you should treat it just like any other code you are responsible for. If the code is ugly, it is your responsibility to fix it. ## How can we improve legacy code? External improvements to an existing codebase, such as adding new features, fixing bugs, or improving performance, frequently require internal improvements to the code first. Some features may be difficult to implement in an existing location, but could be much easier if the code was improved first. This may require changing design _tradeoffs_, addressing _technical debt_, and _refactoring_ the codebase. Let's see each of these in detail. ### Tradeoffs Software engineers make tradeoffs all the time when writing software, such as choosing an implementation that is faster at the cost of using more memory, or simpler to implement at the cost of being slower, or more reliable at the cost of more disk space. As code ages, its context changes, and old tradeoffs may no longer make sense. For instance, Windows XP, released in 2001, groups background services into a small handful of processes. If any background service crashes, it will cause all of the services in the same process to also crash. However, because there are few processes, this minimizes resource use. It would have been too much in 2001, on computers with as little as 64 MB of RAM, to dedicate one process and the associated overheads per background service. But in 2015, when Windows 10 was released, computers typically had well over 2 GB of RAM. Trading reliability for low resource use no longer made sense, so Windows 10 instead runs each background service in its own process. The cost of memory is tiny on the computers Windows 10 is made for, and the benefits from not crashing entire groups of services at a time are well worth it. The same choice made 15 years apart yielded a different decision. ### Technical debt The cost of all of the "cheap" and "quick" fixes done to a codebase making it progressively worse is named _technical debt_. Adding one piece of code that breaks modularity and hacks around the code's internals may be fine to meet a deadline, but after a few dozen such hacks, the code becomes hard to maintain. The concept is similar to monetary debt: it can make sense to invest more money than you have, so you borrow money and slowly pay it back. But if you don't regularly pay back at least the interest, your debt grows and grows, and so does the share of your budget you must spend on repaying your debt. You eventually go bankrupt from the debt payments taking up your entire budget. With technical debt, a task that should take hours can take a week instead, because one now needs to update the code in the multiple places where it has been copy-pasted for "hacks", fix some unrelated code that in practice depends on the specific internals of the code to change, write complex tests that must set up way more than they should need, and so on. You may no longer be able to use the latest library that would solve your problem in an hour, because your codebase is too old and depends on old technology the library is not compatible with, so instead you need weeks to reimplement that functionality yourself. You may regularly need to manually reimplement security patches done to the platform you use because you use an old version that is no longer maintained. This is one reason why standards are useful: using a standard version of a component means you can easily service it. If you instead have a custom component, maintenance becomes much more difficult, even if the component is nicer to work with at the beginning. ### Refactoring Refactoring is the process of making _incremental_ and _internal_ improvements. These are improvements designed to make code easier to maintain, but that do not directly affect end users. Refactoring is about starting from a well-known code problem, applying a well-known solution, and ending up with better code. The well-known problems are sometimes called "code smells", because they're like a strange smell: not harmful on its own, but worrying, and could lead to problems if left unchecked. For instance, consider the following code: ```java class Player { int hitPoints; String weaponName; int weaponDamage; boolean isWeaponRanged; } ``` Something doesn't smell right. Why does a `Player` have all of the attributes of its weapon? As it is, the code works, but what if you need to handle weapons independently of players, say, to buy and sell weapons at shops? Now you will need fake "players" that exist just for their weapons. You'll need to write code that hides these players from view. Future code that deals with players may not handle those "fake players" correctly, introducing bugs. Pay some of your technical debt and fix this with a refactoring: extract a class. ```java class Player { int hitPoints; Weapon weapon; } class Weapon { ... } ``` Much better. Now you can deal with weapons independently of players. Your `Weapon` class now looks something like this: ```java class Weapon { boolean isRanged; void attack() { if (isRanged) { ... } else { ... } } } ``` This doesn't smell right either. Every method on `Weapon` will have to first check if it is ranged or not, and some developers might forget to do that. Refactor it: use polymorphism. ```java abstract class Weapon { abstract void attack(); } class MeleeWeapon extends Weapon { ... } class RangedWeapon extends Weapon { ... } ``` Better. But then you look at the damage calculation... ```java int damage() { return level * attack - max(0, armor - 500) * attack / 20 + min(weakness * level / 10, 400); } ``` What is this even doing? It's hard to tell what was intended and whether there's any bug in there, let alone to extend it. Refactor it: extract variables. ```java int damage() { int base = level * attack; int resistance = max(0, armor - 500) * attack / 20; int bonus = min(weakness * level / 10, 400); return base - resistance + bonus; } ``` This does the same thing, but now you can tell what it is: there's one component for damage that scales with the level, one component for taking the resistance into account, and one component for bonus damage. You do not have to do these refactorings by hand; any IDE contains tools to perform refactorings such as extracting an expression into a variable or renaming a method. --- #### Exercise Take a look at the [gilded-rose/](exercises/lecture/gilded-rose) exercise folder. The code is obviously quite messy. First, try figuring out what the code is trying to do, and what problems it has. Then, write down what refactorings you would make to improve the code. You don't have to actually do the refactorings, only to list them, though you can do them for more practice. <details> <summary>Proposed solution (click to expand)</summary> <p> The code tries to model the quality of items over time. But it has so many special cases and so much copy-pasted code that it's hard to tell. Some possible refactorings: - Turn the `for (int i = 0; i < items.length; i++)` loop into a simpler `for (Item item : items)` loop - Simplify `item.quality = item.quality - item.quality` into the equivalent but clearer `item.quality = 0` - Extract `if (item.quality < 50) item.quality = item.quality + 1;` into a method `incrementQuality` on `Item`, which can thus encapsulate this cap at 50 - Extract numbers such as `50` into named constants such as `MAX_QUALITY` - Extract repeated checks such as those on the item names into methods on `Item` such as `isPerishable`, and maybe create subclasses of `Item` instead of checking names </p> </details> ## Where to start in a large codebase? Refactorings are useful for specific parts of code, but where to even start if you are given a codebase of millions of lines of code and told to fix a bug? There may not be documentation, and if there is it may not be accurate. A naïve strategy is to "move fast and break things", as [was once Facebook's motto](https://www.businessinsider.com/mark-zuckerberg-on-facebooks-new-motto-2014-5). The advantage is that you move fast, but... the disadvantage is that you break things. The latter tends to massively outweigh the former in any large codebase with many users. Making changes you don't fully understand is a recipe for disaster in most cases. An optimistic strategy, often taken by beginners, is to understand _everything_ about the code. Spend days and weeks reading every part of the codebase. Watch video tutorials about every library the code uses. This is not useful either, because it takes far too long, and because it will in fact never finish since others are likely making changes to the code while you learn. Furthermore, by the time you have read half the codebase, you won't remember what exactly the first part you looked at was, and your time will have been wasted. Let's see three components of a more realistic strategy: learning as you go, using an IDE, and taking notes. ### Learning as you go Think of how detectives such as [Sherlock Holmes](https://en.wikipedia.org/wiki/Sherlock_Holmes) or [Miss Marple](https://en.wikipedia.org/wiki/Miss_Marple) solve a case. They need information about the victim, what happened, and any possible suspects, because that is how they will find out who did it. But they do not start by asking every person around for their entire life story from birth to present. They do not investigate the full history of every item found at the scene of the crime. While the information they need is somewhere in there, getting it by enumerating all information would take too much time. Instead, detectives only learn what they need when they need it. If they find evidence that looks related, they ask about that evidence. If somebody's behavior is suspect, they look into that person's general history, and if something looks related, they dig deeper for just that detail. This is what you should do as well in a large codebase. Learn as you go: only learn what you need when you need it. ### Using an IDE You do not have to manually read through files to find out which class is used where, or which modules call which function. IDEs have built-in features to do this for you, and those features get better if the language you're using is statically typed. Want to find who uses a method? Right click on the method's name, and you should find some tool such as "find all references". Do you realize the method is poorly named given how the callers use it? Refactor its name using your IDE, don't manually rename every use. One key feature of IDEs that will help you is the _debugger_. Find the program's "main" function, the one called at the very beginning, and put a breakpoint on its first statement. Run the program with the debugger, and you're ready to start your investigation by following along with the program's flow. Want to know more about a function call? Step into it. Think that call is not relevant right now? Step over it instead. ### Taking notes You cannot hope to remember all context about every part of a large codebase by heart. Instead, take notes as you go, at first for yourself. You may later turn these notes into documentation. One formal way to take notes is to write _regression tests_. You do not know what behavior the program should have, but you do know that it works and you do not want to break it. Thus, write a test without assertions, run the test under the debugger, and look at the code's behavior. Then, add assertions to the test for the current behavior. This serves both as notes for yourself of what happens when the code is used in a specific way, and as an automated way to check if you broke something while modifying the code later. Another formal way to take notes is to write _facades_. "Facade" is a design pattern intended to simplify and modularize existing code by hiding complex parts behind simpler facades. For instance, let's say you are working in a codebase that only provides a very generic "draw" method that takes a lot of arguments, but you only need to draw rectangles: ```java var points = new Point[] { new Point(0, 0), new Point(x, 0), new Point(x, y), new Point(0, y) }; draw(points, true, false, Color.RED, null, new Logger(), ...); ``` This is hard to read and maintain, so write a facade for it: ```java drawRectangle(0, 0, x, y, Color.RED); ``` Then implement the `drawRectangle` method in terms of the complex `draw` method. The behavior hasn't changed, but the code is easier to read. Now, you only need to look at the complex part of the code if you actually need to add functionality related to it. Reading the code that needs to draw rectangles no longer requires knowledge of the complex drawing function. --- #### Exercise Take a look at the [pacman/](exercises/lecture/pacman) exercise folder. It's a cool "Pac-Man" game written in Java, with a graphical user interface. It's fun! Imagine you were asked to maintain it and add features. You've never read its code before. so where to start? First, look at the code, and take some notes: which classes exist, and what do they do? Then, use a debugger to inspect the code's flow, as described above. If someone asked you to extend this game to add a new kind of ghost, with a different color and behavior, which parts of the code would you need to change? Finally, what changes could you make to the code to make it easier to add more kinds of ghosts? <details> <summary>Proposed solution (click to expand)</summary> <p> To add a kind of ghost, you'd need to add a value to the `ghostType` enum, and a class extending `Ghost`. You would then need to add parsing logic in `MapEditor` for your ghost, and to link the enum and class together in `PacBoard`. To make the addition of more ghosts easier, you could start by re-formatting the code to your desired standard, and changing names to be more uniform, such as the casing of `ghostType`. One task would be to have a single object to represent ghosts, instead of having both `ghostType` and `Ghost`. It would also probably make sense to split the parsing logic from `MapEditor`, since editing and parsing are not the same job. Remember, you might look at this Pac-Man game code thinking it's not as nice as some idealized code that could exist, but unlike the idealized code, this one does exist already, and it works. Put energy into improving the code rather than complaining about it. </p> </details> --- Remember the rule typically used by scouts: leave the campground cleaner than you found it. In your case, the campground is code. Even small improvements can pay off with time, just like monetary investments. If you improve a codebase by 1% every day, after 365 days, it will be around 38x better than you started. But if you let it deteriorate by 1% instead, it will be only 0.03x as good. ## How should we document changes? You've made some changes to legacy code, such as refactorings and bug fixes. Now how do you document this? The situation you want to avoid is to provide no documentation, lose all knowledge you gained while making these changes, and need to figure it all out again. This could happen to yourself or to someone else. Let's see three kinds of documentation you may want to write: for yourself, for code reviewers, and for maintainers. ### Documenting for yourself The best way to check and improve your understanding of a legacy codebase is to teach others about it, which you can do by writing comments and documentation. This is a kind of "refactoring": you improve the code's maintainability by writing the comments and documentation that good code should have. For instance, let's say you find the following line in a method somewhere without any explanation: ```java if (i > 127) i = 127; ``` After spending some time on it, such as commenting it out to see what happens, you realize that this value is eventually sent to a server which refuses values above 127. You can document this fact by adding a comment, such as `// The server refuses values above 127`. You now understand the code better. Then you find the following method: ```java int indexOfSpace(String text) { ... } ``` You think you understand what this does, but when running the code, you realize it not only finds spaces but also tabs. After some investigation, it turns out this was a bug that is now a specific behavior on which clients depend, so you must keep it. You can thus add some documentation: `Also finds tabs. Clients depend on this buggy behavior`. You now understand the code better, and you won't be bitten by this issue again. ### Documenting for code reviewers You submit a pull request to a legacy codebase. Your changes touch code that your colleagues aren't quite familiar with either. How do you save your colleagues some time? You don't want them to have to understand exactly what is going on before being able to review your change, yet if you only give them code, this is what will happen. First, your pull request should have a _description_, in which you explain what you are changing and why. This description can be as long as necessary, and can include remarks such as whether this is a refactoring-only change or a change in behavior, or why you had to change some code that intuitively looks like it should not need changes. Second, the commits themselves can help reviewing if you split your work correctly, or if you rewrite the history once you are done with the work. For instance, your change may involve a refactoring and a bug fix, because the refactoring makes the bug fix cleaner. If you submit the change as a single commit, reviewers will need time and energy to read and understand the entire change at once. If a reviewer is interrupted in the middle of understanding that commit, they will have to start from scratch after the interruption. Instead of one big commit, you can submit a pull request consisting of one commit per logical task in the request. For instance, you can have one commit for a refactoring, and one for a bug fix. This is easier to review, because they can be reviewed independently. This is particularly important for large changes: the time spent reviewing a commit is not linear in the length of the commit, but closer to exponential, because we humans have limited brain space and usually do not have large chunks of uninterrupted time whenever we'd like. Instead of spending an hour reviewing 300 modified lines of code, it's easier to spend 10 times 3 minutes reviewing commits of 30 lines at a time. This also lessens the effects of being interrupted during a review. ### Documenting for maintainers We've talked about documentation for individual bits of code, but future maintainers need more than that to understand a codebase. Design decisions must be documented too: what did you choose and why? Even if you plan on maintaining a project yourself for a long time, this saves some work: your future colleagues could each take 5 minutes of your time asking you the same question about some design decision taken long ago, or you could spend 10 minutes once documenting it in writing. At the level of commits, this can be done in a commit message, so that future maintainers can use tools such as [git blame](https://git-scm.com/docs/git-blame) to find the commit that last changed a line of code and understand why it is that way. At the level of modules or entire projects, this can be done with _Architectural Decision Records_. As their name implies, these are all about recording decisions made regarding the architecture of a project: the context, the decision, and its consequences. The goal of ADRs is for future maintainers to know not only what choices were made but also why, so that maintainers can make an informed decision on whether to make changes. For instance, knowing that a specific library for user interfaces was chosen because of its excellent accessibility features informs maintainers that even if they do not like the library's API, they should pay particular attention to accessibility in any potential replacement. Perhaps the choice was made at a time when alternatives had poor accessibility, and the maintainers can change that choice because in their time there are alternatives that also have great accessibility features. The context includes user requirements, deadlines, compatibility with previous systems, or any other piece of information that is useful to know to understand the decision. For instance, in the context of lecture notes for a course, the context could include "We must provide lecture notes, as student feedback tells us they are very useful" and "We want to allow contributions from students, so that they can easily help if they find typos or mistakes". The decision includes the alternatives that were considered, the arguments for and against each of them, and the reasons for the final choice. For instance, still in the same context, the alternatives might be "PDF files", "documents on Google Drive", and "documents on a Git repository". The arguments could then include "PDF files are convenient to read on any device, but they make it hard to contribute". The final choice might then be "We chose documents on a Git repository because of the ease of collaboration and review, and because GitHub provides a nice preview of Markdown files online". The consequences are the list of tasks and changes that must be done in the short-to-medium term. This is necessary to apply the decision, even if it may not be useful in the long term. For instance, one person might be tasked with converting existing lecture notes to Markdown, and another might be tasked to create an organization and a repository on GitHub. It is important to keep ADRs _close to the code_, such as in the same repository, or in the same organization on a platform like GitHub. If ADRs are in some unrelated location that only current maintainers know about, they will be of no use to future maintainers. ## How can we quantify changes? Making changes is not only about describing them qualitatively, but also about telling people who use the software whether the changes will affect them or not. For instance, if you publish a release that removes a function from your library, people who used that function cannot use this new release immediately. They need to change their code to no longer use the function you removed, which might be easy if you provided a replacement, or might require large changes if you did not. And if the people using your library cannot or do not want to update their software, for instance because they have lost the source code, they now have to rewrite their software. Let's talk _compatibility_, and specifically three different axes: theory vs practice, forward vs backward, and source vs binary. ### Theory vs practice In theory, any change could be an "incompatible" change. Someone could have copied your code or binary somewhere, and start their program by checking that yours is still the exact same one. Any change would make this check fail. Someone could depend on the exact precision of some computation whose precision is not documented, and then [fail](https://twitter.com/stephentyrone/status/1425815576795099138) when the computation is made more precise. In practice, we will ignore the theoretical feasibility of detecting changes and choose to be "reasonable" instead. What "reasonable" is can depend on the context, such as Microsoft Windows having to provide compatibility modes for all kinds of old software which did questionable things. Microsoft must do this because one of the key features they provide is compatibility, and customers might move to other operating systems otherwise. Most engineers do not have such strict compatibility requirements. ### Forward vs backward A software release is _forward compatible_ if clients for the next release can also use it without needing changes. This is also known as "upward compatibility". That is, if a client works on version N+1, forward compatibility means it should also work on version N. Forward compatibility means that you cannot ever add new features or make changes that break behavior, since a client using those new features could not work on the previous version that did not have these features. It is rare in practice to offer forward compatibility, since the only changes allowed are performance improvements and bug fixes. A software release is _backward-compatible_ if clients for the previous release can also use it without needing changes. That is, if a client works on version N-1, backward compatibility means it should also work on version N. Backward compatibility is the most common form of compatibility and corresponds to the intuitive notion of "don’t break things". If something works, it should continue working. For instance, if you upgrade your operating systems, your applications should still work. Backward compatibility typically comes with a set of "supported" scenarios, such as a public API. It is important to define what is supported when defining compatibility, since otherwise some clients could misunderstand what is and is not supported, and their code could break even though you intended to maintain backward compatibility. For instance, old operating systems did not have memory protection: any program could read and write any memory, including the operating system's. This was not something programs should have been doing, but they could. When updating to a newer OS with memory protection, this no longer worked, but it was not considered breaking backward compatibility since it was never a feature in the first place, only a limitation of the OS. One extreme example of providing backward compatibility is Microsoft's [App Assure](https://www.microsoft.com/en-us/fasttrack/microsoft-365/app-assure): if a company has a program that used to work and no longer works after upgrading Windows, Microsoft will fix it, for free. This kind of guarantee is what allowed Microsoft to dominate in the corporate world; no one wants to have to frequently rewrite their programs, no matter how much "better" or "nicer" the new technologies are. If something works, it works. ### Source vs binary Source compatibility is about whether your customers' source code still compiles against a different version of your code. Binary compatibility is about whether your customers’ binaries still link with a different version of your binary. These are orthogonal to behavioral compatibility; code may still compile and link against your code even though the behavior at run-time has changed. Binary compatibility can be defined in terms of "ABI", "Application Binary Interface", just like "API" for source code. The ABI defines how components call each other, such as method signatures: method names, return types, parameter types, and so on. The exact compatibility requirements differ due to the ABI of various languages and platforms. For instance, parameter names are not a part of Java's ABI, and thus can be changed without breaking binary compatibility. In fact, parameter names are not a part of Java's API either, and can thus also be changed without breaking source compatibility. An interesting example of preserving source but not binary compatibility is C#'s optional parameters. A definition such as `void Run(int a, int b = 0)` means the parameter `b` is optional with a default value of `0`. However, this is purely source-based; writing `Run(a)` is translated by the compiler as if one had written `Run(a, 0)`. This means that evolving the method from `void Run(int a)` to `void Run(int a, int b = 0)` is compatible at the source level, because the compiler will implicitly add the new parameter to all existing calls, but not at the binary level, because the method signature changed so existing binaries will not find the one they expect. An example of the opposite is Java's generic type parameters, due to type erasure. Changing a class from `Widget<X>` to `Widget<X, Y>` is incompatible at the source level, since the second type parameter must now be added to all existing uses by hand. It is however compatible at the binary level, because generic parameters in Java are erased during compilation. If the second generic parameter is not otherwise used, binaries will not even know it exists. --- #### Exercise Which of these preserves backward compatibility? - Add a new class - Make a return type _less_ specific (e.g., from `String` to `Object`) - Make a return type _more_ specific (e.g., from `Object` to `String`) - Add a new parameter to a function - Make a parameter type _less_ specific - Make a parameter type _more_ specific <details> <summary>Proposed solution (click to expand)</summary> <p> - Adding a new class is binary compatible, since no previous version could have referred to it. It is generally considered to be source compatible, except for the annoying scenario in which someone used wildcard imports (e.g., `import org.example.*`) for two modules in the same file, and your new class has the same name as another class in another module, at which point the compiler will complain of an ambiguity. - Making a return type less specific is not backward compatible. The signature changes, so binary compatibility is already broken, and calling code must be modified to be able to deal with more kinds of values, so source compatibility is also broken. - Making a return type more specific is source compatible, since code that dealt with the return type can definitely deal with a method that happens to always return a more specific type. However, since the signature changes, it is not binary compatible. - Adding a parameter is neither binary nor source compatible, since the signature changes and code must now be modified to pass an additional argument whenever the function is called. - Making a parameter type less specific is source compatible, since a function that accepts a general type of parameter can be used by always giving a more specific type. However, since the signature changes, it is not binary compatible. - Making a parameter type more specific is not backward compatible. The signature changes, so binary compatibility is already broken, and calling code must be modified to always pass a more specific type for arguments, so source compatibility is also broken. </p> </details> --- What compatibility guarantees should you provide, then? This depends on who your customers are, and asking them is a good first step. Avoid over-promising; the effort required to maintain very strict compatibility may be more than the benefits you get from the one or two specific customers who need this much compatibility. Most of your customers are likely to be "reasonable". Backward compatibility is the main guarantee people expect in practice, even if they do not say so explicitly. Breaking things that work is viewed poorly. However, making a scenario that previously had a "failure" result, such as throwing an exception, return a "success” result instead is typically OK. Customers typically do not depend on things _not_ working. ## How can we establish solid foundations? You are asked to run an old Python script that a coworker wrote ages ago. The script begins with `import simplejson`, and then proceeds to use the `simplejson` library. You download the library, run the script... and you get a `NameError: name 'scanstring' is not defined`. Unfortunately, because the script did not specify what _version_ of the library it expected, you now have to figure it out by trial and error. For crashes such as missing functions, this can be done relatively quickly by going through versions in a binary search. However, it is also possible that your script will silently give a wrong result with some versions of the library. For instance, perhaps the script depends on a bug fix made at a specific time, and running the script with a version of the library older than that will give a result that is incorrect but not obviously so. Versions are specific, tested, and named releases. For instance, "Windows 11" is a version, and so is "simplejson 3.17.6". Versions can be more or less specific; for instance, "Windows 11" is a general product name with a set of features, and some more minor features were added in updates such as "Windows 11 22H2". Typical components of a version include a major and a minor version number, sometimes followed by a patch number and a build number; a name or sometimes a codename; a date of release; and possibly even other information. In typical usage, changing the major version number is for big changes and new features, changing the minor version number is for small changes and fixes, and changing the rest such as the patch version number is for small fixes that may not be noticeable to most users, as well as security patches. Versioning schemes can be more formal, such as [Semantic Versioning](https://semver.org/), a commonly used format in which versions have three main components: `Major.Minor.Patch`. Incrementing the major version number is for changes that break compatibility, the minor version number is for changes that add features while remaining compatible, and the patch number is for compatible changes that do not add features. As already stated, remember that the definition of "compatible" changes is not objective. Some people may consider a change to break compatibility even if others think it is compatible. Let's see three ways in which you will use versions: publishing versioned releases, _deprecating_ public APIs if truly necessary, and consuming versions of your dependencies. ### Versioning your releases If you allowed customers to download your source code and compile it whenever they want, it would be difficult to track who is using what, and any bug report would start with a long and arduous process of figuring out exactly which version of the code is in use. Instead, if a customer states they are using version 5.4.1 of your product and encounter a specific bug, you can immediately know which code this corresponds to. Providing specific versions to customers means providing specific guarantees, such as "version X of our product is compatible with versions Y and Z of the operating system", or "version X of our product will be supported for 10 years with security patches". You do not have to maintain a single version at a time; products routinely have multiple versions under active support, such as [Java SE](https://www.oracle.com/java/technologies/java-se-support-roadmap.html). In practice, versions are typically different branches in a repository. If a change is made to the "main" branch, you can then decide whether it should be ported to some of the other branches. Security fixes are a good example of changes that should be ported to all versions that are still supported. ### Deprecating public APIs Sometimes you realize your codebase contains some very bad mistakes that lead to problems, and you'd like to correct them in a way that technically breaks compatibility but still leads to a reasonable experience for your customers. That is what _deprecation_ is for. By declaring that a part of your public surface is deprecated, you are telling customers that they should stop using it, and that you may even remove it in a future version. Deprecation should be reserved for cases that are truly problematic, not just annoying. For instance, if the guarantees provided by a specific method force your entire codebase to use a suboptimal design that makes everything else slower, it may be worth removing the method. Another good example is methods that accidentally make it very easy to introduce bugs or security vulnerabilities due to subtleties in their semantics. For instance, Java's `Thread::checkAccess` method was deprecated in Java 17, because it depends on the Java Security Manager, which very few people use in practice and which constrains the evolution of the Java platform, as [JEP 411 states](https://openjdk.org/jeps/411). Here is an example of a less reasonable deprecation from Python: ``` >>> from collections import Iterable DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working ``` Sure, having classes in the "wrong" module is not great, but the cost of maintaining backward compatibility is low. Breaking all code that expects the "Abstract Base Collections" to be in the "wrong" module is likely more trouble than it's worth. Deprecating in practice means thinking about whether the cost is worth the risk, and if it is, using your language's way of deprecating, such as `@Deprecated(...)` in Java or `[Obsolete(...)]` in C#. ### Consuming versions Using specific versions of your dependencies allows you to have a "known good" environment that you can use as a solid base to work. You can update dependencies as needed, using version numbers as a hint for what kind of changes to expect. This does not mean you should 100% trust all dependencies to follow compatibility guidelines such as semantic versioning. Even those who try to follow such guidelines can make mistakes, and updating a dependency from 1.3.4 to 1.3.5 could break your code due to such a mistake. But at least you know that your code worked with 1.3.4 and you can go back to it if needed. The worst-case scenario, which is unfortunately common with old code, is when you cannot build a codebase anymore because it does not work with the latest versions of its dependencies and you do not know which versions it expects. You then have to spend lots of time figuring out which versions work and do not work, and writing them down so future you does not have to do it all over again. In practice, in order to manage dependencies, software engineers use package managers, such as Gradle for Java, which manage dependencies given versions: ``` testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' ``` This makes it easy to get the right dependency given its name and version, without having to manually find it online. It's also easy to update dependencies; package managers can even tell you whether there is any newer version available. You should however be careful of "wildcard" versions: ``` testImplementation 'org.junit.jupiter:junit-jupiter-api:5.+' ``` Not only can such a version cause your code to break because it will silently use a newer version when one is available, which could contain some bug that breaks your code, but you will have to spend time figuring out which version you were previously using, since it is not written down. For big dependencies such as operating systems, one way to easily save the entire environment as one big "version" is to use a virtual machine or container. Once it is built, you know it works, and you can distribute your software on that virtual machine or container. This is particularly useful for software that needs to be exactly preserved for long periods of time, such as scientific artifacts. ## Summary In this lecture, you learned: - Evolving legacy code: goals, refactorings, and documentation - Dealing with large codebases: learning as you go, improving the code incrementally - Quantifying and describing changes: compatibility and versioning You can now check out the [exercises](exercises/)!
CS-305: Software engineering
**Russell Epstein** Russell Epstein: Russell Epstein is a professor of psychology at the University of Pennsylvania, who studies neural mechanisms underlying visual scene perception, event perception, object recognition, and spatial navigation in humans. His lab studies the role of the Parahippocampal and retrosplenial cortices in determining how people orient themselves relative to their surroundings. Education: Epstein received an undergraduate degree in physics at the University of Chicago and a Ph.D. in computer vision with Alan Yuille at Harvard.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Ambient device** Ambient device: Ambient devices are a type of consumer electronics, characterized by their ability to be perceived at-a-glance, also known as "glanceable". Ambient devices use pre-attentive processing to display information and are aimed at minimizing mental effort. Associated fields include ubiquitous computing and calm technology. The concept is closely related to the Internet of Things.The New York Times Magazine announced ambient devices as one of its Ideas of the Year in 2002. The award recognized a start-up company, Ambient Devices, whose first product Ambient Orb, was a frosted-glass ball lamp, which maps information to a linear color spectrum and displays the trend in the data. Other products in the genre include the 2008 Chumby, and the 2012 52-LED device MooresCloud (a reference to Moore's Law) from Australia.Research on ambient devices began at Xerox Parc, with a paper co-written by Mark Weiser and John Seely Brown, entitled Calm Computing. Purpose: The purpose of ambient devices is to enable immediate and effortless access to information. The original developers of the idea state that an ambient device is designed to provide support to people carrying out everyday activities. Ambient devices decrease the effort needed to process incoming data, thus rendering individuals more productive.The key issue lies with taking Internet-based content (e.g. traffic congestion, weather condition, stock market quotes) and mapping it into a single, usually one-dimensional spectrum (e.g. angle, colour). According to Rose, this presents data to an end user seamlessly, with an insignificant amount of cognitive load. History: The concept of ambient devices can be traced back to the early 2000s, when preliminary research was carried at Xerox PARC, according to the company’s official website. The MIT Media Lab website lists the venture as founded by David L. Rose, Ben Resner, Nabeel Hyatt and Pritesh Gandhi as a lab spin-off. Examples: Ambient Orb was introduced by Ambient Devices in 2002. The device was a glowing sphere that displayed data through changes in color. Ambient Orb was customizable in terms of content and its subsequent visual representation. For instance, when the device was set to monitor a stock market index (e.g. NASDAQ), the Orb glowed green/red to represent the upward/downward price movements; alternatively, it turned amber when the index is unchanged. Nabeel Hyatt stated that the device was marketed as an interior design item with additional functionality. Examples: Another prominent ambient device is Chumby, released in 2008. It served as an at-a-glance widget station. Chumby was able to push relevant customizable data (weather, news, music, photos) to a touchscreen through Wi-Fi. It greatly surpassed the products resembling Ambient Orb, in terms of functionality, and was proclaimed one of the top gadgets of 2008, production ceased in April 2012. Since 1 July 2014 Chumby is available only as a paid subscription service.More recent products such as Amazon Alexa can be seen as adopting the spirit of ambient devices, in that they operate in the background, responding to both users and external data sources.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Electron excitation** Electron excitation: Electron excitation is the transfer of a bound electron to a more energetic, but still bound state. This can be done by photoexcitation (PE), where the electron absorbs a photon and gains all its energy or by collisional excitation (CE), where the electron receives energy from a collision with another, energetic electron. Within a semiconductor crystal lattice, thermal excitation is a process where lattice vibrations provide enough energy to transfer electrons to a higher energy band such as a more energetic sublevel or energy level. When an excited electron falls back to a state of lower energy, it undergoes electron relaxation (deexcitation). This is accompanied by the emission of a photon (radiative relaxation/spontaneous emission) or by a transfer of energy to another particle. The energy released is equal to the difference in energy levels between the electron energy states.In general, the excitation of electrons in atoms strongly varies from excitation in solids, due to the different nature of the electronic levels and the structural properties of some solids. The electronic excitation (or deexcitation) can take place by several processes such as: collision with more energetic electrons (Auger recombination, impact ionization, ...) absorption / emission of a photon, absorption of several photons (so called multiphoton ionization); e.g., quasi-monochromatic laser light.There are several rules that dictate the transition of an electron to an excited state, known as selection rules. First, as previously noted, the electron must absorb an amount of energy equivalent to the energy difference between the electron's current energy level and an unoccupied, higher energy level in order to be promoted to that energy level. The next rule follows from the Frank-Condon Principle, which states that the absorption of a photon by an electron and the subsequent jump in energy levels is near-instantaneous. The atomic nucleus with which the electron is associated cannot adjust to the change in electron position on the same time scale as the electron (because nuclei are much heavier), and thus the nucleus may be brought into a vibrational state in response to the electron transition. Then, the rule is that the amount of energy absorbed by an electron may allow for the electron to be promoted from a vibrational and electronic ground state to a vibrational and electronic excited state. A third rule is the Laporte Rule, which necessitates that the two energy states between which an electron transitions must have different symmetry. A fourth rule is that when an electron undergoes a transition, the spin state of the molecule/atom that contains the electron must be conserved.Under some circumstances, certain selection rules may be broken and excited electrons may make "forbidden" transitions. The spectral lines associated with such transitions are known as forbidden lines. Electron excitation in solids: Ground state preparation The energy and momentum of electrons in solids can be described by introducing Bloch waves into the Schrödinger equation with applying periodic boundary conditions. Solving this eigenvalue equation, one obtains sets of solutions that are describing bands of energies that are allowed to the electrons: the electronic band structure. The latter page contains a summary of the techniques that are nowadays available for modeling the properties of solid crystals at equilibrium, i.e., when they are not illuminated by light. Electron excitation in solids: Electron excitation by light: polariton The behavior of electrons excited by photons can be described by the quasi-particle named "polariton". A number of methods exist to describe these, both using classical and quantum electrodynamics. One of the methods is to use the concept of dressed particle.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Addition chain** Addition chain: In mathematics, an addition chain for computing a positive integer n can be given by a sequence of natural numbers starting with 1 and ending with n, such that each number in the sequence is the sum of two previous numbers. The length of an addition chain is the number of sums needed to express all its numbers, which is one less than the cardinality of the sequence of numbers. Examples: As an example: (1,2,3,6,12,24,30,31) is an addition chain for 31 of length 7, since 2 = 1 + 1 3 = 2 + 1 6 = 3 + 3 12 = 6 + 6 24 = 12 + 12 30 = 24 + 6 31 = 30 + 1Addition chains can be used for addition-chain exponentiation. This method allows exponentiation with integer exponents to be performed using a number of multiplications equal to the length of an addition chain for the exponent. For instance, the addition chain for 31 leads to a method for computing the 31st power of any number n using only seven multiplications, instead of the 30 multiplications that one would get from repeated multiplication, and eight multiplications with exponentiation by squaring: n2 = n × n n3 = n2 × n n6 = n3 × n3 n12 = n6 × n6 n24 = n12 × n12 n30 = n24 × n6 n31 = n30 × n Methods for computing addition chains: Calculating an addition chain of minimal length is not easy; a generalized version of the problem, in which one must find a chain that simultaneously forms each of a sequence of values, is NP-complete. There is no known algorithm which can calculate a minimal addition chain for a given number with any guarantees of reasonable timing or small memory usage. However, several techniques are known to calculate relatively short chains that are not always optimal.One very well known technique to calculate relatively short addition chains is the binary method, similar to exponentiation by squaring. In this method, an addition chain for the number n is obtained recursively, from an addition chain for n′=⌊n/2⌋ . If n is even, it can be obtained in a single additional sum, as n=n′+n′ . If n is odd, this method uses two sums to obtain it, by computing n−1=n′+n′ and then adding one.The factor method for finding addition chains is based on the prime factorization of the number n to be represented. If n has a number p as one of its prime factors, then an addition chain for n can be obtained by starting with a chain for n/p , and then concatenating onto it a chain for p , modified by multiplying each of its numbers by n/p . The ideas of the factor method and binary method can be combined into Brauer's m-ary method by choosing any number m (regardless of whether it divides n ), recursively constructing a chain for ⌊n/m⌋ , concatenating a chain for m (modified in the same way as above) to obtain m⌊n/m⌋ , and then adding the remainder. Additional refinements of these ideas lead to a family of methods called sliding window methods. Chain length: Let l(n) denote the smallest s so that there exists an addition chain of length s which computes n It is known that log log 2.13 log log log log 2⁡(n)) ,where ν(n) is the Hamming weight (the number of ones) of the binary expansion of n .One can obtain an addition chain for 2n from an addition chain for n by including one additional sum 2n=n+n , from which follows the inequality l(2n)≤l(n)+1 on the lengths of the chains for n and 2n . However, this is not always an equality, as in some cases 2n may have a shorter chain than the one obtained in this way. For instance, 382 191 11 , observed by Knuth. It is even possible for 2n to have a shorter chain than n , so that l(2n)<l(n) ; the smallest n for which this happens is 375494703 , which is followed by 602641031 , 619418303 , and so on (sequence A230528 in the OEIS). Brauer chain: A Brauer chain or star addition chain is an addition chain in which each of the sums used to calculate its numbers uses the immediately previous number. A Brauer number is a number for which a Brauer chain is optimal.Brauer proved that l*(2n−1) ≤ n − 1 + l*(n)where l∗ is the length of the shortest star chain. For many values of n, and in particular for n < 12509, they are equal: l(n) = l*(n). But Hansen showed that there are some values of n for which l(n) ≠ l*(n), such as n = 26106 + 23048 + 22032 + 22016 + 1 which has l*(n) = 6110, l(n) ≤ 6109. The smallest such n is 12509. Scholz conjecture: The Scholz conjecture (sometimes called the Scholz–Brauer or Brauer–Scholz conjecture), named after Arnold Scholz and Alfred T. Brauer), is a conjecture from 1937 stating that l(2n−1)≤n−1+l(n). This inequality is known to hold for all Hansen numbers, a generalization of Brauer numbers; Neill Clift checked by computer that all 5784688 are Hansen (while 5784689 is not). Clift further verified that in fact l(2n−1)=n−1+l(n) for all 64
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Frequency separation** Frequency separation: Frequency separation within astrophysics, is a term used in both Helioseismology and Asteroseismology. It refers to the spacing in frequency between adjacent modes of oscillation, having the same angular degree (l) but different radial order (n). Frequency separation: For a Sun-like star, the frequency can be further described using the 'large frequency spacing' between modes of different radial order (136 μHz in the Sun), and the 'small frequency spacing' between modes of even and odd angular degree within the same radial order (9.0 μHz in the Sun). The period corresponding to the large frequency spacing can be shown to be approximately the same as the time required for a sound wave to travel to the centre of the Sun and return, confirming the global nature of the oscillations seen.A further frequency separation, the rotational splitting can be seen in high-resolution solar data between modes of the same angular degree, but different azimuthal order (m). This gives information
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Kaon** Kaon: In particle physics, a kaon (), also called a K meson and denoted K, is any of a group of four mesons distinguished by a quantum number called strangeness. In the quark model they are understood to be bound states of a strange quark (or antiquark) and an up or down antiquark (or quark). Kaon: Kaons have proved to be a copious source of information on the nature of fundamental interactions since their discovery in cosmic rays in 1947. They were essential in establishing the foundations of the Standard Model of particle physics, such as the quark model of hadrons and the theory of quark mixing (the latter was acknowledged by a Nobel Prize in Physics in 2008). Kaons have played a distinguished role in our understanding of fundamental conservation laws: CP violation, a phenomenon generating the observed matter–antimatter asymmetry of the universe, was discovered in the kaon system in 1964 (which was acknowledged by a Nobel Prize in 1980). Moreover, direct CP violation was discovered in the kaon decays in the early 2000s by the NA48 experiment at CERN and the KTeV experiment at Fermilab. Basic properties: The four kaons are : K−, negatively charged (containing a strange quark and an up antiquark) has mass 493.677±0.013 MeV and mean lifetime (1.2380±0.0020)×10−8 s. K+ (antiparticle of above) positively charged (containing an up quark and a strange antiquark) must (by CPT invariance) have mass and lifetime equal to that of K−. Experimentally, the mass difference is 0.032±0.090 MeV, consistent with zero; the difference in lifetimes is (0.11±0.09)×10−8 s, also consistent with zero. K0, neutrally charged (containing a down quark and a strange antiquark) has mass 497.648±0.022 MeV. It has mean squared charge radius of −0.076±0.01 fm2. Basic properties: K0, neutrally charged (antiparticle of above) (containing a strange quark and a down antiquark) has the same mass.As the quark model shows, assignments that the kaons form two doublets of isospin; that is, they belong to the fundamental representation of SU(2) called the 2. One doublet of strangeness +1 contains the K+ and the K0. The antiparticles form the other doublet (of strangeness −1). Basic properties: [*] See Notes on neutral kaons in the article List of mesons, and neutral kaon mixing, below.[§]^ Strong eigenstate. No definite lifetime (see neutral kaon mixing).[†]^ Weak eigenstate. Makeup is missing small CP–violating term (see neutral kaon mixing).[‡]^ The mass of the K0L and K0S are given as that of the K0. However, it is known that a relatively minute difference between the masses of the K0L and K0S on the order of 3.5×10−6 eV/c2 exists.Although the K0 and its antiparticle K0 are usually produced via the strong force, they decay weakly. Thus, once created the two are better thought of as superpositions of two weak eigenstates which have vastly different lifetimes: The long-lived neutral kaon is called the KL ("K-long"), decays primarily into three pions, and has a mean lifetime of 5.18×10−8 s. Basic properties: The short-lived neutral kaon is called the KS ("K-short"), decays primarily into two pions, and has a mean lifetime 8.958×10−11 s.(See discussion of neutral kaon mixing below.) An experimental observation made in 1964 that K-longs rarely decay into two pions was the discovery of CP violation (see below). Main decay modes for K+: Decay modes for the K− are charge conjugates of the ones above. Parity violation: Two different decays were found for charged strange mesons: The intrinsic parity of a pion is P = −1, and parity is a multiplicative quantum number. Therefore, the two final states have different parity (P = +1 and P = −1, respectively). It was thought that the initial states should also have different parities, and hence be two distinct particles. However, with increasingly precise measurements, no difference was found between the masses and lifetimes of each, respectively, indicating that they are the same particle. This was known as the τ–θ puzzle. It was resolved only by the discovery of parity violation in weak interactions. Since the mesons decay through weak interactions, parity is not conserved, and the two decays are actually decays of the same particle, now called the K+. History: The discovery of hadrons with the internal quantum number "strangeness" marks the beginning of a most exciting epoch in particle physics that even now, fifty years later, has not yet found its conclusion ... by and large experiments have driven the development, and that major discoveries came unexpectedly or even against expectations expressed by theorists. — Bigi & Sanda (2016) While looking for the hypothetical nuclear meson, Louis Leprince-Ringuet found evidence for the existence of a positively charged heavier particle in 1944.In 1947, G.D. Rochester and C.C. Butler of the University of Manchester published two cloud chamber photographs of cosmic ray-induced events, one showing what appeared to be a neutral particle decaying into two charged pions, and one which appeared to be a charged particle decaying into a charged pion and something neutral. The estimated mass of the new particles was very rough, about half a proton's mass. More examples of these "V-particles" were slow in coming. History: In 1949, Rosemary Brown (later Rosemary Fowler), a research student in C.F. Powell's Bristol group, spotted her 'k' track, made by a particle of very similar mass that decayed to three pions.(p82) This led to the so-called 'Tau-Theta' problem: What seemed to be the same particles (now called K+) decayed in two different modes, Theta to two pions (parity +1), Tau to three pions (parity −1). The solution to this puzzle turned out to be that weak interactions do not conserve parity. History: The first breakthrough was obtained at Caltech, where a cloud chamber was taken up Mount Wilson, for greater cosmic ray exposure. In 1950, 30 charged and 4 neutral "V-particles" were reported. Inspired by this, numerous mountaintop observations were made over the next several years, and by 1953, the following terminology was being used: "L meson" for either a muon or charged pion; "K meson" meant a particle intermediate in mass between the pion and nucleon. History: Leprince-Rinquet coined the still-used term "hyperon" to mean any particle heavier than a nucleon. The Leprince-Ringuet particle turned out to be the K+ meson.The decays were extremely slow; typical lifetimes are of the order of 10−10 s. However, production in pion-proton reactions proceeds much faster, with a time scale of 10−23 s. The problem of this mismatch was solved by Abraham Pais who postulated the new quantum number called "strangeness" which is conserved in strong interactions but violated by the weak interactions. Strange particles appear copiously due to "associated production" of a strange and an antistrange particle together. It was soon shown that this could not be a multiplicative quantum number, because that would allow reactions which were never seen in the new synchrotrons which were commissioned in Brookhaven National Laboratory in 1953 and in the Lawrence Berkeley Laboratory in 1955. CP violation in neutral meson oscillations: Initially it was thought that although parity was violated, CP (charge parity) symmetry was conserved. In order to understand the discovery of CP violation, it is necessary to understand the mixing of neutral kaons; this phenomenon does not require CP violation, but it is the context in which CP violation was first observed. CP violation in neutral meson oscillations: Neutral kaon mixing Since neutral kaons carry strangeness, they cannot be their own antiparticles. There must be then two different neutral kaons, differing by two units of strangeness. The question was then how to establish the presence of these two mesons. The solution used a phenomenon called neutral particle oscillations, by which these two kinds of mesons can turn from one into another through the weak interactions, which cause them to decay into pions (see the adjacent figure). CP violation in neutral meson oscillations: These oscillations were first investigated by Murray Gell-Mann and Abraham Pais together. They considered the CP-invariant time evolution of states with opposite strangeness. In matrix notation one can write ψ(t)=U(t)ψ(0)=eiHt(ab),H=(MΔΔM), where ψ is a quantum state of the system specified by the amplitudes of being in each of the two basis states (which are a and b at time t = 0). The diagonal elements (M) of the Hamiltonian are due to strong interaction physics which conserves strangeness. The two diagonal elements must be equal, since the particle and antiparticle have equal masses in the absence of the weak interactions. The off-diagonal elements, which mix opposite strangeness particles, are due to weak interactions; CP symmetry requires them to be real. CP violation in neutral meson oscillations: The consequence of the matrix H being real is that the probabilities of the two states will forever oscillate back and forth. However, if any part of the matrix were imaginary, as is forbidden by CP symmetry, then part of the combination will diminish over time. The diminishing part can be either one component (a) or the other (b), or a mixture of the two. CP violation in neutral meson oscillations: Mixing The eigenstates are obtained by diagonalizing this matrix. This gives new eigenvectors, which we can call K1 which is the difference of the two states of opposite strangeness, and K2, which is the sum. The two are eigenstates of CP with opposite eigenvalues; K1 has CP = +1, and K2 has CP = -1 Since the two-pion final state also has CP = +1, only the K1 can decay this way. The K2 must decay into three pions. Since the mass of K2 is just a little larger than the sum of the masses of three pions, this decay proceeds very slowly, about 600 times slower than the decay of K1 into two pions. These two different modes of decay were observed by Leon Lederman and his coworkers in 1956, establishing the existence of the two weak eigenstates (states with definite lifetimes under decays via the weak force) of the neutral kaons. CP violation in neutral meson oscillations: These two weak eigenstates are called the KL (K-long, τ) and KS (K-short, θ). CP symmetry, which was assumed at the time, implies that KS = K1 and KL = K2. CP violation in neutral meson oscillations: Oscillation An initially pure beam of K0 will turn into its antiparticle, K0, while propagating, which will turn back into the original particle, K0, and so on. This is called particle oscillation. On observing the weak decay into leptons, it was found that a K0 always decayed into a positron, whereas the antiparticle K0 decayed into the electron. The earlier analysis yielded a relation between the rate of electron and positron production from sources of pure K0 and its antiparticle K0. Analysis of the time dependence of this semileptonic decay showed the phenomenon of oscillation, and allowed the extraction of the mass splitting between the KS and KL. Since this is due to weak interactions it is very small, 10−15 times the mass of each state, namely ∆MK = M(KL) − M(KS) = 3.484(6)×10−12 MeV . CP violation in neutral meson oscillations: Regeneration A beam of neutral kaons decays in flight so that the short-lived KS disappears, leaving a beam of pure long-lived KL. If this beam is shot into matter, then the K0 and its antiparticle K0 interact differently with the nuclei. The K0 undergoes quasi-elastic scattering with nucleons, whereas its antiparticle can create hyperons. Due to the different interactions of the two components, quantum coherence between the two particles is lost. The emerging beam then contains different linear superpositions of the K0 and K0. Such a superposition is a mixture of KL and KS; the KS is regenerated by passing a neutral kaon beam through matter. Regeneration was observed by Oreste Piccioni and his collaborators at Lawrence Berkeley National Laboratory. Soon thereafter, Robert Adair and his coworkers reported excess KS regeneration, thus opening a new chapter in this history. CP violation in neutral meson oscillations: CP violation While trying to verify Adair's results, J. Christenson, James Cronin, Val Fitch and Rene Turlay of Princeton University found decays of KL into two pions (CP = +1) in an experiment performed in 1964 at the Alternating Gradient Synchrotron at the Brookhaven laboratory. As explained in an earlier section, this required the assumed initial and final states to have different values of CP, and hence immediately suggested CP violation. Alternative explanations such as nonlinear quantum mechanics and a new unobserved particle (hyperphoton) were soon ruled out, leaving CP violation as the only possibility. Cronin and Fitch received the Nobel Prize in Physics for this discovery in 1980. CP violation in neutral meson oscillations: It turns out that although the KL and KS are weak eigenstates (because they have definite lifetimes for decay by way of the weak force), they are not quite CP eigenstates. Instead, for small ε (and up to normalization), KL = K2 + εK1and similarly for KS. Thus occasionally the KL decays as a K1 with CP = +1, and likewise the KS can decay with CP = −1. This is known as indirect CP violation, CP violation due to mixing of K0 and its antiparticle. There is also a direct CP violation effect, in which the CP violation occurs during the decay itself. Both are present, because both mixing and decay arise from the same interaction with the W boson and thus have CP violation predicted by the CKM matrix. Direct CP violation was discovered in the kaon decays in the early 2000s by the NA48 and KTeV experiments at CERN and Fermilab.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Twist (cocktail garnish)** Twist (cocktail garnish): A twist is a piece of citrus zest used as a cocktail garnish, generally for decoration and to add flavor when added to a mixed drink. Twist (cocktail garnish): There are a variety of ways of making and using twists. Twists are typically cut from a whole fresh citrus fruit with a small kitchen knife immediately prior to serving, although a peeler, citrus zesters, or other utensil may be used. A curled shape may come from cutting the wedge into a spiral, winding it around a straw or other object, or as a byproduct of the cutting. Twist (cocktail garnish): The name may refer to the shape of the garnish, which is typically curled or twisted longitudinally, or else to the act of twisting the garnish to release fruit oils that infuse the drink. Other techniques include running the twist along the rim of the glass, and "flaming" the twist.They are generally about 50 mm (2 inches) long (although length varies), and thin.Cocktails featuring a twist include Horse's Neck. A lemon twist is also an optional garnish for the martini, and an orange twist is traditional for the old fashioned.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Registered user** Registered user: A registered user is a user of a website, program, or other systems who has previously registered. Registered users normally provide some sort of credentials (such as a username or e-mail address, and a password) to the system in order to prove their identity: this is known as logging in. Systems intended for use by the general public often allow any user to register simply by selecting a register or sign up function and providing these credentials for the first time. Registered users may be granted privileges beyond those granted to unregistered users. Rationale: User registration and login enables a system to personalize itself. For example, a website might display a welcome banner with the user's name and change its appearance or behavior according to preferences indicated by the user. The system may also allow a logged-in user to send and receive messages, and to view and modify personal files or other information. Criticism: Privacy concerns Registration necessarily provides more personal information to a system than it would otherwise have. Even if the credentials used are otherwise meaningless, the system can distinguish a logged-in user from other users and might use this property to store a history of users' actions or activity, possibly without their knowledge or consent. While many systems have privacy policies, depending on the nature of the system, a user might not have any way of knowing for certain exactly what information is stored, how it is used, and with whom, if anyone, it is shared. Criticism: A system could even sell information it has gathered on its users to third parties for advertising or other purposes. The subject of systems' transparency in this regard is one of ongoing debate. Criticism: User inconvenience Registration may be seen as an annoyance or hindrance, especially if it is not inherently necessary or important (for example, in the context of a search engine) or if the system repeatedly prompts users to register. A system's registration process might also be time-consuming or require that the user provide the information they might be reluctant to, such as a home address or social security number.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Parabolic antenna** Parabolic antenna: A parabolic antenna is an antenna that uses a parabolic reflector, a curved surface with the cross-sectional shape of a parabola, to direct the radio waves. The most common form is shaped like a dish and is popularly called a dish antenna or parabolic dish. The main advantage of a parabolic antenna is that it has high directivity. It functions similarly to a searchlight or flashlight reflector to direct radio waves in a narrow beam, or receive radio waves from one particular direction only. Parabolic antennas have some of the highest gains, meaning that they can produce the narrowest beamwidths, of any antenna type. In order to achieve narrow beamwidths, the parabolic reflector must be much larger than the wavelength of the radio waves used, so parabolic antennas are used in the high frequency part of the radio spectrum, at UHF and microwave (SHF) frequencies, at which the wavelengths are small enough that conveniently-sized reflectors can be used. Parabolic antenna: Parabolic antennas are used as high-gain antennas for point-to-point communications, in applications such as microwave relay links that carry telephone and television signals between nearby cities, wireless WAN/LAN links for data communications, satellite communications, and spacecraft communication antennas. They are also used in radio telescopes. Parabolic antenna: The other large use of parabolic antennas is for radar antennas, which need to transmit a narrow beam of radio waves to locate objects like ships, airplanes, and guided missiles. They are also often used for weather detection. With the advent of home satellite television receivers, parabolic antennas have become a common feature of the landscapes of modern countries.The parabolic antenna was invented by German physicist Heinrich Hertz during his discovery of radio waves in 1887. He used cylindrical parabolic reflectors with spark-excited dipole antennas at their foci for both transmitting and receiving during his historic experiments. Design: The operating principle of a parabolic antenna is that a point source of radio waves at the focal point in front of a paraboloidal reflector of conductive material will be reflected into a collimated plane wave beam along the axis of the reflector. Conversely, an incoming plane wave parallel to the axis will be focused to a point at the focal point. Design: A typical parabolic antenna consists of a metal parabolic reflector with a small feed antenna suspended in front of the reflector at its focus, pointed back toward the reflector. The reflector is a metallic surface formed into a paraboloid of revolution and usually truncated in a circular rim that forms the diameter of the antenna. In a transmitting antenna, radio frequency current from a transmitter is supplied through a transmission line cable to the feed antenna, which converts it into radio waves. The radio waves are emitted back toward the dish by the feed antenna and reflect off the dish into a parallel beam. In a receiving antenna the incoming radio waves bounce off the dish and are focused to a point at the feed antenna, which converts them into electric currents which travel through a transmission line to the radio receiver. Design: Parabolic reflector The reflector can be constructed from sheet metal, a metal screen, or a wire grill, and can be either a circular dish or various other shapes to create different beam shapes. A metal screen reflects radio waves as effectively as a solid metal surface if its holes are smaller than one-tenth of a wavelength, so screen reflectors are often used to reduce weight and wind loads on the dish. To achieve the maximum gain, the shape of the dish needs to be accurate within a small fraction of a wavelength, to ensure the waves from different parts of the antenna arrive at the focus in phase. Large dishes often require a supporting truss structure behind them to provide the required stiffness. Design: A reflector made of a grill of parallel wires or bars oriented in one direction acts as a polarizing filter as well as a reflector. It only reflects linearly polarized radio waves, with the electric field parallel to the grill elements. This type is often used in radar antennas. Combined with a linearly polarized feed horn, it helps filter out noise in the receiver and reduces false returns. Design: A shiny metal parabolic reflector can also focus the sun's rays. Since most dishes could concentrate enough solar energy on the feed structure to severely overheat it if they happened to be pointed at the sun, solid reflectors are always given a coat of flat paint. Design: Feed antenna The feed antenna at the reflector's focus is typically a low-gain type, such as a half-wave dipole or (more often) a small horn antenna called a feed horn. In more complex designs, such as the Cassegrain and Gregorian, a secondary reflector is used to direct the energy into the parabolic reflector from a feed antenna located away from the primary focal point. The feed antenna is connected to the associated radio-frequency (RF) transmitting or receiving equipment by means of a coaxial cable transmission line or waveguide. Design: At the microwave frequencies used in many parabolic antennas, waveguide is required to conduct the microwaves between the feed antenna and transmitter or receiver. Because of the high cost of waveguide runs, in many parabolic antennas the RF front end electronics of the receiver is located at the feed antenna, and the received signal is converted to a lower intermediate frequency (IF) so it can be conducted to the receiver through cheaper coaxial cable. This is called a low-noise block downconverter. Similarly, in transmitting dishes, the microwave transmitter may be located at the feed point. Design: An advantage of parabolic antennas is that most of the structure of the antenna (all of it except the feed antenna) is nonresonant, so it can function over a wide range of frequencies (i.e. a wide bandwidth). All that is necessary to change the frequency of operation is to replace the feed antenna with one that operates at the desired frequency. Some parabolic antennas transmit or receive at multiple frequencies by having several feed antennas mounted at the focal point, close together. Types: Parabolic antennas are distinguished by their shapes: Paraboloidal or dish – The reflector is shaped like a paraboloid truncated with a circular rim. This is the most common type. It radiates a narrow pencil-shaped beam along the axis of the dish. Types: Shrouded dish – Sometimes a cylindrical metal shield is attached to the rim of the dish. The shroud shields the antenna from radiation from angles outside the main beam axis, reducing the sidelobes. It is sometimes used to prevent interference in terrestrial microwave links, where several antennas using the same frequency are located close together. The shroud is coated inside with microwave absorbent material. Shrouds can reduce back lobe radiation by 10 dB. Types: Cylindrical – The reflector is curved in only one direction and flat in the other. The radio waves come to a focus not at a point but along a line. The feed is sometimes a dipole antenna located along the focal line. Cylindrical parabolic antennas radiate a fan-shaped beam, narrow in the curved dimension, and wide in the uncurved dimension. The curved ends of the reflector are sometimes capped by flat plates, to prevent radiation out the ends, and this is called a pillbox antenna. Types: Shaped-beam antennas – Modern reflector antennas can be designed to produce a beam or beams of a particular shape, rather than just the narrow "pencil" or "fan" beams of the simple dish and cylindrical antennas mentioned above. Two techniques are used, often in combination, to control the shape of the beam: Shaped reflectors – The parabolic reflector can be given a noncircular shape, or different curvatures in the horizontal and vertical directions, to alter the shape of the beam. This is often used in radar antennas. As a general principle, the wider the antenna is in a given transverse direction, the narrower the radiation pattern will be in that direction. Types: "Orange peel" antenna – Used in search radars, this is a long narrow antenna shaped like the letter "C". It radiates a narrow vertical fan-shaped beam.Arrays of feeds – In order to produce an arbitrary shaped beam, instead of one feed horn, an array of feed horns clustered around the focal point can be used. Array-fed antennas are often used on communication satellites, particularly direct broadcast satellites, to create a downlink radiation pattern to cover a particular continent or coverage area. They are often used with secondary reflector antennas such as the Cassegrain.Parabolic antennas are also classified by the type of feed, that is, how the radio waves are supplied to the antenna: Axial, prime focus, or front feed – This is the most common type of feed, with the feed antenna located in front of the dish at the focus, on the beam axis, pointed back toward the dish. A disadvantage of this type is that the feed and its supports block some of the beam, which limits the aperture efficiency to only 55–60%. Types: Off-axis or offset feed – The reflector is an asymmetrical segment of a paraboloid, so the focus, and the feed antenna, are located to one side of the dish. The purpose of this design is to move the feed structure out of the beam path, so it does not block the beam. It is widely used in home satellite television dishes, which are small enough that the feed structure would otherwise block a significant percentage of the signal. Offset feed can also be used in multiple reflector designs such as the Cassegrain and Gregorian, below. Types: Cassegrain – In a Cassegrain antenna, the feed is located on or behind the dish, and radiates forward, illuminating a convex hyperboloidal secondary reflector at the focus of the dish. The radio waves from the feed reflect off the secondary reflector to the dish, which reflects them forward again, forming the outgoing beam. An advantage of this configuration is that the feed, with its waveguides and "front end" electronics does not have to be suspended in front of the dish, so it is used for antennas with complicated or bulky feeds, such as large satellite communication antennas and radio telescopes. Aperture efficiency is on the order of 65–70%. Types: Gregorian – Similar to the Cassegrain design except that the secondary reflector is concave (ellipsoidal) in shape. Aperture efficiency over 70% can be achieved. Feed pattern: The radiation pattern of the feed antenna has to be tailored to the shape of the dish, because it has a strong influence on the aperture efficiency, which determines the antenna gain (see Gain section below). Radiation from the feed that falls outside the edge of the dish is called spillover and is wasted, reducing the gain and increasing the backlobes, possibly causing interference or (in receiving antennas) increasing susceptibility to ground noise. However, maximum gain is only achieved when the dish is uniformly "illuminated" with a constant field strength to its edges. Therefore, the ideal radiation pattern of a feed antenna would be a constant field strength throughout the solid angle of the dish, dropping abruptly to zero at the edges. However, practical feed antennas have radiation patterns that drop off gradually at the edges, so the feed antenna is a compromise between acceptably low spillover and adequate illumination. For most front feed horns, optimum illumination is achieved when the power radiated by the feed horn is 10 dB less at the dish edge than its maximum value at the center of the dish. Feed pattern: Polarization The pattern of electric and magnetic fields at the mouth of a parabolic antenna is simply a scaled-up image of the fields radiated by the feed antenna, so the polarization is determined by the feed antenna. In order to achieve maximum gain, both feed antennas (transmitting and receiving) must have the same polarization. For example, a vertical dipole feed antenna will radiate a beam of radio waves with their electric field vertical, called vertical polarization. The receiving feed antenna must also have vertical polarization to receive them; if the feed is horizontal (horizontal polarization) the antenna will suffer a severe loss of gain. Feed pattern: To increase the data rate, some parabolic antennas transmit two separate radio channels on the same frequency with orthogonal polarizations, using separate feed antennas; this is called a dual polarization antenna. For example, satellite television signals are transmitted from the satellite on two separate channels at the same frequency using right and left circular polarization. In a home satellite dish, these are received by two small monopole antennas in the feed horn, oriented at right angles. Each antenna is connected to a separate receiver. Feed pattern: If the signal from one polarization channel is received by the oppositely polarized antenna, it will cause crosstalk that degrades the signal-to-noise ratio. The ability of an antenna to keep these orthogonal channels separate is measured by a parameter called cross polarization discrimination (XPD). In a transmitting antenna, XPD is the fraction of power from an antenna of one polarization radiated in the other polarization. For example, due to minor imperfections a dish with a vertically polarized feed antenna will radiate a small amount of its power in horizontal polarization; this fraction is the XPD. In a receiving antenna, the XPD is the ratio of signal power received of the opposite polarization to power received in the same antenna of the correct polarization, when the antenna is illuminated by two orthogonally polarized radio waves of equal power. If the antenna system has inadequate XPD, cross polarization interference cancelling (XPIC) digital signal processing algorithms can often be used to decrease crosstalk. Feed pattern: Dual reflector shaping In the Cassegrain and Gregorian antennas, the presence of two reflecting surfaces in the signal path offers additional possibilities for improving performance. When the highest performance is required, a technique called dual reflector shaping may be used. This involves changing the shape of the sub-reflector to direct more signal power to outer areas of the dish, to map the known pattern of the feed into a uniform illumination of the primary, to maximize the gain. However, this results in a secondary that is no longer precisely hyperbolic (though it is still very close), so the constant phase property is lost. This phase error, however, can be compensated for by slightly tweaking the shape of the primary mirror. The result is a higher gain, or gain/spillover ratio, at the cost of surfaces that are trickier to fabricate and test. Other dish illumination patterns can also be synthesized, such as patterns with high taper at the dish edge for ultra-low spillover sidelobes, and patterns with a central "hole" to reduce feed shadowing. Gain: The directive qualities of an antenna are measured by a dimensionless parameter called its gain, which is the ratio of the power received by the antenna from a source along its beam axis to the power received by a hypothetical isotropic antenna. The gain of a parabolic antenna is: G=4πAλ2eA=(πdλ)2eA where: A is the area of the antenna aperture, that is, the mouth of the parabolic reflector. For a circular dish antenna, A=πd2/4 , giving the second formula above. Gain: d is the diameter of the parabolic reflector, if it is circular. λ is the wavelength of the radio waves. Gain: eA is a dimensionless parameter between 0 and 1 called the aperture efficiency. The aperture efficiency of typical parabolic antennas is 0.55 to 0.70.It can be seen that, as with any aperture antenna, the larger the aperture is, compared to the wavelength, the higher the gain. The gain increases with the square of the ratio of aperture width to wavelength, so large parabolic antennas, such as those used for spacecraft communication and radio telescopes, can have extremely high gain. Applying the above formula to the 25-meter-diameter antennas often used in radio telescope arrays and satellite ground antennas at a wavelength of 21 cm (1.42 GHz, a common radio astronomy frequency), yields an approximate maximum gain of 140,000 times or about 52 dBi (decibels above the isotropic level). The largest parabolic dish antenna in the world is the Five-hundred-meter Aperture Spherical radio Telescope in southwest China, which has an effective aperture of about 300 meters. The gain of this dish at 3 GHz is roughly 90 million, or 80 dBi. Gain: Aperture efficiency eA is a catchall variable which accounts for various losses that reduce the gain of the antenna from the maximum that could be achieved with the given aperture. The major factors reducing the aperture efficiency in parabolic antennas are: Feed spillover – Some of the radiation from the feed antenna falls outside the edge of the dish and so does not contribute to the main beam. Gain: Feed illumination taper – The maximum gain for any aperture antenna is only achieved when the intensity of the radiated beam is constant across the entire aperture area. However, the radiation pattern from the feed antenna usually tapers off toward the outer part of the dish, so the outer parts of the dish are "illuminated" with a lower intensity of radiation. Even if the feed provided constant illumination across the angle subtended by the dish, the outer parts of the dish are farther away from the feed antenna than the inner parts, so the intensity would drop off with distance from the center. Hence, the intensity of the beam radiated by a parabolic antenna is maximum at the center of the dish and falls off with distance from the axis, reducing the efficiency. Gain: Aperture blockage – In front-fed parabolic dishes where the feed antenna is located in front of the dish in the beam path (and in Cassegrain and Gregorian designs as well), the feed structure and its supports block some of the beam. In small dishes such as home satellite dishes, where the size of the feed structure is comparable with the size of the dish, this can seriously reduce the antenna gain. To prevent this problem these types of antennas often use an offset feed, where the feed antenna is located to one side, outside the beam area. The aperture efficiency for these types of antennas can reach 0.7 to 0.8. Gain: Shape errors – Random surface errors in the shape of the reflector reduce efficiency. This loss is approximated by Ruze's Equation.For theoretical considerations of mutual interference (at frequencies between 2 and approximately 30 GHz; typically in the Fixed Satellite Service) where specific antenna performance has not been defined, a reference antenna based on Recommendation ITU-R S.465 is used to calculate the interference, which will include the likely sidelobes for off-axis effects. Radiation pattern: In parabolic antennas, virtually all the power radiated is concentrated in a narrow main lobe along the antenna's axis. The residual power is radiated in sidelobes, usually much smaller, in other directions. Since the reflector aperture of parabolic antennas is much larger than the wavelength, diffraction usually causes many narrow sidelobes, so the sidelobe pattern is complex. There is also usually a backlobe, in the opposite direction to the main lobe, due to the spillover radiation from the feed antenna that misses the reflector. Radiation pattern: Beamwidth The angular width of the beam radiated by high-gain antennas is measured by the half-power beam width (HPBW), which is the angular separation between the points on the antenna radiation pattern at which the power drops to one-half (-3 dB) its maximum value. For parabolic antennas, the HPBW θ is given by: θ=kλ/d where k is a factor which varies slightly depending on the shape of the reflector and the feed illumination pattern. For an ideal uniformly illuminated parabolic reflector and θ in degrees, k would be 57.3 (the number of degrees in a radian). For a typical parabolic antenna, k is approximately 70.For a typical 2 meter satellite dish operating on C band (4 GHz), this formula gives a beamwidth of about 2.6°. For the Arecibo antenna at 2.4 GHz, the beamwidth is 0.028°. Since parabolic antennas can produce very narrow beams, aiming them can be a problem. Some parabolic dishes are equipped with a boresight so they can be aimed accurately at the other antenna. Radiation pattern: There is an inverse relation between gain and beam width. By combining the beamwidth equation with the gain equation, the relation is: G=(πkθ)2eA Radiation pattern formula The radiation from a large paraboloid with uniform illuminated aperture is essentially equivalent to that from a circular aperture of the same diameter D in an infinite metal plate with a uniform plane wave incident on the plate.The radiation-field pattern can be calculated by applying Huygens' principle in a similar way to a rectangular aperture. The electric field pattern can be found by evaluating the Fraunhofer diffraction integral over the circular aperture. It can also be determined through Fresnel zone equations. Radiation pattern: E=∫∫Ar1ej(ωt−βr1)dS=∫∫e2πi(lx+my)/λdS where β=ω/c=2π/λ . Using polar coordinates, cos ⁡θ and sin ⁡θ . Taking account of symmetry, cos ⁡θl/λρdρ and using first-order Bessel function gives the electric field pattern E(θ) where D is the diameter of the antenna's aperture in meters, λ is the wavelength in meters, θ is the angle in radians from the antenna's symmetry axis as shown in the figure, and J1 is the first-order Bessel function. Determining the first nulls of the radiation pattern gives the beamwidth θ0 . The term J1(x)=0 whenever 3.83 . Thus, arcsin 3.83 arcsin 1.22 λD When the aperture is large, the angle θ0 is very small, so arcsin ⁡(x) is approximately equal to x . This gives the common beamwidth formulas, History: The idea of using parabolic reflectors for radio antennas was taken from optics, where the power of a parabolic mirror to focus light into a beam has been known since classical antiquity. The designs of some specific types of parabolic antenna, such as the Cassegrain and Gregorian, come from similarly named analogous types of reflecting telescope, which were invented by astronomers during the 15th century.German physicist Heinrich Hertz constructed the world's first parabolic reflector antenna in 1888. The antenna was a cylindrical parabolic reflector made of zinc sheet metal supported by a wooden frame, and had a spark-gap excited 26 cm dipole as a feed antenna along the focal line. Its aperture was 2 meters high by 1.2 meters wide, with a focal length of 0.12 meters, and was used at an operating frequency of about 450 MHz. With two such antennas, one used for transmitting and the other for receiving, Hertz demonstrated the existence of radio waves which had been predicted by James Clerk Maxwell some 22 years earlier. However, the early development of radio was limited to lower frequencies at which parabolic antennas were unsuitable, and they were not widely used until after World War II, when microwave frequencies began to be employed. History: Italian radio pioneer Guglielmo Marconi used a parabolic reflector during the 1930s in investigations of UHF transmission from his boat in the Mediterranean. In 1931, a 1.7 GHz microwave relay telephone link across the English Channel was demonstrated using 3.0-meter (10 ft) diameter dishes. The first large parabolic antenna, a 9 m dish, was built in 1937 by pioneering radio astronomer Grote Reber in his backyard, and the sky survey he did with it was one of the events that founded the field of radio astronomy.The development of radar during World War II provided a great impetus to parabolic antenna research. This led to the evolution of shaped-beam antennas, in which the curve of the reflector is different in the vertical and horizontal directions, tailored to produce a beam with a particular shape. After the war, very large parabolic dishes were built as radio telescopes. The 100-meter Green Bank Radio Telescope at Green Bank, West Virginia—the first version of which was completed in 1962—is currently the world's largest fully steerable parabolic dish. History: During the 1960s, dish antennas became widely used in terrestrial microwave relay communication networks, which carried telephone calls and television programs across continents. The first parabolic antenna used for satellite communications was constructed in 1962 at Goonhilly in Cornwall, England, to communicate with the Telstar satellite. The Cassegrain antenna was developed in Japan in 1963 by NTT, KDDI, and Mitsubishi Electric. The advent of computer design tools in the 1970s—such as NEC, capable of calculating the radiation pattern of parabolic antennas—has led to the development of sophisticated asymmetric, multi-reflector and multi-feed designs in recent years.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Learning engineering** Learning engineering: Learning Engineering is the systematic application of evidence-based principles and methods from educational technology and the learning sciences to create engaging and effective learning experiences, support the difficulties and challenges of learners as they learn, and come to better understand learners and learning. It emphasizes the use of a human-centered design approach in conjunction with analyses of rich data sets to iteratively develop and improve those designs to address specific learning needs, opportunities, and problems, often with the help of technology. Working with subject-matter and other experts, the Learning Engineer deftly combines knowledge, tools, and techniques from a variety of technical, pedagogical, empirical, and design-based disciplines to create effective and engaging learning experiences and environments and to evaluate the resulting outcomes. While doing so, the Learning Engineer strives to generate processes and theories that afford generalization of best practices, along with new tools and infrastructures that empower others to create their own learning designs based on those best practices. Learning engineering: Supporting learners as they learn is complex, and design of learning experiences and support for learners usually requires interdisciplinary teams. Learning engineers themselves might specialize in designing learning experiences that unfold over time, engage the population of learners, and support their learning; automated data collection and analysis; design of learning technologies; design of learning platforms; improve environments or conditions that support learning; or some combination. The products of learning engineering teams include on-line courses (e.g., a particular MOOC), software platforms for offering online courses, learning technologies (e.g., ranging from physical manipulatives to electronically-enhanced physical manipulatives to technologies for simulation or modeling to technologies for allowing immersion), after-school programs, community learning experiences, formal curricula, and more. Learning engineering teams require expertise associated with the content that learners will learn, the targeted learners themselves, the venues in which learning is expected to happen, educational practice, software engineering, and sometimes even more. Learning engineering: Learning engineering teams employ an iterative design process for supporting and improving learning. Initial designs are informed by findings from the learning sciences. Refinements are informed by analysis of data collected as designs are carried out in the world. Methods from learning analytics, design-based research, and rapid large-scale experimentation are used to evaluate designs, inform refinements, and keep track of iterations. According to the IEEE Standards Association's IC Industry Consortium on Learning Engineering, "Learning Engineering is a process and practice that applies the learning sciences using human-centered engineering design methodologies and data-informed decision making to support learners and their development." History: Herbert Simon, a cognitive psychologist and economist, first coined the term learning engineering in 1967. However, associations between the two terms learning and engineering began emerging earlier, in the 1940s and as early as the 1920s. Simon argued that the social sciences, including the field of education, should be approached with the same kind of mathematical principles as other fields like physics and engineering.Simon’s ideas about learning engineering continued to reverberate at Carnegie Mellon University, but the term did not catch on until businessman Bror Saxberg began marketing it in 2014 after visiting Carnegie Mellon University and the Pittsburgh Science of Learning Center, or LearnLab for short. Bror Saxberg brought his team from the for-profit education company, Kaplan, to visit CMU. The team went back to Kaplan with what we now call learning engineering to enhance, optimize, test, and sell their educational products. Bror Saxberg would later co-write with Frederick Hess, founder of the American Enterprise Institute's Conservative Education Reform Network, the 2014 book using the term learning engineering. Overview: Learning Engineering is aimed at addressing a deficit in the application of science and engineering methodologies to education and training. Its advocates emphasize the need to connect computing technology and generated data with the overall goal of optimizing learning environments.Learning Engineering initiatives aim to improve educational outcomes by leveraging computing to dramatically increase the applications and effectiveness of learning science as a discipline. Digital learning platforms have generated large amounts of data which can reveal immediately actionable insights.The Learning Engineering field has the further potential to communicate educational insights automatically available to educators. For example, learning engineering techniques have been applied to the issue of drop-out or high failure rates. Traditionally, educators and administrators have to wait until students actually withdraw from school or nearly fail their courses to accurately predict when the drop out will occur. Learning engineers are now able to use data on off-task behavior or wheel spinning to better understand student engagement and predict whether individual students are likely to fail. Overview: This data enables educators to spot struggling students weeks or months prior to being in danger of dropping out. Proponents of Learning Engineering posit that data analytics will contribute to higher success rates and lower drop-out rates.Learning Engineering can also assist students by providing automatic and individualized feedback. Carnegie Learning’s tool LiveLab, for instance, employs big data to create a learning experience for each student user by, in part, identifying the causes of student mistakes. Research insights gleaned from LiveLab analyses allow teachers to see student progress in real-time. Common approaches: A/B Testing A/B testing compares two versions of a given program and allows researchers to determine which approach is most effective. In the context of Learning Engineering, platforms like TeacherASSIST and Coursera use A/B testing to determine which type of feedback is the most effective for learning outcomes.Neil Heffernan’s work with TeacherASSIST includes hint messages from teachers that guide students toward correct answers. Heffernan’s lab runs A/B tests between teachers to determine which type of hints result in the best learning for future questions.UpGrade is an open-source platform for A/B testing in education. It allows EdTech companies to run experiments within their own software. ETRIALS leverages ASSISTments and give scientists freedom to run experiments in authentic learning environments. Terracotta is a research platform that supports teachers' and researchers' abilities to easily run experiments in live classes. Common approaches: Educational Data Mining Educational Data Mining involves analyzing data from student use of educational software to understand how software can improve learning for all students. Researchers in the field, such as Ryan Baker at the University of Pennsylvania, have developed models of student learning, engagement, and affect to relate them to learning outcomes. Platform Instrumentation Education tech platforms link educators and students with resources to improve learning outcomes. Dataset Generation Datasets provide the raw material that researchers use to formulate educational insights. For example, Carnegie Mellon University hosts a large volume of learning interaction data in LearnLab's DataShop. Their datasets range from sources like Intelligent Writing Tutors to Chinese tone studies to data from Carnegie Learning’s MATHia platform. Kaggle, a hub for programmers and open source data, regularly hosts machine learning competitions. In 2019, PBS partnered with Kaggle to create the 2019 Data Science Bowl. The DataScience Bowl sought machine learning insights from researchers and developers, specifically into how digital media can better facilitate early-childhood STEM learning outcomes. Datasets, like those hosted by Kaggle PBS and Carnegie Learning, allow researchers to gather information and derive conclusions about student outcomes. These insights help predict student performance in courses and exams. Common approaches: Learning Engineering in Practice Combining education theory with data analytics has contributed to the development of tools that differentiate between when a student is wheel spinning (i.e., not mastering a skill within a set timeframe) and when they are persisting productively. Tools like ASSISTments alert teachers when students consistently fail to answer a given problem, which keeps students from tackling insurmountable obstacles, promotes effective feedback and educator intervention, and increases student engagement. Common approaches: Studies have found that Learning Engineering may help students and educators to plan their studies before courses begin. For example, UC Berkeley Professor Zach Pardos uses Learning Engineering to help reduce stress for community college students matriculating into four-year institutions. Their predictive model analyzes course descriptions and offers recommendations regarding transfer credits and courses that would align with previous directions of study.Similarly, researchers Kelli Bird and Benjamin Castlemen’s work focuses on creating an algorithm to provide automatic, personalized guidance for transfer students. The algorithm is a response to the finding that while 80 percent of community college students intend to transfer to a four-year institution, only roughly 30 percent actually do so. Such research could lead to a higher pass/fail rate and help educators know when to intervene to prevent student failure or drop out. Criticisms of Learning Engineering: Researchers and educational technology commentators have published critiques of learning engineering. The criticisms raised include that learning engineering misrepresents the field of learning sciences and that despite stating it is based on cognitive science, it actually resembles a return to behaviorism. Others have also commented that learning engineering exists as a form of surveillance capitalism. Other fields, such as instructional systems design, have criticized that learning engineering rebrands the work of their own field. Criticisms of Learning Engineering: Still others have commented critically on learning engineering's use of metaphors and figurative language. Often a term or metaphor carries a different meaning for professionals or academics from different domains. At times a term that is used positively in one domain carries a strong negative perception in another domain. Challenges for Learning Engineering Teams: The multidisciplinary nature of learning engineering creates challenges. The problems that learning engineering attempts to solve often require expertise in diverse fields such as software engineering, instructional design, domain knowledge, pedagogy/andragogy, psychometrics, learning sciences, data science, and systems engineering. In some cases, an individual Learning Engineer with expertise in multiple disciplines might be sufficient. However, learning engineering problems often exceed any one person’s ability to solve. A 2021 convening of thirty learning engineers produced recommendations that key challenges and opportunities for the future of the field involve enhancing R&D infrastructure, supporting domain-based education research, developing components for reuse across learning systems, enhancing human-computer systems, better engineering implementation in schools, improving advising, optimizing for the long-term instead of short-term, supporting 21st-century skills, improved support for learner engagement, and designing algorithms for equity.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Middle reliever** Middle reliever: In baseball, a middle reliever or middle relief pitcher, is a relief pitcher who typically pitches during the fifth, sixth, and seventh innings of a standard baseball game. In leagues with no designated hitter, such as in the National League prior to 2022 and the Japanese Central League, a middle reliever often comes in after the starting pitcher has been pulled in favor of a pinch hitter. Middle relief pitchers are usually tasked to pitch one or two innings where they are then replaced in later innings by a left-handed specialist, setup pitcher, or closer due to deprivation of stamina and effectiveness, but middle relievers may sometimes pitch in these innings as well, especially during games which are close, tied or in extra innings.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Nested transaction** Nested transaction: A nested transaction is a database transaction that is started by an instruction within the scope of an already started transaction. Nested transactions are implemented differently in different databases. However, they have in common that the changes are not made visible to any unrelated transactions until the outermost transaction has committed. This means that a commit in an inner transaction does not necessarily persist updates to the system. In some databases, changes made by the nested transaction are not seen by the 'host' transaction until the nested transaction is committed. According to some, this follows from the isolation property of transactions. Nested transaction: The capability to handle nested transactions properly is a prerequisite for true component-based application architectures. In a component-based encapsulated architecture, nested transactions can occur without the programmer knowing it. A component function may or may not contain a database transaction (this is the encapsulated secret of the component. See Information hiding). If a call to such a component function is made inside a BEGIN - COMMIT bracket, nested transactions occur. Since popular databases like MySQL do not allow nesting BEGIN - COMMIT brackets, a framework or a transaction monitor is needed to handle this. When we speak about nested transactions, it should be made clear that this feature is DBMS dependent and is not available for all databases. Nested transaction: Theory for nested transactions is similar to the theory for flat transactions.The banking industry usually processes financial transactions using open nested transactions, which is a looser variant of the nested transaction model that provides higher performance while accepting the accompanying trade-offs of inconsistency.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Decamethylferrocene** Decamethylferrocene: Decamethylferrocene or bis(pentamethylcyclopentadienyl)iron(II) is a chemical compound with formula Fe(C5(CH3)5)2 or C20H30Fe. It is a sandwich compound, whose molecule has an iron(II) cation Fe2+ attached by coordination bonds between two pentamethylcyclopentadienyl anions (Cp*−, (CH3)5C−5). It can also be viewed as a derivative of ferrocene, with a methyl group replacing each hydrogen atom of its cyclopentadienyl rings. The name and formula are often abbreviated to DmFc, Me10Fc or FeCp*2.This compound is a yellow crystalline solid that is used in chemical laboratories as a weak reductant. The iron(II) core is easily oxidized to iron(III), yielding the monovalent cation decamethylferrocenium, and even to higher oxidation states. Preparation: Decamethylferrocene is prepared in the same manner as ferrocene from pentamethylcyclopentadiene. This method can be used to produce other decamethylcyclopentadienyl sandwich compounds. 2 Li(C5Me5) + FeCl2 → Fe(C5Me5)2 + 2 LiClThe product can be purified by sublimation. FeCp*2 has staggered Cp* rings. The average distance between iron and each carbon is approximately 2.050 Å. This structure has been confirmed by X-ray crystallography. Redox reactions: Like ferrocene, decamethylferrocene forms a stable cation because Fe(II) is easily oxidized to Fe(III). Because of the electron donating methyl groups on the Cp* groups, decamethylferrocene is more reducing than is ferrocene. In a solution of acetonitrile the reduction potential for the [FeCp*2]+/0 couple is −0.59 V compared to a [FeCp2]0/+ reference (−0.48 V vs Fc/Fc+ in CH2Cl2). Oxygen is reduced to hydrogen peroxide by decamethylferrocene in acidic solution.Using powerful oxidants (e.g. SbF5 or AsF5 in SO2, or XeF+/Sb2F−11 in HF/SbF5) decamethylferrocene is oxidized to a stable dication with an iron(IV) core. In the Sb2F−11 salt, the Cp* rings are parallel. In contrast, a tilt angle of 17° between the Cp* rings is observed in the crystal structure of the SbF−6 salt.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**RoboCup Simulation League** RoboCup Simulation League: The RoboCup Simulation League is one of five soccer leagues within the RoboCup initiative.It is characterised by independently moving software players (agents) that play soccer on a virtual field inside a computer simulation. It is divided into four subleagues: 2D Soccer Simulation 3D Soccer Simulation 3D Development Mixed Reality Soccer Simulation (formerly called Visualisation) Differences between 2D and 3D simulations: The 2D simulation sub-league had its first release in early 1995 with version 0.1. It has been actively maintained since then with updates every few months. The ball and all players are represented as circles on the plane of the field. Their position is restricted to the two dimensions of the plane. SimSpark, the platform on top of which the 3D simulation sub-league is built, was registered with SourceForge in 2004. The platform itself is now well established with ongoing development. The ball and all players are represented as articulated rigid bodies within a system that enforces the simulation of physical properties such as mass, inertia and friction. Differences between 2D and 3D simulations: As of 2010, a direct comparison of the gameplay of the 2D and 3D leagues shows a marked difference. 2D league teams are generally exhibiting advanced strategies and teamwork, whereas 3D teams appear to struggle with the basics of stability and ambulation. This is partly due to the difference in age of the two leagues, and partly to the difference in complexity involved in building agents for the two leagues. Replaying log files of finals over the recent years shows progress is being made by many teams. Differences between 2D and 3D simulations: In the 2D system, movement around the plane is achieved via commands from the agents such as move, dash, turn and kick. The 3D system has fewer command choices for agents to send, but the mechanics of motion about the field are much more involved as the positions of 22 hinges throughout the articulated body must be simultaneously controlled.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Lagometer** Lagometer: A lagometer is a display of network latency on an Internet connection and of rendering by the client. Lagometers are commonly found in computer games or IRC where timing plays a large role. Quake and derived games commonly have them. Lagometer: Advanced lagometer consists of two lines – bottom and top. The bottom line advances one pixel per each snapshot received from server (by default they are being sent at 20 snapshots per second rate), while the top one advances one pixel per each frame that is rendered by client. Thus, if the machine framerate was 20 per second, both lines – top and bottom – would run at the same speed. Lagometer: Bottom bars correspond to delay before sending a snapshot by a server and receiving it by a client (so called "ping"). The shorter the bar, the smaller the ping was. Red bars mean that the frame has not arrived on time, yellow ones - that the snapshot was suppressed to stay under the rate limit. Top bars can be drawn in blue or in yellow. While server snapshots are usually received at lower rate as the client framerate, the software interpolates position and movements until it gets an update from a server, when it adjusts own state accordingly. Lagometer: The height of upper bars is proportional to the interpolated time between snapshots received (so as long as they come regularly, it stays below the "zero line" and is drawn in blue), or - if snapshots stop to arrive on time - is extrapolated after the last snapshot expected (then bars cross the "zero line" and are drawn in yellow). Lagometer: If those bars stay yellow for too long, client is forced to interpolate its frames beyond the "reasonable level" and finally, when the snapshot arrives, the prediction turns out to hardly correspond to the server-side version, which results in a jerky, non continuous movement of scenery (obviously lowering the quality of gameplay). Some games that use a "lagometer" will simply remove a player from the game if their lag is too high. In the game Minecraft, the lagometer is displayed on the debug screen, as a line graph that will go up when lag spikes. Use the following console commands for the following games:
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Russell 2000 Index** Russell 2000 Index: The Russell 2000 Index is a small-cap U.S. stock market index that makes up the smallest 2,000 stocks in the Russell 3000 Index. It was started by the Frank Russell Company in 1984. The index is maintained by FTSE Russell, a subsidiary of the London Stock Exchange Group (LSEG). Overview: The Russell 2000 is by far the most common benchmark for mutual funds that identify themselves as "small-cap", while the S&P 500 index is used primarily for large capitalization stocks. It is the most widely quoted measure of the overall performance of small-cap to mid-cap company shares. It is commonly considered an indicator of the U.S. economy due to its focus on small-cap companies in the U.S. market. The index represents approximately 10% of the total market capitalization of the Russell 3000 Index. As of 31 December 2022, the weighted average market capitalization of a company in the index is approximately $2.76 billion and the median market capitalization is approximately $950 million. The market capitalization of the largest company in the index is approximately $8.1 billion.It first traded above the 1,000 level on May 20, 2013, and above the 2,000 level on December 23, 2020. Overview: Similar small-cap indices include the S&P 600 from Standard & Poor's, which is less commonly used, along with those from other financial information providers. Investing: Many fund companies offer mutual funds and exchange-traded funds (ETFs) that attempt to replicate the performance of the Russell 2000. Their results will be affected by stock selection, trading expenses, and market impact of reacting to changes in the constituent companies of the index. It is not possible to invest directly in an index.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Sigma 150-600mm f/5-6.3 DG OS HSM lens** Sigma 150-600mm f/5-6.3 DG OS HSM lens: The Sigma APO 150-600mm F5-6.3 DG OS HSM lens is a super-telephoto lens produced by Sigma Corporation. Sigma 150-600mm f/5-6.3 DG OS HSM lens: It is actually a range of two slightly different lenses based on a common design: the Sports and Contemporary. Both lenses feature similar specifications, but there are some notable differences. The Sports model has better weather sealing, more lens elements, a larger size and weight and slightly better optical performance at towards the 600 mm end of its zoom range. The Contemporary model, on the other hand, is built to a cheaper price point but features similar performance. Its performance suffers a little more than the Sport model between 300-600 mm.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Urelement** Urelement: In set theory, a branch of mathematics, an urelement or ur-element (from the German prefix ur-, 'primordial') is an object that is not a set, but that may be an element of a set. It is also referred to as an atom or individual. Theory: There are several different but essentially equivalent ways to treat urelements in a first-order theory. One way is to work in a first-order theory with two sorts, sets and urelements, with a ∈ b only defined when b is a set. In this case, if U is an urelement, it makes no sense to say X∈U , although U∈X is perfectly legitimate. Theory: Another way is to work in a one-sorted theory with a unary relation used to distinguish sets and urelements. As non-empty sets contain members while urelements do not, the unary relation is only needed to distinguish the empty set from urelements. Note that in this case, the axiom of extensionality must be formulated to apply only to objects that are not urelements. Theory: This situation is analogous to the treatments of theories of sets and classes. Indeed, urelements are in some sense dual to proper classes: urelements cannot have members whereas proper classes cannot be members. Put differently, urelements are minimal objects while proper classes are maximal objects by the membership relation (which, of course, is not an order relation, so this analogy is not to be taken literally). Urelements in set theory: The Zermelo set theory of 1908 included urelements, and hence is a version now called ZFA or ZFCA (i.e. ZFA with axiom of choice). It was soon realized that in the context of this and closely related axiomatic set theories, the urelements were not needed because they can easily be modeled in a set theory without urelements. Thus, standard expositions of the canonical axiomatic set theories ZF and ZFC do not mention urelements (for an exception, see Suppes). Axiomatizations of set theory that do invoke urelements include Kripke–Platek set theory with urelements and the variant of Von Neumann–Bernays–Gödel set theory described by Mendelson. In type theory, an object of type 0 can be called an urelement; hence the name "atom". Urelements in set theory: Adding urelements to the system New Foundations (NF) to produce NFU has surprising consequences. In particular, Jensen proved the consistency of NFU relative to Peano arithmetic; meanwhile, the consistency of NF relative to anything remains an open problem, pending verification of Holmes's proof of its consistency relative to ZF. Moreover, NFU remains relatively consistent when augmented with an axiom of infinity and the axiom of choice. Meanwhile, the negation of the axiom of choice is, curiously, an NF theorem. Holmes (1998) takes these facts as evidence that NFU is a more successful foundation for mathematics than NF. Holmes further argues that set theory is more natural with than without urelements, since we may take as urelements the objects of any theory or of the physical universe. In finitist set theory, urelements are mapped to the lowest-level components of the target phenomenon, such as atomic constituents of a physical object or members of an organisation. Quine atoms: An alternative approach to urelements is to consider them, instead of as a type of object other than sets, as a particular type of set. Quine atoms (named after Willard Van Orman Quine) are sets that only contain themselves, that is, sets that satisfy the formula x = {x}.Quine atoms cannot exist in systems of set theory that include the axiom of regularity, but they can exist in non-well-founded set theory. ZF set theory with the axiom of regularity removed cannot prove that any non-well-founded sets exist (unless it is inconsistent, in which case it will prove any arbitrary statement), but it is compatible with the existence of Quine atoms. Aczel's anti-foundation axiom implies that there is a unique Quine atom. Other non-well-founded theories may admit many distinct Quine atoms; at the opposite end of the spectrum lies Boffa's axiom of superuniversality, which implies that the distinct Quine atoms form a proper class.Quine atoms also appear in Quine's New Foundations, which allows more than one such set to exist.Quine atoms are the only sets called reflexive sets by Peter Aczel, although other authors, e.g. Jon Barwise and Lawrence Moss, use the latter term to denote the larger class of sets with the property x ∈ x.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Mid-Atlantic Soft Matter Workshop** Mid-Atlantic Soft Matter Workshop: Mid-Atlantic Soft Matter Workshop or MASM is an interdisciplinary meeting on soft matter routinely hosted and participated in by research and educational organizations in the mid-Atlantic region of the United States. The workshop consists of several talks relating to the field of soft matter given by invited lecturers, and these talks are interspersed with sessions of short, three-minute "sound-bite" talks that can be delivered by any participant. History: MASM was started at Georgetown University and organized by Daniel Blair and Jeffrey Urbach of Georgetown University. There have been 16 MASM meetings. The 16th MASM meeting was hosted at National Institutes of Health (NIH) on July 29, 2015.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Discrete cosine transform** Discrete cosine transform: A discrete cosine transform (DCT) expresses a finite sequence of data points in terms of a sum of cosine functions oscillating at different frequencies. The DCT, first proposed by Nasir Ahmed in 1972, is a widely used transformation technique in signal processing and data compression. It is used in most digital media, including digital images (such as JPEG and HEIF), digital video (such as MPEG and H.26x), digital audio (such as Dolby Digital, MP3 and AAC), digital television (such as SDTV, HDTV and VOD), digital radio (such as AAC+ and DAB+), and speech coding (such as AAC-LD, Siren and Opus). DCTs are also important to numerous other applications in science and engineering, such as digital signal processing, telecommunication devices, reducing network bandwidth usage, and spectral methods for the numerical solution of partial differential equations. Discrete cosine transform: The use of cosine rather than sine functions is critical for compression since fewer cosine functions are needed to approximate a typical signal, whereas for differential equations the cosines express a particular choice of boundary conditions. In particular, a DCT is a Fourier-related transform similar to the discrete Fourier transform (DFT), but using only real numbers. The DCTs are generally related to Fourier series coefficients of a periodically and symmetrically extended sequence whereas DFTs are related to Fourier series coefficients of only periodically extended sequences. DCTs are equivalent to DFTs of roughly twice the length, operating on real data with even symmetry (since the Fourier transform of a real and even function is real and even), whereas in some variants the input or output data are shifted by half a sample. There are eight standard DCT variants, of which four are common. Discrete cosine transform: The most common variant of discrete cosine transform is the type-II DCT, which is often called simply the DCT. This was the original DCT as first proposed by Ahmed. Its inverse, the type-III DCT, is correspondingly often called simply the inverse DCT or the IDCT. Two related transforms are the discrete sine transform (DST), which is equivalent to a DFT of real and odd functions, and the modified discrete cosine transform (MDCT), which is based on a DCT of overlapping data. Multidimensional DCTs (MD DCTs) are developed to extend the concept of DCT to multidimensional signals. A variety of fast algorithms have been developed to reduce the computational complexity of implementing DCT. One of these is the integer DCT (IntDCT), an integer approximation of the standard DCT,: ix, xiii, 1, 141–304  used in several ISO/IEC and ITU-T international standards.DCT compression, also known as block compression, compresses data in sets of discrete DCT blocks. DCT blocks sizes including 8x8 pixels for the standard DCT, and varied integer DCT sizes between 4x4 and 32x32 pixels. The DCT has a strong energy compaction property, capable of achieving high quality at high data compression ratios. However, blocky compression artifacts can appear when heavy DCT compression is applied. History: The DCT was first conceived by Nasir Ahmed, T. Natarajan and K. R. Rao while working at Kansas State University. The concept was proposed to the National Science Foundation in 1972. The DCT was originally intended for image compression. Ahmed developed a practical DCT algorithm with his PhD students T. Raj Natarajan, Wills Dietrich, and Jeremy Fries, and his friend Dr. K. R. Rao at the University of Texas at Arlington in 1973. They presented their results in a January 1974 paper, titled Discrete Cosine Transform. It described what is now called the type-II DCT (DCT-II),: 51  as well as the type-III inverse DCT (IDCT).Since its introduction in 1974, there has been significant research on the DCT. In 1977, Wen-Hsiung Chen published a paper with C. Harrison Smith and Stanley C. Fralick presenting a fast DCT algorithm. Further developments include a 1978 paper by M. J. Narasimha and A. M. Peterson, and a 1984 paper by B. G. Lee. These research papers, along with the original 1974 Ahmed paper and the 1977 Chen paper, were cited by the Joint Photographic Experts Group as the basis for JPEG's lossy image compression algorithm in 1992.The discrete sine transform (DST) was derived from the DCT, by replacing the Neumann condition at x=0 with a Dirichlet condition.: 35-36  The DST was described in the 1974 DCT paper by Ahmed, Natarajan and Rao. A type-I DST (DST-I) was later described by Anil K. Jain in 1976, and a type-II DST (DST-II) was then described by H.B. Kekra and J.K. Solanka in 1978.In 1975, John A. Roese and Guner S. Robinson adapted the DCT for inter-frame motion-compensated video coding. They experimented with the DCT and the fast Fourier transform (FFT), developing inter-frame hybrid coders for both, and found that the DCT is the most efficient due to its reduced complexity, capable of compressing image data down to 0.25-bit per pixel for a videotelephone scene with image quality comparable to an intra-frame coder requiring 2-bit per pixel. In 1979, Anil K. Jain and Jaswant R. Jain further developed motion-compensated DCT video compression, also called block motion compensation. This led to Chen developing a practical video compression algorithm, called motion-compensated DCT or adaptive scene coding, in 1981. Motion-compensated DCT later became the standard coding technique for video compression from the late 1980s onwards.A DCT variant, the modified discrete cosine transform (MDCT), was developed by John P. Princen, A.W. Johnson and Alan B. Bradley at the University of Surrey in 1987, following earlier work by Princen and Bradley in 1986. The MDCT is used in most modern audio compression formats, such as Dolby Digital (AC-3), MP3 (which uses a hybrid DCT-FFT algorithm), Advanced Audio Coding (AAC), and Vorbis (Ogg).Nasir Ahmed also developed a lossless DCT algorithm with Giridhar Mandyam and Neeraj Magotra at the University of New Mexico in 1995. This allows the DCT technique to be used for lossless compression of images. It is a modification of the original DCT algorithm, and incorporates elements of inverse DCT and delta modulation. It is a more effective lossless compression algorithm than entropy coding. Lossless DCT is also known as LDCT. Applications: The DCT is the most widely used transformation technique in signal processing, and by far the most widely used linear transform in data compression. Uncompressed digital media as well as lossless compression have high memory and bandwidth requirements, which is significantly reduced by the DCT lossy compression technique, capable of achieving data compression ratios from 8:1 to 14:1 for near-studio-quality, up to 100:1 for acceptable-quality content. DCT compression standards are used in digital media technologies, such as digital images, digital photos, digital video, streaming media, digital television, streaming television, video on demand (VOD), digital cinema, high-definition video (HD video), and high-definition television (HDTV).The DCT, and in particular the DCT-II, is often used in signal and image processing, especially for lossy compression, because it has a strong "energy compaction" property: in typical applications, most of the signal information tends to be concentrated in a few low-frequency components of the DCT. For strongly correlated Markov processes, the DCT can approach the compaction efficiency of the Karhunen-Loève transform (which is optimal in the decorrelation sense). As explained below, this stems from the boundary conditions implicit in the cosine functions. Applications: DCTs are also widely employed in solving partial differential equations by spectral methods, where the different variants of the DCT correspond to slightly different even/odd boundary conditions at the two ends of the array. DCTs are also closely related to Chebyshev polynomials, and fast DCT algorithms (below) are used in Chebyshev approximation of arbitrary functions by series of Chebyshev polynomials, for example in Clenshaw–Curtis quadrature. The DCT is the coding standard for multimedia telecommunication devices. It is widely used for bit rate reduction, and reducing network bandwidth usage. DCT compression significantly reduces the amount of memory and bandwidth required for digital signals. General applications The DCT is widely used in many applications, which include the following. Applications: DCT visual media standards The DCT-II, also known as simply the DCT, is the most important image compression technique. It is used in image compression standards such as JPEG, and video compression standards such as H.26x, MJPEG, MPEG, DV, Theora and Daala. There, the two-dimensional DCT-II of N×N blocks are computed and the results are quantized and entropy coded. In this case, N is typically 8 and the DCT-II formula is applied to each row and column of the block. The result is an 8 × 8 transform coefficient array in which the (0,0) element (top-left) is the DC (zero-frequency) component and entries with increasing vertical and horizontal index values represent higher vertical and horizontal spatial frequencies. Applications: The integer DCT, an integer approximation of the DCT, is used in Advanced Video Coding (AVC), introduced in 2003, and High Efficiency Video Coding (HEVC), introduced in 2013. The integer DCT is also used in the High Efficiency Image Format (HEIF), which uses a subset of the HEVC video coding format for coding still images. AVC uses 4x4 and 8x8 blocks. HEVC and HEIF use varied block sizes between 4x4 and 32x32 pixels. As of 2019, AVC is by far the most commonly used format for the recording, compression and distribution of video content, used by 91% of video developers, followed by HEVC which is used by 43% of developers. Applications: Image formats Video formats MDCT audio standards General audio Speech coding MD DCT Multidimensional DCTs (MD DCTs) have several applications, mainly 3-D DCTs such as the 3-D DCT-II, which has several new applications like Hyperspectral Imaging coding systems, variable temporal length 3-D DCT coding, video coding algorithms, adaptive video coding and 3-D Compression. Due to enhancement in the hardware, software and introduction of several fast algorithms, the necessity of using M-D DCTs is rapidly increasing. DCT-IV has gained popularity for its applications in fast implementation of real-valued polyphase filtering banks, lapped orthogonal transform and cosine-modulated wavelet bases. Applications: Digital signal processing DCT plays a very important role in digital signal processing. By using the DCT, the signals can be compressed. DCT can be used in electrocardiography for the compression of ECG signals. DCT2 provides a better compression ratio than DCT. The DCT is widely implemented in digital signal processors (DSP), as well as digital signal processing software. Many companies have developed DSPs based on DCT technology. DCTs are widely used for applications such as encoding, decoding, video, audio, multiplexing, control signals, signaling, and analog-to-digital conversion. DCTs are also commonly used for high-definition television (HDTV) encoder/decoder chips. Applications: Compression artifacts A common issue with DCT compression in digital media are blocky compression artifacts, caused by DCT blocks. The DCT algorithm can cause block-based artifacts when heavy compression is applied. Due to the DCT being used in the majority of digital image and video coding standards (such as the JPEG, H.26x and MPEG formats), DCT-based blocky compression artifacts are widespread in digital media. In a DCT algorithm, an image (or frame in an image sequence) is divided into square blocks which are processed independently from each other, then the DCT of these blocks is taken, and the resulting DCT coefficients are quantized. This process can cause blocking artifacts, primarily at high data compression ratios. This can also cause the "mosquito noise" effect, commonly found in digital video (such as the MPEG formats).DCT blocks are often used in glitch art. The artist Rosa Menkman makes use of DCT-based compression artifacts in her glitch art, particularly the DCT blocks found in most digital media formats such as JPEG digital images and MP3 digital audio. Another example is Jpegs by German photographer Thomas Ruff, which uses intentional JPEG artifacts as the basis of the picture's style. Informal overview: Like any Fourier-related transform, discrete cosine transforms (DCTs) express a function or a signal in terms of a sum of sinusoids with different frequencies and amplitudes. Like the discrete Fourier transform (DFT), a DCT operates on a function at a finite number of discrete data points. The obvious distinction between a DCT and a DFT is that the former uses only cosine functions, while the latter uses both cosines and sines (in the form of complex exponentials). However, this visible difference is merely a consequence of a deeper distinction: a DCT implies different boundary conditions from the DFT or other related transforms. Informal overview: The Fourier-related transforms that operate on a function over a finite domain, such as the DFT or DCT or a Fourier series, can be thought of as implicitly defining an extension of that function outside the domain. That is, once you write a function f(x) as a sum of sinusoids, you can evaluate that sum at any x , even for x where the original f(x) was not specified. The DFT, like the Fourier series, implies a periodic extension of the original function. A DCT, like a cosine transform, implies an even extension of the original function. Informal overview: However, because DCTs operate on finite, discrete sequences, two issues arise that do not apply for the continuous cosine transform. First, one has to specify whether the function is even or odd at both the left and right boundaries of the domain (i.e. the min-n and max-n boundaries in the definitions below, respectively). Second, one has to specify around what point the function is even or odd. In particular, consider a sequence abcd of four equally spaced data points, and say that we specify an even left boundary. There are two sensible possibilities: either the data are even about the sample a, in which case the even extension is dcbabcd, or the data are even about the point halfway between a and the previous point, in which case the even extension is dcbaabcd (a is repeated). Informal overview: These choices lead to all the standard variations of DCTs and also discrete sine transforms (DSTs). Each boundary can be either even or odd (2 choices per boundary) and can be symmetric about a data point or the point halfway between two data points (2 choices per boundary), for a total of 2 × 2 × 2 × 2 = 16 possibilities. Half of these possibilities, those where the left boundary is even, correspond to the 8 types of DCT; the other half are the 8 types of DST. Informal overview: These different boundary conditions strongly affect the applications of the transform and lead to uniquely useful properties for the various DCT types. Most directly, when using Fourier-related transforms to solve partial differential equations by spectral methods, the boundary conditions are directly specified as a part of the problem being solved. Or, for the MDCT (based on the type-IV DCT), the boundary conditions are intimately involved in the MDCT's critical property of time-domain aliasing cancellation. In a more subtle fashion, the boundary conditions are responsible for the "energy compactification" properties that make DCTs useful for image and audio compression, because the boundaries affect the rate of convergence of any Fourier-like series. Informal overview: In particular, it is well known that any discontinuities in a function reduce the rate of convergence of the Fourier series, so that more sinusoids are needed to represent the function with a given accuracy. The same principle governs the usefulness of the DFT and other transforms for signal compression; the smoother a function is, the fewer terms in its DFT or DCT are required to represent it accurately, and the more it can be compressed. (Here, we think of the DFT or DCT as approximations for the Fourier series or cosine series of a function, respectively, in order to talk about its "smoothness".) However, the implicit periodicity of the DFT means that discontinuities usually occur at the boundaries: any random segment of a signal is unlikely to have the same value at both the left and right boundaries. (A similar problem arises for the DST, in which the odd left boundary condition implies a discontinuity for any function that does not happen to be zero at that boundary.) In contrast, a DCT where both boundaries are even always yields a continuous extension at the boundaries (although the slope is generally discontinuous). This is why DCTs, and in particular DCTs of types I, II, V, and VI (the types that have two even boundaries) generally perform better for signal compression than DFTs and DSTs. In practice, a type-II DCT is usually preferred for such applications, in part for reasons of computational convenience. Formal definition: Formally, the discrete cosine transform is a linear, invertible function f:RN→RN (where R denotes the set of real numbers), or equivalently an invertible N × N square matrix. There are several variants of the DCT with slightly modified definitions. The N real numbers x0,…xN−1 are transformed into the N real numbers X0,…,XN−1 according to one of the formulas: DCT-I cos for k=0,…N−1. Formal definition: Some authors further multiply the x0 and xN−1 terms by 2, and correspondingly multiply the X0 and XN−1 terms by 1/2, which makes the DCT-I matrix orthogonal, if one further multiplies by an overall scale factor of 2N−1, but breaks the direct correspondence with a real-even DFT. Formal definition: The DCT-I is exactly equivalent (up to an overall scale factor of 2), to a DFT of 2(N−1) real numbers with even symmetry. For example, a DCT-I of N=5 real numbers abcde is exactly equivalent to a DFT of eight real numbers abcdedcb (even symmetry), divided by two. (In contrast, DCT types II-IV involve a half-sample shift in the equivalent DFT.) Note, however, that the DCT-I is not defined for N less than 2, while all other DCT types are defined for any positive N. Formal definition: Thus, the DCT-I corresponds to the boundary conditions: xn is even around n=0 and even around n=N−1 ; similarly for Xk. DCT-II cos for k=0,…N−1. Formal definition: The DCT-II is probably the most commonly used form, and is often simply referred to as "the DCT".This transform is exactly equivalent (up to an overall scale factor of 2) to a DFT of 4N real inputs of even symmetry where the even-indexed elements are zero. That is, it is half of the DFT of the 4N inputs yn, where y2n=0, y2n+1=xn for 0≤n<N, y2N=0, and y4N−n=yn for 0<n<2N. Formal definition: DCT-II transformation is also possible using 2N signal followed by a multiplication by half shift. This is demonstrated by Makhoul. Formal definition: Some authors further multiply the X0 term by 1/N and multiply the rest of the matrix by an overall scale factor of {\textstyle {\sqrt {{2}/{N}}}} (see below for the corresponding change in DCT-III). This makes the DCT-II matrix orthogonal, but breaks the direct correspondence with a real-even DFT of half-shifted input. This is the normalization used by Matlab, for example, see. In many applications, such as JPEG, the scaling is arbitrary because scale factors can be combined with a subsequent computational step (e.g. the quantization step in JPEG), and a scaling can be chosen that allows the DCT to be computed with fewer multiplications.The DCT-II implies the boundary conditions: xn is even around n=−1/2 and even around n=N−1/2; Xk is even around k=0 and odd around k=N. Formal definition: Because it is the inverse of DCT-II up to a scale factor (see below), this form is sometimes simply referred to as "the inverse DCT" ("IDCT").Some authors divide the x0 term by 2 instead of by 2 (resulting in an overall x0/2 term) and multiply the resulting matrix by an overall scale factor of {\textstyle {\sqrt {2/N}}} (see above for the corresponding change in DCT-II), so that the DCT-II and DCT-III are transposes of one another. This makes the DCT-III matrix orthogonal, but breaks the direct correspondence with a real-even DFT of half-shifted output. Formal definition: The DCT-III implies the boundary conditions: xn is even around n=0 and odd around n=N; Xk is even around k=−1/2 and even around 2. DCT-IV cos for k=0,…N−1. Formal definition: The DCT-IV matrix becomes orthogonal (and thus, being clearly symmetric, its own inverse) if one further multiplies by an overall scale factor of {\textstyle {\sqrt {2/N}}.} A variant of the DCT-IV, where data from different transforms are overlapped, is called the modified discrete cosine transform (MDCT).The DCT-IV implies the boundary conditions: xn is even around n=−1/2 and odd around n=N−1/2; similarly for Xk. Formal definition: DCT V-VIII DCTs of types I–IV treat both boundaries consistently regarding the point of symmetry: they are even/odd around either a data point for both boundaries or halfway between two data points for both boundaries. By contrast, DCTs of types V-VIII imply boundaries that are even/odd around a data point for one boundary and halfway between two data points for the other boundary. Formal definition: In other words, DCT types I–IV are equivalent to real-even DFTs of even order (regardless of whether N is even or odd), since the corresponding DFT is of length 2(N−1) (for DCT-I) or 4N (for DCT-II & III) or 8N (for DCT-IV). The four additional types of discrete cosine transform correspond essentially to real-even DFTs of logically odd order, which have factors of N±1/2 in the denominators of the cosine arguments. Formal definition: However, these variants seem to be rarely used in practice. One reason, perhaps, is that FFT algorithms for odd-length DFTs are generally more complicated than FFT algorithms for even-length DFTs (e.g. the simplest radix-2 algorithms are only for even lengths), and this increased intricacy carries over to the DCTs as described below. (The trivial real-even array, a length-one DFT (odd length) of a single number a , corresponds to a DCT-V of length 1. Inverse transforms: Using the normalization conventions above, the inverse of DCT-I is DCT-I multiplied by 2/(N − 1). The inverse of DCT-IV is DCT-IV multiplied by 2/N. The inverse of DCT-II is DCT-III multiplied by 2/N and vice versa.Like for the DFT, the normalization factor in front of these transform definitions is merely a convention and differs between treatments. For example, some authors multiply the transforms by 2 / N {\textstyle {\sqrt {2/N}}} so that the inverse does not require any additional multiplicative factor. Combined with appropriate factors of √2 (see above), this can be used to make the transform matrix orthogonal. Multidimensional DCTs: Multidimensional variants of the various DCT types follow straightforwardly from the one-dimensional definitions: they are simply a separable product (equivalently, a composition) of DCTs along each dimension. M-D DCT-II For example, a two-dimensional DCT-II of an image or a matrix is simply the one-dimensional DCT-II, from above, performed along the rows and then along the columns (or vice versa). That is, the 2D DCT-II is given by the formula (omitting normalization and other scale factors, as above): cos cos cos cos ⁡[πN2(n2+12)k2]. Multidimensional DCTs: The inverse of a multi-dimensional DCT is just a separable product of the inverses of the corresponding one-dimensional DCTs (see above), e.g. the one-dimensional inverses applied along one dimension at a time in a row-column algorithm.The 3-D DCT-II is only the extension of 2-D DCT-II in three dimensional space and mathematically can be calculated by the formula cos cos cos for 1. Multidimensional DCTs: The inverse of 3-D DCT-II is 3-D DCT-III and can be computed from the formula given by cos cos cos for 1. Multidimensional DCTs: Technically, computing a two-, three- (or -multi) dimensional DCT by sequences of one-dimensional DCTs along each dimension is known as a row-column algorithm. As with multidimensional FFT algorithms, however, there exist other methods to compute the same thing while performing the computations in a different order (i.e. interleaving/combining the algorithms for the different dimensions). Owing to the rapid growth in the applications based on the 3-D DCT, several fast algorithms are developed for the computation of 3-D DCT-II. Vector-Radix algorithms are applied for computing M-D DCT to reduce the computational complexity and to increase the computational speed. To compute 3-D DCT-II efficiently, a fast algorithm, Vector-Radix Decimation in Frequency (VR DIF) algorithm was developed. Multidimensional DCTs: 3-D DCT-II VR DIF In order to apply the VR DIF algorithm the input data is to be formulated and rearranged as follows. The transform size N × N × N is assumed to be 2. Multidimensional DCTs: x~(n1,n2,n3)=x(2n1,2n2,2n3)x~(n1,n2,N−n3−1)=x(2n1,2n2,2n3+1)x~(n1,N−n2−1,n3)=x(2n1,2n2+1,2n3)x~(n1,N−n2−1,N−n3−1)=x(2n1,2n2+1,2n3+1)x~(N−n1−1,n2,n3)=x(2n1+1,2n2,2n3)x~(N−n1−1,n2,N−n3−1)=x(2n1+1,2n2,2n3+1)x~(N−n1−1,N−n2−1,n3)=x(2n1+1,2n2+1,2n3)x~(N−n1−1,N−n2−1,N−n3−1)=x(2n1+1,2n2+1,2n3+1) where 0≤n1,n2,n3≤N2−1 The figure to the adjacent shows the four stages that are involved in calculating 3-D DCT-II using VR DIF algorithm. The first stage is the 3-D reordering using the index mapping illustrated by the above equations. The second stage is the butterfly calculation. Each butterfly calculates eight points together as shown in the figure just below, where cos ⁡(φi) The original 3-D DCT-II now can be written as cos cos cos ⁡(φk3) where and 3. Multidimensional DCTs: If the even and the odd parts of k1,k2 and k3 and are considered, the general formula for the calculation of the 3-D DCT-II can be expressed as cos cos cos ⁡(φ(2k3+l)) where x~ijl(n1,n2,n3)=x~(n1,n2,n3)+(−1)lx~(n1,n2,n3+n2) +(−1)jx~(n1,n2+n2,n3)+(−1)j+lx~(n1,n2+n2,n3+n2) +(−1)ix~(n1+n2,n2,n3)+(−1)i+jx~(n1+n2+n2,n2,n3) +(−1)i+lx~(n1+n2,n2,n3+n3) where or 1. Multidimensional DCTs: Arithmetic complexity The whole 3-D DCT calculation needs log 2⁡N] stages, and each stage involves 18N3 butterflies. The whole 3-D DCT requires log 2⁡N] butterflies to be computed. Each butterfly requires seven real multiplications (including trivial multiplications) and 24 real additions (including trivial additions). Therefore, the total number of real multiplications needed for this stage is log 2⁡N], and the total number of real additions i.e. including the post-additions (recursive additions) which can be calculated directly after the butterfly stage or after the bit-reverse stage are given by log Real log Recursive log 2⁡N−3N3+3N2]. Multidimensional DCTs: The conventional method to calculate MD-DCT-II is using a Row-Column-Frame (RCF) approach which is computationally complex and less productive on most advanced recent hardware platforms. The number of multiplications required to compute VR DIF Algorithm when compared to RCF algorithm are quite a few in number. The number of Multiplications and additions involved in RCF approach are given by log 2⁡N] and log 2⁡N−3N3+3N2], respectively. From Table 1, it can be seen that the total number of multiplications associated with the 3-D DCT VR algorithm is less than that associated with the RCF approach by more than 40%. In addition, the RCF approach involves matrix transpose and more indexing and data swapping than the new VR algorithm. This makes the 3-D DCT VR algorithm more efficient and better suited for 3-D applications that involve the 3-D DCT-II such as video compression and other 3-D image processing applications. Multidimensional DCTs: The main consideration in choosing a fast algorithm is to avoid computational and structural complexities. As the technology of computers and DSPs advances, the execution time of arithmetic operations (multiplications and additions) is becoming very fast, and regular computational structure becomes the most important factor. Therefore, although the above proposed 3-D VR algorithm does not achieve the theoretical lower bound on the number of multiplications, it has a simpler computational structure as compared to other 3-D DCT algorithms. It can be implemented in place using a single butterfly and possesses the properties of the Cooley–Tukey FFT algorithm in 3-D. Hence, the 3-D VR presents a good choice for reducing arithmetic operations in the calculation of the 3-D DCT-II, while keeping the simple structure that characterize butterfly-style Cooley–Tukey FFT algorithms. Multidimensional DCTs: The image to the right shows a combination of horizontal and vertical frequencies for an 8 × 8 (N1=N2=8) two-dimensional DCT. Each step from left to right and top to bottom is an increase in frequency by 1/2 cycle. For example, moving right one from the top-left square yields a half-cycle increase in the horizontal frequency. Another move to the right yields two half-cycles. A move down yields two half-cycles horizontally and a half-cycle vertically. The source data ( 8×8 ) is transformed to a linear combination of these 64 frequency squares. MD-DCT-IV The M-D DCT-IV is just an extension of 1-D DCT-IV on to M dimensional domain. The 2-D DCT-IV of a matrix or an image is given by cos cos ⁡((2n+1)(2ℓ+1)π4M), for k=0,1,2…N−1 and ℓ=0,1,2,…M−1. We can compute the MD DCT-IV using the regular row-column method or we can use the polynomial transform method for the fast and efficient computation. The main idea of this algorithm is to use the Polynomial Transform to convert the multidimensional DCT into a series of 1-D DCTs directly. MD DCT-IV also has several applications in various fields. Computation: Although the direct application of these formulas would require O(N2) operations, it is possible to compute the same thing with only log ⁡N) complexity by factorizing the computation similarly to the fast Fourier transform (FFT). One can also compute DCTs via FFTs combined with O(N) pre- and post-processing steps. In general, log ⁡N) methods to compute DCTs are known as fast cosine transform (FCT) algorithms. Computation: The most efficient algorithms, in principle, are usually those that are specialized directly for the DCT, as opposed to using an ordinary FFT plus O(N) extra operations (see below for an exception). However, even "specialized" DCT algorithms (including all of those that achieve the lowest known arithmetic counts, at least for power-of-two sizes) are typically closely related to FFT algorithms – since DCTs are essentially DFTs of real-even data, one can design a fast DCT algorithm by taking an FFT and eliminating the redundant operations due to this symmetry. This can even be done automatically (Frigo & Johnson 2005). Algorithms based on the Cooley–Tukey FFT algorithm are most common, but any other FFT algorithm is also applicable. For example, the Winograd FFT algorithm leads to minimal-multiplication algorithms for the DFT, albeit generally at the cost of more additions, and a similar algorithm was proposed by (Feig & Winograd 1992a) for the DCT. Because the algorithms for DFTs, DCTs, and similar transforms are all so closely related, any improvement in algorithms for one transform will theoretically lead to immediate gains for the other transforms as well (Duhamel & Vetterli 1990). Computation: While DCT algorithms that employ an unmodified FFT often have some theoretical overhead compared to the best specialized DCT algorithms, the former also have a distinct advantage: Highly optimized FFT programs are widely available. Thus, in practice, it is often easier to obtain high performance for general lengths N with FFT-based algorithms. Computation: Specialized DCT algorithms, on the other hand, see widespread use for transforms of small, fixed sizes such as the 8 × 8 DCT-II used in JPEG compression, or the small DCTs (or MDCTs) typically used in audio compression. (Reduced code size may also be a reason to use a specialized DCT for embedded-device applications.) In fact, even the DCT algorithms using an ordinary FFT are sometimes equivalent to pruning the redundant operations from a larger FFT of real-symmetric data, and they can even be optimal from the perspective of arithmetic counts. For example, a type-II DCT is equivalent to a DFT of size 4N with real-even symmetry whose even-indexed elements are zero. One of the most common methods for computing this via an FFT (e.g. the method used in FFTPACK and FFTW) was described by Narasimha & Peterson (1978) and Makhoul (1980), and this method in hindsight can be seen as one step of a radix-4 decimation-in-time Cooley–Tukey algorithm applied to the "logical" real-even DFT corresponding to the DCT-II. Computation: Because the even-indexed elements are zero, this radix-4 step is exactly the same as a split-radix step. If the subsequent size N real-data FFT is also performed by a real-data split-radix algorithm (as in Sorensen et al. (1987)), then the resulting algorithm actually matches what was long the lowest published arithmetic count for the power-of-two DCT-II ( log 2⁡N−N+2 real-arithmetic operations). Computation: A recent reduction in the operation count to 17 log 2⁡N+O(N) also uses a real-data FFT. So, there is nothing intrinsically bad about computing the DCT via an FFT from an arithmetic perspective – it is sometimes merely a question of whether the corresponding FFT algorithm is optimal. (As a practical matter, the function-call overhead in invoking a separate FFT routine might be significant for small N, but this is an implementation rather than an algorithmic question since it can be solved by unrolling or inlining.) Example of IDCT: Consider this 8x8 grayscale image of capital letter A. Each basis function is multiplied by its coefficient and then this product is added to the final image.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Monocytopenia** Monocytopenia: Monocytopenia is a form of leukopenia associated with a deficiency of monocytes. It has been proposed as a measure during chemotherapy to predict neutropenia, though some research indicates that it is less effective than lymphopenia. Causes: The causes of monocytopenia include: acute infections, stress, treatment with glucocorticoids, aplastic anemia, hairy cell leukemia, acute myeloid leukemia, treatment with myelotoxic drugs and genetic syndromes, as for example MonoMAC syndrome. Diagnosis: - Blood Test (CBC) (Normal range of Monocytes: 1-10%) (Normal range in males: 0.2-0.8 x 10 3 /microliter)- Blood test checking for monocytopenia (Abnormal ranges: <1%) (Abnormal range in males: <0.2 x 10 3 /microliter)
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Shc (shell script compiler)** Shc (shell script compiler): shc is a shell script compiler for Unix-like operating systems written in the C programming language. The Shell Script Compiler (SHC) encodes and encrypts shell scripts into executable binaries. Compiling shell scripts into binaries provides protection against accidental changes and source code modification, and is a way of hiding shell script source code. Mechanism: shc takes a shell script which is specified on the command line by the -f option and produces a C source code of the script with added encryption. The generated source code is then compiled and linked to produce a binary executable. It is a two step process where, first, it creates a filename.x.c file of the shell script file filename. Then it is compiled with cc -$CFLAGS filename.x.c to create the binary from the C source code with the default C compiler.The compiled binary will still be dependent on the shell specified in the shebang (eg. #!/bin/sh), thus shc does not create completely independent binaries.shc itself is not a compiler such as the C compiler, it rather encodes and encrypts a shell script and generates C source code with the added expiration capability. It then uses the system C compiler to compile the source shell script and build a stripped binary which behaves exactly like the original script. Upon execution, the compiled binary will decrypt and execute the code with the shells'-c option.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Desktop environment** Desktop environment: In computing, a desktop environment (DE) is an implementation of the desktop metaphor made of a bundle of programs running on top of a computer operating system that share a common graphical user interface (GUI), sometimes described as a graphical shell. The desktop environment was seen mostly on personal computers until the rise of mobile computing. Desktop GUIs help the user to easily access and edit files, while they usually do not provide access to all of the features found in the underlying operating system. Instead, the traditional command-line interface (CLI) is still used when full control over the operating system is required. Desktop environment: A desktop environment typically consists of icons, windows, toolbars, folders, wallpapers and desktop widgets (see Elements of graphical user interfaces and WIMP). A GUI might also provide drag and drop functionality and other features that make the desktop metaphor more complete. A desktop environment aims to be an intuitive way for the user to interact with the computer using concepts which are similar to those used when interacting with the physical world, such as buttons and windows. Desktop environment: While the term desktop environment originally described a style of user interfaces following the desktop metaphor, it has also come to describe the programs that realize the metaphor itself. This usage has been popularized by projects such as the Common Desktop Environment, K Desktop Environment, and GNOME. Implementation: On a system that offers a desktop environment, a window manager in conjunction with applications written using a widget toolkit are generally responsible for most of what the user sees. The window manager supports the user interactions with the environment, while the toolkit provides developers a software library for applications with a unified look and behavior. Implementation: A windowing system of some sort generally interfaces directly with the underlying operating system and libraries. This provides support for graphical hardware, pointing devices, and keyboards. The window manager generally runs on top of this windowing system. While the windowing system may provide some window management functionality, this functionality is still considered to be part of the window manager, which simply happens to have been provided by the windowing system. Implementation: Applications that are created with a particular window manager in mind usually make use of a windowing toolkit, generally provided with the operating system or window manager. A windowing toolkit gives applications access to widgets that allow the user to interact graphically with the application in a consistent way. History and common use: The first desktop environment was created by Xerox and was sold with the Xerox Alto in the 1970s. The Alto was generally considered by Xerox to be a personal office computer; it failed in the marketplace because of poor marketing and a very high price tag. With the Lisa, Apple introduced a desktop environment on an affordable personal computer, which also failed in the market. History and common use: The desktop metaphor was popularized on commercial personal computers by the original Macintosh from Apple in 1984, and was popularized further by Windows from Microsoft since the 1990s. As of 2014, the most popular desktop environments are descendants of these earlier environments, including the Windows shell used in Microsoft Windows, and the Aqua environment used in macOS. When compared with the X-based desktop environments available for Unix-like operating systems such as Linux and BSD, the proprietary desktop environments included with Windows and macOS have relatively fixed layouts and static features, with highly integrated "seamless" designs that aim to provide mostly consistent customer experiences across installations. History and common use: Microsoft Windows dominates in marketshare among personal computers with a desktop environment. Computers using Unix-like operating systems such as macOS, ChromeOS, Linux, BSD or Solaris are much less common; however, as of 2015 there is a growing market for low-cost Linux PCs using the X Window System or Wayland with a broad choice of desktop environments. Among the more popular of these are Google's Chromebooks and Chromeboxes, Intel's NUC, the Raspberry Pi, etc.On tablets and smartphones, the situation is the opposite, with Unix-like operating systems dominating the market, including the iOS (BSD-derived), Android, Tizen, Sailfish and Ubuntu (all Linux-derived). Microsoft's Windows phone, Windows RT and Windows 10 are used on a much smaller number of tablets and smartphones. However, the majority of Unix-like operating systems dominant on handheld devices do not use the X11 desktop environments used by other Unix-like operating systems, relying instead on interfaces based on other technologies. Desktop environments for the X Window System: On systems running the X Window System (typically Unix-family systems such as Linux, the BSDs, and formal UNIX distributions), desktop environments are much more dynamic and customizable to meet user needs. In this context, a desktop environment typically consists of several separate components, including a window manager (such as Mutter or KWin), a file manager (such as Files or Dolphin), a set of graphical themes, together with toolkits (such as GTK+ and Qt) and libraries for managing the desktop. All these individual modules can be exchanged and independently configured to suit users, but most desktop environments provide a default configuration that works with minimal user setup. Desktop environments for the X Window System: Some window managers‍—‌such as IceWM, Fluxbox, Openbox, ROX Desktop and Window Maker‍—‌contain relatively sparse desktop environment elements, such as an integrated spatial file manager, while others like evilwm and wmii do not provide such elements. Not all of the program code that is part of a desktop environment has effects which are directly visible to the user. Some of it may be low-level code. KDE, for example, provides so-called KIO slaves which give the user access to a wide range of virtual devices. These I/O slaves are not available outside the KDE environment. Desktop environments for the X Window System: In 1996 the KDE was announced, followed in 1997 by the announcement of GNOME. Xfce is a smaller project that was also founded in 1996, and focuses on speed and modularity, just like LXDE which was started in 2006. A comparison of X Window System desktop environments demonstrates the differences between environments. GNOME and KDE were usually seen as dominant solutions, and these are still often installed by default on Linux systems. Each of them offers: To programmers, a set of standard APIs, a programming environment, and human interface guidelines. Desktop environments for the X Window System: To translators, a collaboration infrastructure. KDE and GNOME are available in many languages. To artists, a workspace to share their talents. To ergonomics specialists, the chance to help simplify the working environment. To developers of third-party applications, a reference environment for integration. OpenOffice.org is one such application. Desktop environments for the X Window System: To users, a complete desktop environment and a suite of essential applications. These include a file manager, web browser, multimedia player, email client, address book, PDF reader, photo manager, and system preferences application.In the early 2000s, KDE reached maturity. The Appeal and ToPaZ projects focused on bringing new advances to the next major releases of both KDE and GNOME respectively. Although striving for broadly similar goals, GNOME and KDE do differ in their approach to user ergonomics. KDE encourages applications to integrate and interoperate, is highly customizable, and contains many complex features, all whilst trying to establish sensible defaults. GNOME on the other hand is more prescriptive, and focuses on the finer details of essential tasks and overall simplification. Accordingly, each one attracts a different user and developer community. Technically, there are numerous technologies common to all Unix-like desktop environments, most obviously the X Window System. Accordingly, the freedesktop.org project was established as an informal collaboration zone with the goal being to reduce duplication of effort. Desktop environments for the X Window System: As GNOME and KDE focus on high-performance computers, users of less powerful or older computers often prefer alternative desktop environments specifically created for low-performance systems. Most commonly used lightweight desktop environments include LXDE and Xfce; they both use GTK+, which is the same underlying toolkit GNOME uses. The MATE desktop environment, a fork of GNOME 2, is comparable to Xfce in its use of RAM and processor cycles, but is often considered more as an alternative to other lightweight desktop environments. Desktop environments for the X Window System: For a while, GNOME and KDE enjoyed the status of the most popular Linux desktop environments; later, other desktop environments grew in popularity. In April 2011, GNOME introduced a new interface concept with its version 3, while a popular Linux distribution Ubuntu introduced its own new desktop environment, Unity. Some users preferred to keep the traditional interface concept of GNOME 2, resulting in the creation of MATE as a GNOME 2 fork. Examples of desktop environments: The most common desktop environment on personal computers is Windows Shell in Microsoft Windows. Microsoft has made significant efforts in making Windows shell visually pleasing. As a result, Microsoft has introduced theme support in Windows 98, the various Windows XP visual styles, the Aero brand in Windows Vista, the Microsoft design language (codenamed "Metro") in Windows 8, and the Fluent Design System and Windows Spotlight in Windows 10. Windows shell can be extended via Shell extensions. Examples of desktop environments: Mainstream desktop environments for Unix-like operating systems use the X Window System, and include KDE, GNOME, Xfce, LXDE, and Aqua, any of which may be selected by users and are not tied exclusively to the operating system in use. Examples of desktop environments: A number of other desktop environments also exist, including (but not limited to) CDE, EDE, GEM, IRIX Interactive Desktop, Sun's Java Desktop System, Jesktop, Mezzo, Project Looking Glass, ROX Desktop, UDE, Xito, XFast. Moreover, there exists FVWM-Crystal, which consists of a powerful configuration for the FVWM window manager, a theme and further adds, altogether forming a "construction kit" for building up a desktop environment. Examples of desktop environments: X window managers that are meant to be usable stand-alone — without another desktop environment — also include elements reminiscent of those found in typical desktop environments, most prominently Enlightenment. Other examples include OpenBox, Fluxbox, WindowLab, Fvwm, as well as Window Maker and AfterStep, which both feature the NeXTSTEP GUI look and feel. However newer versions of some operating systems make self configure. Examples of desktop environments: The Amiga approach to desktop environment was noteworthy: the original Workbench desktop environment in AmigaOS evolved through time to originate an entire family of descendants and alternative desktop solutions. Some of those descendants are the Scalos, the Ambient desktop of MorphOS, and the Wanderer desktop of the AROS open source OS. WindowLab also contains features reminiscent of the Amiga UI. Third-party Directory Opus software, which was originally just a navigational file manager program, evolved to become a complete Amiga desktop replacement called Directory Opus Magellan. Examples of desktop environments: OS/2 (and derivatives such as eComStation and ArcaOS) use the Workplace Shell. Earlier versions of OS/2 used the Presentation Manager. The BumpTop project was an experimental desktop environment. Its main objective is to replace the 2D paradigm with a "real-world" 3D implementation, where documents can be freely manipulated across a virtual table. Gallery
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**SPIM** SPIM: SPIM is a MIPS processor simulator, designed to run assembly language code for this architecture. The program simulates R2000 and R3000 processors, and was written by James R. Larus while a professor at the University of Wisconsin–Madison. The MIPS machine language is often taught in college-level assembly courses, especially those using the textbook Computer Organization and Design: The Hardware/Software Interface by David A. Patterson and John L. Hennessy (ISBN 1-55860-428-6). SPIM: The name of the simulator is a reversal of the letters "MIPS". SPIM simulators are available for Windows (PCSpim), Mac OS X and Unix/Linux-based (xspim) operating systems. As of release 8.0 in January 2010, the simulator is licensed under the standard BSD license. SPIM: In January, 2011, a major release version 9.0 features QtSpim that has a new user interface built on the cross-platform Qt UI framework and runs on Windows, Linux, and macOS. From this version, the project has also been moved to SourceForge for better maintenance. Precompiled versions of QtSpim for Linux (32-bit), Windows, and Mac OS X, as well as PCSpim for Windows are provided. The SPIM operating system: The SPIM simulator comes with a rudimentary operating system, which allows the programmer usage of common used functions in a comfortable way. Such functions are invoked by the syscall-instruction. Then the OS acts depending on the values of specific registers. The SPIM OS expects a label named main as a handover point from the OS-preamble. SPIM Alternatives/Competitors: MARS (MIPS Assembler and Runtime Simulator) is a Java-based IDE for the MIPS Assembly Programming Language and an alternative to SPIM. Its initial release was in 2005 and is under active development.Imperas is a suite of embedded software development tools for MIPS architecture which uses Just-in-time compilation emulation and simulation technology. The simulator was initially released in 2008 and is under active development. There are over 30 open source models of the MIPS 32 bit and 64 bit cores. Other alternative to SPIM for educational purposes is The CREATOR simulator. CREATOR is portable (can be executed in current web browsers) and allow students to learn several assembly languages of different processors at the same time (CREATOR includes examples of MIPS32 and RISC-V instructions).
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Carbon tetraiodide** Carbon tetraiodide: Carbon tetraiodide is a tetrahalomethane with the molecular formula CI4. Being bright red, it is a relatively rare example of a highly colored methane derivative. It is only 2.3% by weight carbon, although other methane derivatives are known with still less carbon. Structure: The tetrahedral molecule features C-I distances of 2.12 ± 0.02 Å. The molecule is slightly crowded with short contacts between iodine atoms of 3.459 ± 0.03 Å, and possibly for this reason, it is thermally and photochemically unstable. Carbon tetraiodide crystallizes in tetragonal crystal structure (a 6.409, c 9.558 (.10−1 nm)).It has zero dipole moment due to its symmetrically substituted tetrahedral geometry. Properties, synthesis, uses: Carbon tetraiodide is slightly reactive towards water, giving iodoform and I2. It is soluble in nonpolar organic solvents. It decomposes thermally and photochemically to tetraiodoethylene, C2I4. Its synthesis entails AlCl3-catalyzed halide exchange, which is conducted at room temperature: CCl EtI CI EtCl The product crystallizes from the reaction solution. Carbon tetraiodide is used as an iodination reagent, often upon reaction with bases. Ketones are converted to 1,1-diiodoalkenes upon treatment with triphenylphosphine (PPh3) and carbon tetraiodide. Alcohols are converted in and to iodide, by a mechanism similar to the Appel reaction. In an Appel reaction, carbon tetrachloride is used to generate alkyl chlorides from alcohols. Safety considerations: Manufacturers recommend that carbon tetraiodide be stored near 0 °C (32 °F). As a ready source of iodine, it is an irritant. Its LD50 on rats is 18 mg/kg. In general, perhalogenated organic compounds should be considered toxic, with the narrow exception of small perfluoroalkanes (essentially inert due to the strength of the C-F bond).
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Asystole** Asystole: Asystole (New Latin, from Greek privative a "not, without" + systolē "contraction") is the absence of ventricular contractions in the context of a lethal heart arrhythmia (in contrast to an induced asystole on a cooled patient on a heart-lung machine and general anesthesia during surgery necessitating stopping the heart). Asystole is the most serious form of cardiac arrest and is usually irreversible. Also referred to as cardiac flatline, asystole is the state of total cessation of electrical activity from the heart, which means no tissue contraction from the heart muscle and therefore no blood flow to the rest of the body. Asystole: Asystole should not be confused with very brief pauses in the heart's electrical activity—even those that produce a temporary flatline—that can occur in certain less severe abnormal rhythms. Asystole is different from very fine occurrences of ventricular fibrillation, though both have a poor prognosis, and untreated fine VF will lead to asystole. Faulty wiring, disconnection of electrodes and leads, and power disruptions should be ruled out. Asystole: Asystolic patients (as opposed to those with a "shockable rhythm" such as coarse or fine ventricular fibrillation, or unstable ventricular tachycardia that is not producing a pulse, which can potentially be treated with defibrillation) usually present with a very poor prognosis. Asystole is found initially in only about 28% of cardiac arrest cases in hospitalized patients, but only 15% of these survive, even with the benefit of an intensive care unit, with the rate being lower (6%) for those already prescribed drugs for high blood pressure.Asystole is treated by cardiopulmonary resuscitation (CPR) combined with an intravenous vasopressor such as epinephrine (a.k.a. adrenaline). Sometimes an underlying reversible cause can be detected and treated (the so-called "Hs and Ts", an example of which is hypokalaemia). Several interventions previously recommended—such as defibrillation (known to be ineffective on asystole, but previously performed in case the rhythm was actually very fine ventricular fibrillation) and intravenous atropine—are no longer part of the routine protocols recommended by most major international bodies. 1 mg epinephrine by IV every 3–5 minutes is given for asystole.Survival rates in a cardiac arrest patient with asystole are much lower than a patient with a rhythm amenable to defibrillation; asystole is itself not a "shockable" rhythm. Even in those cases where an individual suffers a cardiac arrest with asystole and it is converted to a less severe shockable rhythm (ventricular fibrillation, or ventricular tachycardia), this does not necessarily improve the person's chances of survival to discharge from the hospital, though if the case was witnessed by a civilian, or better, a paramedic, who gave good CPR and cardiac drugs, this is an important confounding factor to be considered in certain select cases. Out-of-hospital survival rates (even with emergency intervention) are less than 2 percent. Cause: Possible underlying causes, which may be treatable and reversible in certain cases, include the Hs and Ts. Cause: Hypovolemia Hypoxia Hydrogen ions (acidosis) Hypothermia Hyperkalemia or hypokalemia Toxins (e.g. drug overdose) Cardiac tamponade Tension pneumothorax Thrombosis (myocardial infarction or pulmonary embolism)While the heart is asystolic, there is no blood flow to the brain unless CPR or internal cardiac massage (when the chest is opened and the heart is manually compressed) is performed, and even then it is a small amount. After many emergency treatments have been applied but the heart is still unresponsive, it is time to consider pronouncing the patient dead. Even in the rare case that a rhythm reappears, if asystole has persisted for fifteen minutes or more, the brain will have been deprived of oxygen long enough to cause severe hypoxic brain damage, resulting in brain death or persistent vegetative state.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Lie–Kolchin theorem** Lie–Kolchin theorem: In mathematics, the Lie–Kolchin theorem is a theorem in the representation theory of linear algebraic groups; Lie's theorem is the analog for linear Lie algebras. It states that if G is a connected and solvable linear algebraic group defined over an algebraically closed field and ρ:G→GL(V) a representation on a nonzero finite-dimensional vector space V, then there is a one-dimensional linear subspace L of V such that ρ(G)(L)=L. Lie–Kolchin theorem: That is, ρ(G) has an invariant line L, on which G therefore acts through a one-dimensional representation. This is equivalent to the statement that V contains a nonzero vector v that is a common (simultaneous) eigenvector for all ρ(g),g∈G It follows directly that every irreducible finite-dimensional representation of a connected and solvable linear algebraic group G has dimension one. In fact, this is another way to state the Lie–Kolchin theorem. Lie–Kolchin theorem: The result for Lie algebras was proved by Sophus Lie (1876) and for algebraic groups was proved by Ellis Kolchin (1948, p.19). The Borel fixed point theorem generalizes the Lie–Kolchin theorem. Triangularization: Sometimes the theorem is also referred to as the Lie–Kolchin triangularization theorem because by induction it implies that with respect to a suitable basis of V the image ρ(G) has a triangular shape; in other words, the image group ρ(G) is conjugate in GL(n,K) (where n = dim V) to a subgroup of the group T of upper triangular matrices, the standard Borel subgroup of GL(n,K): the image is simultaneously triangularizable. Triangularization: The theorem applies in particular to a Borel subgroup of a semisimple linear algebraic group G. Counter-example: If the field K is not algebraically closed, the theorem can fail. The standard unit circle, viewed as the set of complex numbers {x+iy∈C∣x2+y2=1} of absolute value one is a one-dimensional commutative (and therefore solvable) linear algebraic group over the real numbers which has a two-dimensional representation into the special orthogonal group SO(2) without an invariant (real) line. Here the image ρ(z) of z=x+iy is the orthogonal matrix (xy−yx).
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Isotope fractionation** Isotope fractionation: Isotope fractionation describes fractionation processes that affect the relative abundance of isotopes, phenomena which are taken advantage of in isotope geochemistry and other fields. Normally, the focus is on stable isotopes of the same element. Isotopic fractionation can be measured by isotope analysis, using isotope-ratio mass spectrometry or cavity ring-down spectroscopy to measure ratios of isotopes, an important tool to understand geochemical and biological systems. For example, biochemical processes cause changes in ratios of stable carbon isotopes incorporated into biomass. Definition: Stable isotopes partitioning between two substances A and B can be expressed by the use of the isotopic fractionation factor (alpha): αA-B = RA/RBwhere R is the ratio of the heavy to light isotope (e.g., 2H/1H or 18O/16O). Values for alpha tend to be very close to 1. Types: There are four types of isotope fractionation (of which the first two are normally most important): equilibrium fractionation, kinetic fractionation, mass-independent fractionation (or non-mass-dependent fractionation), and transient kinetic isotope fractionation. Example: Isotope fractionation occurs during a phase transition, when the ratio of light to heavy isotopes in the involved molecules changes. When water vapor condenses (an equilibrium fractionation), the heavier water isotopes (18O and 2H) become enriched in the liquid phase while the lighter isotopes (16O and 1H) tend toward the vapor phase. Literature: Faure G., Mensing T.M. (2004), Isotopes: Principles and Applications (John Wiley & Sons). Hoefs J., 2004. Stable Isotope Geochemistry (Springer Verlag). Sharp Z., 2006. Principles of Stable Isotope Geochemistry (Prentice Hall).
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Cloud chamber** Cloud chamber: A cloud chamber, also known as a Wilson cloud chamber, is a particle detector used for visualizing the passage of ionizing radiation. Cloud chamber: A cloud chamber consists of a sealed environment containing a supersaturated vapor of water or alcohol. An energetic charged particle (for example, an alpha or beta particle) interacts with the gaseous mixture by knocking electrons off gas molecules via electrostatic forces during collisions, resulting in a trail of ionized gas particles. The resulting ions act as condensation centers around which a mist-like trail of small droplets form if the gas mixture is at the point of condensation. These droplets are visible as a "cloud" track that persists for several seconds while the droplets fall through the vapor. These tracks have characteristic shapes. For example, an alpha particle track is thick and straight, while a beta particle track is wispy and shows more evidence of deflections by collisions. Cloud chambers were invented in the early 1900s by the Scottish physicist Charles Thomson Rees Wilson. They played a prominent role in experimental particle physics from the 1920s to the 1950s, until the advent of the bubble chamber. In particular, the discoveries of the positron in 1932 (see Fig. 1) and the muon in 1936, both by Carl Anderson (awarded a Nobel Prize in Physics in 1936), used cloud chambers. Discovery of the kaon by George Rochester and Clifford Charles Butler in 1947, also was made using a cloud chamber as the detector. In each of these cases, cosmic rays were the source of ionizing radiation. Yet they were also used with artificial sources of particles, for example in radiography applications as part of the Manhattan Project. Invention: Charles Thomson Rees Wilson (1869–1959), a Scottish physicist, is credited with inventing the cloud chamber. Inspired by sightings of the Brocken spectre while working on the summit of Ben Nevis in 1894, he began to develop expansion chambers for studying cloud formation and optical phenomena in moist air. Very rapidly he discovered that ions could act as centers for water droplet formation in such chambers. He pursued the application of this discovery and perfected the first cloud chamber in 1911. In Wilson's original chamber (See Fig. 2) the air inside the sealed device was saturated with water vapor, then a diaphragm was used to expand the air inside the chamber (adiabatic expansion), cooling the air and starting to condense water vapor. Hence the name expansion cloud chamber is used. When an ionizing particle passes through the chamber, water vapor condenses on the resulting ions and the trail of the particle is visible in the vapor cloud. Wilson received half the Nobel Prize in Physics in 1927 for his work on the cloud chamber (the same year as Arthur Compton received half the prize for the Compton Effect). This kind of chamber is also called a pulsed chamber because the conditions for operation are not continuously maintained. Further developments were made by Patrick Blackett who utilised a stiff spring to expand and compress the chamber very rapidly, making the chamber sensitive to particles several times a second. A cine film was used to record the images. Invention: The diffusion cloud chamber was developed in 1936 by Alexander Langsdorf. This chamber differs from the expansion cloud chamber in that it is continuously sensitized to radiation, and in that the bottom must be cooled to a rather low temperature, generally colder than −26 °C (−15 °F). Instead of water vapor, alcohol is used because of its lower freezing point. Cloud chambers cooled by dry ice or Peltier effect thermoelectric cooling are common demonstration and hobbyist devices; the alcohol used in them is commonly isopropyl alcohol or methylated spirit. Structure and operation: Diffusion-type cloud chambers will be discussed here. A simple cloud chamber consists of the sealed environment, a warm top plate and a cold bottom plate (See Fig. 3). It requires a source of liquid alcohol at the warm side of the chamber where the liquid evaporates, forming a vapor that cools as it falls through the gas and condenses on the cold bottom plate. Some sort of ionizing radiation is needed. Structure and operation: Isopropanol, methanol, or other alcohol vapor saturates the chamber. The alcohol falls as it cools down and the cold condenser provides a steep temperature gradient. The result is a supersaturated environment. As energetic charged particles pass through the gas they leave ionization trails. The alcohol vapor condenses around gaseous ion trails left behind by the ionizing particles. This occurs because alcohol and water molecules are polar, resulting in a net attractive force toward a nearby free charge (See Fig. 4). The result is a misty cloud-like formation, seen by the presence of droplets falling down to the condenser. When the tracks are emitted from a source, their point of origin can easily be determined. Fig. 5 shows an example of an alpha particle from a Pb-210 pin-type source undergoing Rutherford scattering. Structure and operation: Just above the cold condenser plate there is a volume of the chamber which is sensitive to ionization tracks. The ion trail left by the radioactive particles provides an optimal trigger for condensation and cloud formation. This sensitive volume is increased in height by employing a steep temperature gradient, and stable conditions. A strong electric field is often used to draw cloud tracks down to the sensitive region of the chamber and increase the sensitivity of the chamber. The electric field can also serve to prevent large amounts of background "rain" from obscuring the sensitive region of the chamber, caused by condensation forming above the sensitive volume of the chamber, thereby obscuring tracks by constant precipitation. A black background makes it easier to observe cloud tracks, and typically a tangential light source is needed to illuminate the white droplets against the black background. Often the tracks are not apparent until a shallow pool of alcohol is formed at the condenser plate. If a magnetic field is applied across the cloud chamber, positively and negatively charged particles will curve in opposite directions, according to the Lorentz force law; strong-enough fields are difficult to achieve, however, with small hobbyist setups. This method was also used to prove the existence of the Positron in 1932, in accordance with Paul Dirac's theoretical proof, published in 1928. Benefits and functionality: Particle Visualization: Cloud chambers allow scientists to observe the paths of charged particles as they pass through the chamber. By creating a supersaturated vapor environment, the particles ionize the vapor molecules, creating a visible trail of tiny droplets or clouds. This visualization helps researchers study the behavior, properties, and interactions of these particles. Particle Identification: Cloud chambers can be used to identify different types of particles based on their path and characteristics. By analyzing the curvature, density, and other properties of the particle tracks, scientists can distinguish between various particles, such as electrons, muons, alpha particles, and more. Studying Radioactivity: Cloud chambers are particularly useful in studying radioactive decay and radiation. Radioactive particles emitted from a radioactive source can be observed and their properties analyzed within the cloud chamber. This helps scientists understand the nature of radioactivity, decay processes, and the behavior of radioactive particles. Educational Tool: Research and Discovery: Cloud chambers have been instrumental in numerous scientific discoveries throughout history, including the identification of new particles and the study of particle interactions. By providing a means to observe and analyze particle tracks, cloud chambers have contributed significantly to advancing our knowledge of the subatomic world. Other particle detectors: The bubble chamber was invented by Donald A. Glaser of the United States in 1952, and for this, he was awarded the Nobel Prize in Physics in 1960. The bubble chamber similarly reveals the tracks of subatomic particles, but as trails of bubbles in a superheated liquid, usually liquid hydrogen. Bubble chambers can be made physically larger than cloud chambers, and since they are filled with much-denser liquid material, they reveal the tracks of much more energetic particles. These factors rapidly made the bubble chamber the predominant particle detector for a number of decades, so that cloud chambers were effectively superseded in fundamental research by the start of the 1960s.A spark chamber is an electrical device that uses a grid of uninsulated electric wires in a chamber, with high voltages applied between the wires. Energetic charged particles cause ionization of the gas along the path of the particle in the same way as in the Wilson cloud chamber, but in this case the ambient electric fields are high enough to precipitate full-scale gas breakdown in the form of sparks at the position of the initial ionization. The presence and location of these sparks is then registered electrically, and the information is stored for later analysis, such as by a digital computer. Other particle detectors: Similar condensation effects can be observed as Wilson clouds, also called condensation clouds, at large explosions in humid air and other Prandtl–Glauert singularity effects.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Popular beat combo** Popular beat combo: Popular beat combo, which originated as a synonym for "pop group", is a phrase within British culture. It may also be used more specifically to refer to The Beatles, or other such purveyors of beat music. The phrase is frequently used in Private Eye and in the BBC panel game Have I Got News For You, making fun of Ian Hislop's supposed lack of knowledge about modern music. Derivation: It is widely held that the phrase "popular beat combo" was coined in an English courtroom in the 1960s, by a barrister in response to a judge asking (for the benefit of the court's records) "Who are The Beatles?"; the answer being "I believe they are a popular beat combo, m'lud."However, neither the question nor the answer has ever been reliably attributed, and remains the stuff of urban legend. Marcel Berlins, legal correspondent for The Guardian newspaper, failed in his attempt to track down any verification. In 2007, Berlins restated his offer of "a bottle of best Guardian champagne to any reader with a solution". Christie Davies attributes the encounter to Judge James Pickles.The phrase is part of a trope in postwar British culture where judges are seen to be out of touch, the ultimate example being in the 1960 obscenity trial of Lady Chatterley's Lover, in which the legal profession was ridiculed for being out of touch with changing social norms when the chief prosecutor, Mervyn Griffith-Jones, asked jurors to consider if it were the kind of book "you would wish your wife or servants to read".
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Protoaphin-aglucone dehydratase (cyclizing)** Protoaphin-aglucone dehydratase (cyclizing): The enzyme protoaphin-aglucone dehydratase (cyclizing) (EC 4.2.1.73) catalyzes the chemical reaction protoaphin aglucone ⇌ xanthoaphin + H2OThis enzyme belongs to the family of lyases, specifically the hydro-lyases, which cleave carbon-oxygen bonds. The systematic name of this enzyme class is protoaphin-aglucone hydro-lyase (cyclizing; xanthoaphin-forming). Other names in common use include protoaphin dehydratase, protoaphin dehydratase (cyclizing), and protoaphin-aglucone hydro-lyase (cyclizing).
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Coeliac UK** Coeliac UK: Coeliac UK is a UK charity for people with coeliac disease - a condition estimated to affect 1 out of every 100 people and to be twice as common in women as in men - and the skin manifestation of the condition, dermatitis herpetiformis (DH). History: Founded in 1968 by Amnesty International founder Peter Benenson, and Elizabeth Segall, Coeliac UK (originally called The Coeliac Society) launched the first symbol that acknowledged and advertised that a product contained no gluten, namely the Crossed Grain symbol. Noted clinician Sir Christopher Booth was a founding member. The charity renamed itself Coeliac UK in 2001 and has since established the All Party Parliamentary Group on coeliac disease and DH and worked with the Food Standards Agency to introduce a new law that governed the labelling of gluten-free food.English actress Caroline Quentin is the current patron of the charity.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Apoptosis-inducing factor, mitochondria-associated 3** Apoptosis-inducing factor, mitochondria-associated 3: Apoptosis-inducing factor, mitochondria-associated 3 is a protein that in humans is encoded by the AIFM3 gene.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Troponin** Troponin: Troponin, or the troponin complex, is a complex of three regulatory proteins (troponin C, troponin I, and troponin T) that are integral to muscle contraction in skeletal muscle and cardiac muscle, but not smooth muscle. Measurements of cardiac-specific troponins I and T are extensively used as diagnostic and prognostic indicators in the management of myocardial infarction and acute coronary syndrome. Blood troponin levels may be used as a diagnostic marker for stroke or other myocardial injury that is ongoing, although the sensitivity of this measurement is low. Function: Troponin is attached to the protein tropomyosin and lies within the groove between actin filaments in muscle tissue. In a relaxed muscle, tropomyosin blocks the attachment site for the myosin crossbridge, thus preventing contraction. When the muscle cell is stimulated to contract by an action potential, calcium channels open in the sarcoplasmic membrane and release calcium into the sarcoplasm. Some of this calcium attaches to troponin, which causes it to change shape, exposing binding sites for myosin (active sites) on the actin filaments. Myosin's binding to actin causes crossbridge formation, and contraction of the muscle begins. Function: Troponin is found in both skeletal muscle and cardiac muscle, but the specific versions of troponin differ between types of muscle. The main difference is that the TnC subunit of troponin in skeletal muscle has four calcium ion-binding sites, whereas in cardiac muscle there are only three. The actual amount of calcium that binds to troponin has not been definitively established. Physiology: In both cardiac and skeletal muscles, muscular force production is controlled primarily by changes in intracellular calcium concentration. In general, when calcium rises, the muscles contract and, when calcium falls, the muscles relax.Troponin is a component of thin filaments (along with actin and tropomyosin), and is the protein complex to which calcium binds to trigger the production of muscular force. Troponin has three subunits, TnC, TnI, and TnT, each playing a role in force regulation.. Under resting intracellular levels of calcium, tropomyosin covers the active actin sites to which myosin (a molecular motor organized in muscle thick filaments) binds in order to generate force. When calcium becomes bound to specific sites in the N-domain of TnC, a series of protein structural changes occurs, such that tropomyosin is rolled away from myosin-binding sites on actin, allowing myosin to attach to the thin filament and produce force and shorten the sarcomere.Individual subunits serve different functions: Troponin C binds to calcium ions to produce a conformational change in TnI Troponin T binds to tropomyosin, interlocking them to form a troponin-tropomyosin complex Troponin I binds to actin in thin myofilaments to hold the actin-tropomyosin complex in placeSmooth muscle does not have troponin. Physiology: Subunits TnT is a tropomyosin-binding subunit which regulates the interaction of troponin complex with thin filaments; TnI inhibits ATP-ase activity of acto-myosin; TnC is a Ca2+-binding subunit, playing the main role in Ca2+ dependent regulation of muscle contraction.TnT and TnI in cardiac muscle are presented by forms different from those in skeletal muscles. Two isoforms of TnI and two isoforms of TnT are expressed in human skeletal muscle tissue (skTnI and skTnT). Only one tissue-specific isoform of TnI is described for cardiac muscle tissue (cTnI), whereas the existence of several cardiac specific isoforms of TnT (cTnT) are described in the literature. No cardiac specific isoforms are known for human TnC. TnC in human cardiac muscle tissue is presented by an isoform typical for slow skeletal muscle. Another form of TnC, the fast skeletal TnC isoform, is more typical for fast skeletal muscles. cTnI is expressed only in myocardium. No examples of cTnI expression in healthy or injured skeletal muscle or in other tissue types are known. cTnT is probably less cardiac specific. The expression of cTnT in skeletal tissue of patients with chronic skeletal muscle injuries has been described.Inside the cardiac troponin complex the strongest interaction between molecules has been demonstrated for cTnI – TnC binary complex especially in the presence of Ca2+ ( KA = 1.5 × 10−8 M−1). TnC, forming a complex with cTnI, changes the conformation of cTnI molecule and shields part of its surface. According to the latest data cTnI is released in the blood stream of the patient in the form of binary complex with TnC or ternary complex with cTnT and TnC. cTnI-TnC complex formation plays an important positive role in improving the stability of cTnI molecule. cTnI, which is extremely unstable in its free form, demonstrates significantly better stability in complex with TnC or in ternary cTnI-cTnT-TnC complex. It has been demonstrated that stability of cTnI in native complex is significantly better than stability of the purified form of the protein or the stability of cTnI in artificial troponin complexes combined from purified proteins. Research: Cardiac conditions Certain subtypes of troponin (cardiac I and T) are sensitive and specific indicators of damage to the heart muscle (myocardium). They are measured in the blood to differentiate between unstable angina and myocardial infarction (heart attack) in people with chest pain or acute coronary syndrome. A person who recently had a myocardial infarction would have an area of damaged heart muscle and elevated cardiac troponin levels in the blood. This can also occur in people with coronary vasospasm, a type of myocardial infarction involving severe constriction of the cardiac blood vessels. After a myocardial infarction troponins may remain high for up to 2 weeks.Cardiac troponins are a marker of all heart muscle damage, not just myocardial infarction, which is the most severe form of heart disorder. However, diagnostic criteria for raised troponin indicating myocardial infarction is currently set by the WHO at a threshold of 2 μg or higher. Critical levels of other cardiac biomarkers are also relevant, such as creatine kinase. Other conditions that directly or indirectly lead to heart muscle damage and death can also increase troponin levels, such as kidney failure. Severe tachycardia (for example due to supraventricular tachycardia) in an individual with normal coronary arteries can also lead to increased troponins for example, it is presumed due to increased oxygen demand and inadequate supply to the heart muscle.Troponins are also increased in patients with heart failure, where they also predict mortality and ventricular rhythm abnormalities. They can rise in inflammatory conditions such as myocarditis and pericarditis with heart muscle involvement (which is then termed myopericarditis). Troponins can also indicate several forms of cardiomyopathy, such as dilated cardiomyopathy, hypertrophic cardiomyopathy or (left) ventricular hypertrophy, peripartum cardiomyopathy, Takotsubo cardiomyopathy, or infiltrative disorders such as cardiac amyloidosis.Heart injury with increased troponins also occurs in cardiac contusion, defibrillation and internal or external cardioversion. Troponins are commonly increased in several procedures such as cardiac surgery and heart transplantation, closure of atrial septal defects, percutaneous coronary intervention, or radiofrequency ablation. Research: Non-cardiac conditions The distinction between cardiac and non-cardiac conditions is somewhat artificial; the conditions listed below are not primary heart diseases, but they exert indirect effects on the heart muscle. Troponins are increased in around 40% of patients with critical illnesses such as sepsis. There is an increased risk of mortality and length of stay in the intensive-care unit in these patients. In severe gastrointestinal bleeding, there can also be a mismatch between oxygen demand and supply of the myocardium. Research: Chemotherapy agents can exert toxic effects on the heart (examples include anthracycline, cyclophosphamide, 5-fluorouracil, and cisplatin). Several toxins and venoms can also lead to heart muscle injury (scorpion venom, snake venom, and venom from jellyfish and centipedes). Carbon monoxide poisoning or cyanide poisoning can also be accompanied by the release of troponins due to hypoxic cardiotoxic effects. Cardiac injury occurs in about one-third of severe CO poisoning cases, and troponin screening is appropriate in these patients.In both primary pulmonary hypertension, pulmonary embolism, and acute exacerbations of chronic obstructive pulmonary disease (COPD), right ventricular strain results in increased wall tension and may cause ischemia. Of course, patients with COPD exacerbations might also have concurrent myocardial infarction or pulmonary embolism, so care has to be taken to attribute increased troponin levels to COPD. Research: People with end-stage kidney disease can have chronically elevated troponin T levels, which are linked to a poorer prognosis. Troponin I is less likely to be falsely elevated.Strenuous endurance exercise such as marathons or triathlons can lead to increased troponin levels in up to one-third of subjects, but it is not linked to adverse health effects in these competitors. High troponin T levels have also been reported in patients with inflammatory muscle diseases such as polymyositis or dermatomyositis. Troponins are also increased in rhabdomyolysis. In hypertensive disorders of pregnancy such as preeclampsia, elevated troponin levels indicate some degree of myofibrillary damage.Cardiac troponin T and I can be used to monitor drug and toxin-induced cardiomyocyte toxicity. .In 2020, it was found that patients with severe COVID-19 had higher troponin I levels compared to those with milder disease. Research: Prognostic use Elevated troponin levels are prognostically important in many of the conditions in which they are used for diagnosis.In a community-based cohort study indicating the importance of silent cardiac damage, troponin I has been shown to predict mortality and first coronary heart disease event in men free from cardiovascular disease at baseline. In people with stroke, elevated blood troponin levels are not a useful marker to detect the condition. Research: Subunits First cTnI and later cTnT were originally used as markers for cardiac cell death. Both proteins are now widely used to diagnose acute myocardial infarction (AMI), unstable angina, post-surgery myocardium trauma and some other related diseases with cardiac muscle injury. Both markers can be detected in patient's blood 3–6 hours after onset of the chest pain, reaching peak level within 16–30 hours. Elevated concentration of cTnI and cTnT in blood samples can be detected even 5–8 days after onset of the symptoms, making both proteins useful also for the late diagnosis of AMI. Detection: Cardiac troponin T and I are measured by immunoassay methods. Due to patent regulations, a single manufacturer (Roche Diagnostics) distributes cTnT. A host of diagnostic companies make cTnI immunoassay methods available on many different immunoassay platforms.Troponin elevation following cardiac cell necrosis starts within 2–3 hours, peaks in approx. 24 hours, and persists for 1–2 weeks.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**ML (programming language)** ML (programming language): ML (Meta Language) is a general-purpose functional programming language. It is known for its use of the polymorphic Hindley–Milner type system, which automatically assigns the types of most expressions without requiring explicit type annotations, and ensures type safety – there is a formal proof that a well-typed ML program does not cause runtime type errors. ML provides pattern matching for function arguments, garbage collection, imperative programming, call-by-value and currying. It is used heavily in programming language research and is one of the few languages to be completely specified and verified using formal semantics. Its types and pattern matching make it well-suited and commonly used to operate on other formal languages, such as in compiler writing, automated theorem proving, and formal verification. Overview: Features of ML include a call-by-value evaluation strategy, first-class functions, automatic memory management through garbage collection, parametric polymorphism, static typing, type inference, algebraic data types, pattern matching, and exception handling. ML uses static scoping rules.ML can be referred to as an impure functional language, because although it encourages functional programming, it does allow side-effects (like languages such as Lisp, but unlike a purely functional language such as Haskell). Like most programming languages, ML uses eager evaluation, meaning that all subexpressions are always evaluated, though lazy evaluation can be achieved through the use of closures. Thus one can create and use infinite streams as in Haskell, but their expression is indirect. Overview: ML's strengths are mostly applied in language design and manipulation (compilers, analyzers, theorem provers), but it is a general-purpose language also used in bioinformatics and financial systems. ML was developed by Robin Milner and others in the early 1970s at the University of Edinburgh, and its syntax is inspired by ISWIM. Historically, ML was conceived to develop proof tactics in the LCF theorem prover (whose language, pplambda, a combination of the first-order predicate calculus and the simply-typed polymorphic lambda calculus, had ML as its metalanguage). Today there are several languages in the ML family; the three most prominent are Standard ML (SML), OCaml and F#. Ideas from ML have influenced numerous other languages, like Haskell, Cyclone, Nemerle, ATS, and Elm. Examples: The following examples use the syntax of Standard ML. Other ML dialects such as OCaml and F# differ in small ways. Factorial The factorial function expressed as pure ML: This describes the factorial as a recursive function, with a single terminating base case. It is similar to the descriptions of factorials found in mathematics textbooks. Much of ML code is similar to mathematics in facility and syntax. Examples: Part of the definition shown is optional, and describes the types of this function. The notation E : t can be read as expression E has type t. For instance, the argument n is assigned type integer (int), and fac (n : int), the result of applying fac to the integer n, also has type integer. The function fac as a whole then has type function from integer to integer (int -> int), that is, fac accepts an integer as an argument and returns an integer result. Thanks to type inference, the type annotations can be omitted and will be derived by the compiler. Rewritten without the type annotations, the example looks like: The function also relies on pattern matching, an important part of ML programming. Note that parameters of a function are not necessarily in parentheses but separated by spaces. When the function's argument is 0 (zero) it will return the integer 1 (one). For all other cases the second line is tried. This is the recursion, and executes the function again until the base case is reached. Examples: This implementation of the factorial function is not guaranteed to terminate, since a negative argument causes an infinite descending chain of recursive calls. A more robust implementation would check for a nonnegative argument before recursing, as follows: The problematic case (when n is negative) demonstrates a use of ML's exception system. Examples: The function can be improved further by writing its inner loop as a tail call, such that the call stack need not grow in proportion to the number of function calls. This is achieved by adding an extra, accumulator, parameter to the inner function. At last, we arrive at List reverse The following function reverses the elements in a list. More precisely, it returns a new list whose elements are in reverse order compared to the given list. Examples: This implementation of reverse, while correct and clear, is inefficient, requiring quadratic time for execution. The function can be rewritten to execute in linear time: This function is an example of parametric polymorphism. That is, it can consume lists whose elements have any type, and return lists of the same type. Examples: Modules Modules are ML's system for structuring large projects and libraries. A module consists of a signature file and one or more structure files. The signature file specifies the API to be implemented (like a C header file, or Java interface file). The structure implements the signature (like a C source file or Java class file). For example, the following define an Arithmetic signature and an implementation of it using Rational numbers: These are imported into the interpreter by the 'use' command. Interaction with the implementation is only allowed via the signature functions, for example it is not possible to create a 'Rat' data object directly via this code. The 'structure' block hides all the implementation detail from outside. Examples: ML's standard libraries are implemented as modules in this way.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Transcriptome** Transcriptome: The transcriptome is the set of all RNA transcripts, including coding and non-coding, in an individual or a population of cells. The term can also sometimes be used to refer to all RNAs, or just mRNA, depending on the particular experiment. The term transcriptome is a portmanteau of the words transcript and genome; it is associated with the process of transcript production during the biological process of transcription. Transcriptome: The early stages of transcriptome annotations began with cDNA libraries published in the 1980s. Subsequently, the advent of high-throughput technology led to faster and more efficient ways of obtaining data about the transcriptome. Two biological techniques are used to study the transcriptome, namely DNA microarray, a hybridization-based technique and RNA-seq, a sequence-based approach. RNA-seq is the preferred method and has been the dominant transcriptomics technique since the 2010s. Single-cell transcriptomics allows tracking of transcript changes over time within individual cells. Transcriptome: Data obtained from the transcriptome is used in research to gain insight into processes such as cellular differentiation, carcinogenesis, transcription regulation and biomarker discovery among others. Transcriptome-obtained data also finds applications in establishing phylogenetic relationships during the process of evolution and in in vitro fertilization. The transcriptome is closely related to other -ome based biological fields of study; it is complementary to the proteome and the metabolome and encompasses the translatome, exome, meiome and thanatotranscriptome which can be seen as ome fields studying specific types of RNA transcripts. There are quantifiable and conserved relationships between the Transcriptome and other -omes, and Transcriptomics data can be used effectively to predict other molecular species, such as metabolites. There are numerous publicly available transcriptome databases. Etymology and history: The word transcriptome is a portmanteau of the words transcript and genome. It appeared along with other neologisms formed using the suffixes -ome and -omics to denote all studies conducted on a genome-wide scale in the fields of life sciences and technology. As such, transcriptome and transcriptomics were one of the first words to emerge along with genome and proteome. The first study to present a case of a collection of a cDNA library for silk moth mRNA was published in 1979. The first seminal study to mention and investigate the transcriptome of an organism was published in 1997 and it described 60,633 transcripts expressed in S. cerevisiae using serial analysis of gene expression (SAGE). With the rise of high-throughput technologies and bioinformatics and the subsequent increased computational power, it became increasingly efficient and easy to characterize and analyze enormous amount of data. Attempts to characterize the transcriptome became more prominent with the advent of automated DNA sequencing during the 1980s. During the 1990s, expressed sequence tag sequencing was used to identify genes and their fragments. This was followed by techniques such as serial analysis of gene expression (SAGE), cap analysis of gene expression (CAGE), and massively parallel signature sequencing (MPSS). Transcription: The transcriptome encompasses all the ribonucleic acid (RNA) transcripts present in a given organism or experimental sample. RNA is the main carrier of genetic information that is responsible for the process of converting DNA into an organism's phenotype. A gene can give rise to a single-stranded messenger RNA (mRNA) through a molecular process known as transcription; this mRNA is complementary to the strand of DNA it originated from. The enzyme RNA polymerase II attaches to the template DNA strand and catalyzes the addition of ribonucleotides to the 3' end of the growing sequence of the mRNA transcript.In order to initiate its function, RNA polymerase II needs to recognize a promoter sequence, located upstream (5') of the gene. In eukaryotes, this process is mediated by transcription factors, most notably Transcription factor II D (TFIID) which recognizes the TATA box and aids in the positioning of RNA polymerase at the appropriate start site. To finish the production of the RNA transcript, termination takes place usually several hundred nuclecotides away from the termination sequence and cleavage takes place. This process occurs in the nucleus of a cell along with RNA processing by which mRNA molecules are capped, spliced and polyadenylated to increase their stability before being subsequently taken to the cytoplasm. The mRNA gives rise to proteins through the process of translation that takes place in ribosomes. Types of RNA transcripts: Almost all functional transcripts are derived from known genes. The only exceptions are a small number of transcripts that might play a direct role in regulating gene expression near the prompters of known genes. (See Enhancer RNA.) Gene occupy most of prokaryotic genomes so most of their genomes are transcribed. Many eukaryotic genomes are very large and known genes may take up only a fraction of the genome. In mammals, for example, known genes only account for 40-50% of the genome. Nevertheless, identified transcripts often map to a much larger fraction of the genome suggesting that the transcriptome contains spurious transcripts that do not come from genes. Some of these transcripipts are known to be non-functional because they map to transcribed pseudogenes or degenerative transposons and viruses. Others map to unidentified regions of the genome that may be junk DNA. Spurious transcription is very common in eukaryotes, especially those with large genomes that might contain a lot of junk DNA. Some scientists claim that if a transcript has not been assigned to a known gene then the default assumption must be that it is junk RNA until it has been shown to be functional. This would mean that much of the transcriptome in species with large genomes is probably junk RNA. (See Non-coding RNA) The transcriptome includes the transcripts of protein-coding genes (mRNA plus introns) as well as the transcripts of non-coding genes (functional RNAs plus introns). Ribosomal RNA/rRNA: Usually the most abundant RNA in the transcriptome. Types of RNA transcripts: Long non-coding RNA/lncRNA: Non-coding RNA transcripts that are more than 200 nucleotides long. Members of this group comprise the largest fraction of the non-coding transcriptome other than introns. It is not known how many of these transcripts are functional and how many are junk RNA. transfer RNA/tRNA micro RNA/miRNA: 19-24 nucleotides (nt) long. Micro RNAs up- or downregulate expression levels of mRNAs by the process of RNA interference at the post-transcriptional level. small interfering RNA/siRNA: 20-24 nt small nucleolar RNA/snoRNA Piwi-interacting RNA/piRNA: 24-31 nt. They interact with Piwi proteins of the Argonaute family and have a function in targeting and cleaving transposons. enhancer RNA/eRNA: Scope of study: In the human genome, all genes get transcribed into RNA because that's how the molecular gene is defined. (See Gene.) The transcriptome consists of coding regions of mRNA plus non-coding UTRs, introns, non-coding RNAs, and spurious non-functional transcripts. Several factors render the content of the transcriptome difficult to establish. These include alternative splicing, RNA editing and alternative transcription among others. Additionally, transcriptome techniques are capable of capturing transcription occurring in a sample at a specific time point, although the content of the transcriptome can change during differentiation. The main aims of transcriptomics are the following: "catalogue all species of transcript, including mRNAs, non-coding RNAs and small RNAs; to determine the transcriptional structure of genes, in terms of their start sites, 5′ and 3′ ends, splicing patterns and other post-transcriptional modifications; and to quantify the changing expression levels of each transcript during development and under different conditions".The term can be applied to the total set of transcripts in a given organism, or to the specific subset of transcripts present in a particular cell type. Unlike the genome, which is roughly fixed for a given cell line (excluding mutations), the transcriptome can vary with external environmental conditions. Because it includes all mRNA transcripts in the cell, the transcriptome reflects the genes that are being actively expressed at any given time, with the exception of mRNA degradation phenomena such as transcriptional attenuation. The study of transcriptomics, (which includes expression profiling, splice variant analysis etc.), examines the expression level of RNAs in a given cell population, often focusing on mRNA, but sometimes including others such as tRNAs and sRNAs. Methods of construction: Transcriptomics is the quantitative science that encompasses the assignment of a list of strings ("reads") to the object ("transcripts" in the genome). To calculate the expression strength, the density of reads corresponding to each object is counted. Initially, transcriptomes were analyzed and studied using expressed sequence tags libraries and serial and cap analysis of gene expression (SAGE). Methods of construction: Currently, the two main transcriptomics techniques include DNA microarrays and RNA-Seq. Both techniques require RNA isolation through RNA extraction techniques, followed by its separation from other cellular components and enrichment of mRNA.There are two general methods of inferring transcriptome sequences. One approach maps sequence reads onto a reference genome, either of the organism itself (whose transcriptome is being studied) or of a closely related species. The other approach, de novo transcriptome assembly, uses software to infer transcripts directly from short sequence reads and is used in organisms with genomes that are not sequenced. Methods of construction: DNA microarrays The first transcriptome studies were based on microarray techniques (also known as DNA chips). Microarrays consist of thin glass layers with spots on which oligonucleotides, known as "probes" are arrayed; each spot contains a known DNA sequence.When performing microarray analyses, mRNA is collected from a control and an experimental sample, the latter usually representative of a disease. The RNA of interest is converted to cDNA to increase its stability and marked with fluorophores of two colors, usually green and red, for the two groups. The cDNA is spread onto the surface of the microarray where it hybridizes with oligonucleotides on the chip and a laser is used to scan. The fluorescence intensity on each spot of the microarray corresponds to the level of gene expression and based on the color of the fluorophores selected, it can be determined which of the samples exhibits higher levels of the mRNA of interest.One microarray usually contains enough oligonucleotides to represent all known genes; however, data obtained using microarrays does not provide information about unknown genes. During the 2010s, microarrays were almost completely replaced by next-generation techniques that are based on DNA sequencing. Methods of construction: RNA sequencing RNA sequencing is a next-generation sequencing technology; as such it requires only a small amount of RNA and no previous knowledge of the genome. It allows for both qualitative and quantitative analysis of RNA transcripts, the former allowing discovery of new transcripts and the latter a measure of relative quantities for transcripts in a sample.The three main steps of sequencing transcriptomes of any biological samples include RNA purification, the synthesis of an RNA or cDNA library and sequencing the library. The RNA purification process is different for short and long RNAs. This step is usually followed by an assessment of RNA quality, with the purpose of avoiding contaminants such as DNA or technical contaminants related to sample processing. RNA quality is measured using UV spectrometry with an absorbance peak of 260 nm. RNA integrity can also be analyzed quantitatively comparing the ratio and intensity of 28S RNA to 18S RNA reported in the RNA Integrity Number (RIN) score. Since mRNA is the species of interest and it represents only 3% of its total content, the RNA sample should be treated to remove rRNA and tRNA and tissue-specific RNA transcripts.The step of library preparation with the aim of producing short cDNA fragments, begins with RNA fragmentation to transcripts in length between 50 and 300 base pairs. Fragmentation can be enzymatic (RNA endonucleases), chemical (trismagnesium salt buffer, chemical hydrolysis) or mechanical (sonication, nebulisation). Reverse transcription is used to convert the RNA templates into cDNA and three priming methods can be used to achieve it, including oligo-DT, using random primers or ligating special adaptor oligos. Methods of construction: Single-cell transcriptomics Transcription can also be studied at the level of individual cells by single-cell transcriptomics. Single-cell RNA sequencing (scRNA-seq) is a recently developed technique that allows the analysis of the transcriptome of single cells. With single-cell transcriptomics, subpopulations of cell types that constitute the tissue of interest are also taken into consideration. This approach allows to identify whether changes in experimental samples are due to phenotypic cellular changes as opposed to proliferation, with which a specific cell type might be overexpressed in the sample. Additionally, when assessing cellular progression through differentiation, average expression profiles are only able to order cells by time rather than their stage of development and are consequently unable to show trends in gene expression levels specific to certain stages. Single-cell trarnscriptomic techniques have been used to characterize rare cell populations such as circulating tumor cells, cancer stem cells in solid tumors, and embryonic stem cells (ESCs) in mammalian blastocysts.Although there are no standardized techniques for single-cell transcriptomics, several steps need to be undertaken. The first step includes cell isolation, which can be performed using low- and high-throughput techniques. This is followed by a qPCR step and then single-cell RNAseq where the RNA of interest is converted into cDNA. Newer developments in single-cell transcriptomics allow for tissue and sub-cellular localization preservation through cryo-sectioning thin slices of tissues and sequencing the transcriptome in each slice. Another technique allows the visualization of single transcripts under a microscope while preserving the spatial information of each individual cell where they are expressed. Analysis: A number of organism-specific transcriptome databases have been constructed and annotated to aid in the identification of genes that are differentially expressed in distinct cell populations. Analysis: RNA-seq is emerging (2013) as the method of choice for measuring transcriptomes of organisms, though the older technique of DNA microarrays is still used. RNA-seq measures the transcription of a specific gene by converting long RNAs into a library of cDNA fragments. The cDNA fragments are then sequenced using high-throughput sequencing technology and aligned to a reference genome or transcriptome which is then used to create an expression profile of the genes. Applications: Mammals The transcriptomes of stem cells and cancer cells are of particular interest to researchers who seek to understand the processes of cellular differentiation and carcinogenesis. A pipeline using RNA-seq or gene array data can be used to track genetic changes occurring in stem and precursor cells and requires at least three independent gene expression data from the former cell type and mature cells.Analysis of the transcriptomes of human oocytes and embryos is used to understand the molecular mechanisms and signaling pathways controlling early embryonic development, and could theoretically be a powerful tool in making proper embryo selection in in vitro fertilisation. Analyses of the transcriptome content of the placenta in the first-trimester of pregnancy in in vitro fertilization and embryo transfer (IVT-ET) revealed differences in genetic expression which are associated with higher frequency of adverse perinatal outcomes. Such insight can be used to optimize the practice. Transcriptome analyses can also be used to optimize cryopreservation of oocytes, by lowering injuries associated with the process.Transcriptomics is an emerging and continually growing field in biomarker discovery for use in assessing the safety of drugs or chemical risk assessment.Transcriptomes may also be used to infer phylogenetic relationships among individuals or to detect evolutionary patterns of transcriptome conservation.Transcriptome analyses were used to discover the incidence of antisense transcription, their role in gene expression through interaction with surrounding genes and their abundance in different chromosomes. RNA-seq was also used to show how RNA isoforms, transcripts stemming from the same gene but with different structures, can produce complex phenotypes from limited genomes. Applications: Plants Transcriptome analysis have been used to study the evolution and diversification process of plant species. In 2014, the 1000 Plant Genomes Project was completed in which the transcriptomes of 1,124 plant species from the families viridiplantae, glaucophyta and rhodophyta were sequenced. The protein coding sequences were subsequently compared to infer phylogenetic relationships between plants and to characterize the time of their diversification in the process of evolution. Transcriptome studies have been used to characterize and quantify gene expression in mature pollen. Genes involved in cell wall metabolism and cytoskeleton were found to be overexpressed. Transcriptome approaches also allowed to track changes in gene expression through different developmental stages of pollen, ranging from microspore to mature pollen grains; additionally such stages could be compared across species of different plants including Arabidopsis, rice and tobacco. Relation to other ome fields: Similar to other -ome based technologies, analysis of the transcriptome allows for an unbiased approach when validating hypotheses experimentally. This approach also allows for the discovery of novel mediators in signaling pathways. As with other -omics based technologies, the transcriptome can be analyzed within the scope of a multiomics approach. It is complementary to metabolomics but contrary to proteomics, a direct association between a transcript and metabolite cannot be established. Relation to other ome fields: There are several -ome fields that can be seen as subcategories of the transcriptome. The exome differs from the transcriptome in that it includes only those RNA molecules found in a specified cell population, and usually includes the amount or concentration of each RNA molecule in addition to the molecular identities. Additionally, the transcritpome also differs from the translatome, which is the set of RNAs undergoing translation. Relation to other ome fields: The term meiome is used in functional genomics to describe the meiotic transcriptome or the set of RNA transcripts produced during the process of meiosis. Meiosis is a key feature of sexually reproducing eukaryotes, and involves the pairing of homologous chromosome, synapse and recombination. Since meiosis in most organisms occurs in a short time period, meiotic transcript profiling is difficult due to the challenge of isolation (or enrichment) of meiotic cells (meiocytes). As with transcriptome analyses, the meiome can be studied at a whole-genome level using large-scale transcriptomic techniques. The meiome has been well-characterized in mammal and yeast systems and somewhat less extensively characterized in plants.The thanatotranscriptome consists of all RNA transcripts that continue to be expressed or that start getting re-expressed in internal organs of a dead body 24–48 hours following death. Some genes include those that are inhibited after fetal development. If the thanatotranscriptome is related to the process of programmed cell death (apoptosis), it can be referred to as the apoptotic thanatotranscriptome. Analyses of the thanatotranscriptome are used in forensic medicine.eQTL mapping can be used to complement genomics with transcriptomics; genetic variants at DNA level and gene expression measures at RNA level. Relation to other ome fields: Relation to proteome The transcriptome can be seen as a subset of the proteome, that is, the entire set of proteins expressed by a genome. Relation to other ome fields: However, the analysis of relative mRNA expression levels can be complicated by the fact that relatively small changes in mRNA expression can produce large changes in the total amount of the corresponding protein present in the cell. One analysis method, known as gene set enrichment analysis, identifies coregulated gene networks rather than individual genes that are up- or down-regulated in different cell populations.[1]Although microarray studies can reveal the relative amounts of different mRNAs in the cell, levels of mRNA are not directly proportional to the expression level of the proteins they code for. The number of protein molecules synthesized using a given mRNA molecule as a template is highly dependent on translation-initiation features of the mRNA sequence; in particular, the ability of the translation initiation sequence is a key determinant in the recruiting of ribosomes for protein translation. Transcriptome databases: Ensembl: [2] OmicTools: [3] Transcriptome Browser: [4] ArrayExpress: [5]
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Nervine** Nervine: Nervine was a patent medicine tonic with sedative effects introduced in 1884 by Dr. Miles Medical Company (later Miles Laboratories which was absorbed into Bayer). It is a cognate of 'Nerve', and the implication was that the material worked to calm nervousness. Formulation: One form of Nervine was formulated with the primary active ingredients sodium bromide, ammonium bromide, and potassium bromide, combined with sodium bicarbonate and citric acid in an effervescent tablet. Modern appropriation of term: In the late 20th and early 21st century, promulgators of alternative medicine and herbalism have begun to use the term Nervine as an adjective. This is not a term used by mainstream medicine, where anxiolytic is the preferred term.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Comonotonicity** Comonotonicity: In probability theory, comonotonicity mainly refers to the perfect positive dependence between the components of a random vector, essentially saying that they can be represented as increasing functions of a single random variable. In two dimensions it is also possible to consider perfect negative dependence, which is called countermonotonicity. Comonotonicity is also related to the comonotonic additivity of the Choquet integral.The concept of comonotonicity has applications in financial risk management and actuarial science, see e.g. Dhaene et al. (2002a) and Dhaene et al. (2002b). In particular, the sum of the components X1 + X2 + · · · + Xn is the riskiest if the joint probability distribution of the random vector (X1, X2, . . . , Xn) is comonotonic. Furthermore, the α-quantile of the sum equals of the sum of the α-quantiles of its components, hence comonotonic random variables are quantile-additive. In practical risk management terms it means that there is minimal (or eventually no) variance reduction from diversification. Comonotonicity: For extensions of comonotonicity, see Jouini & Napp (2004) and Puccetti & Scarsini (2010). Definitions: Comonotonicity of subsets of Rn A subset S of Rn is called comonotonic (sometimes also nondecreasing) if, for all (x1, x2, . . . , xn) and (y1, y2, . . . , yn) in S with xi < yi for some i ∈ {1, 2, . . . , n}, it follows that xj ≤ yj for all j ∈ {1, 2, . . . , n}. Definitions: This means that S is a totally ordered set. Comonotonicity of probability measures on Rn Let μ be a probability measure on the n-dimensional Euclidean space Rn and let F denote its multivariate cumulative distribution function, that is := μ({(y1,…,yn)∈Rn∣y1≤x1,…,yn≤xn}),(x1,…,xn)∈Rn. Furthermore, let F1, . . . , Fn denote the cumulative distribution functions of the n one-dimensional marginal distributions of μ, that means := μ({(y1,…,yn)∈Rn∣yi≤x}),x∈R for every i ∈ {1, 2, . . . , n}. Then μ is called comonotonic, if min i∈{1,…,n}Fi(xi),(x1,…,xn)∈Rn. Note that the probability measure μ is comonotonic if and only if its support S is comonotonic according to the above definition. Comonotonicity of Rn-valued random vectors An Rn-valued random vector X = (X1, . . . , Xn) is called comonotonic, if its multivariate distribution (the pushforward measure) is comonotonic, this means Pr min Pr (Xi≤xi),(x1,…,xn)∈Rn. Properties: An Rn-valued random vector X = (X1, . . . , Xn) is comonotonic if and only if it can be represented as (X1,…,Xn)=d(FX1−1(U),…,FXn−1(U)), where =d stands for equality in distribution, on the right-hand side are the left-continuous generalized inverses of the cumulative distribution functions FX1, . . . , FXn, and U is a uniformly distributed random variable on the unit interval. More generally, a random vector is comonotonic if and only if it agrees in distribution with a random vector where all components are non-decreasing functions (or all are non-increasing functions) of the same random variable. Upper bounds: Upper Fréchet–Hoeffding bound for cumulative distribution functions Let X = (X1, . . . , Xn) be an Rn-valued random vector. Then, for every i ∈ {1, 2, . . . , n}, Pr Pr (Xi≤xi),(x1,…,xn)∈Rn, hence Pr min Pr (Xi≤xi),(x1,…,xn)∈Rn, with equality everywhere if and only if (X1, . . . , Xn) is comonotonic. Upper bounds: Upper bound for the covariance Let (X, Y) be a bivariate random vector such that the expected values of X, Y and the product XY exist. Let (X*, Y*) be a comonotonic bivariate random vector with the same one-dimensional marginal distributions as (X, Y). Then it follows from Höffding's formula for the covariance and the upper Fréchet–Hoeffding bound that Cov Cov (X∗,Y∗) and, correspondingly, E⁡[XY]≤E⁡[X∗Y∗] with equality if and only if (X, Y) is comonotonic.Note that this result generalizes the rearrangement inequality and Chebyshev's sum inequality.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Becoming (philosophy)** Becoming (philosophy): Process philosophy, also ontology of becoming, or processism, is an approach in philosophy that identifies processes, changes, or shifting relationships as the only real experience of everyday living. In opposition to the classical view of change as illusory (as argued by Parmenides) or accidental (as argued by Aristotle), process philosophy posits transient occasions of change or becoming as the only fundamental things of the ordinary everyday real world. Becoming (philosophy): Since the time of Plato and Aristotle, classical ontology has posited ordinary world reality as constituted of enduring substances, to which transient processes are ontologically subordinate, if they are not denied. If Socrates changes, becoming sick, Socrates is still the same (the substance of Socrates being the same), and change (his sickness) only glides over his substance: change is accidental, and devoid of primary reality, whereas the substance is essential. Becoming (philosophy): In physics, Ilya Prigogine distinguishes between the "physics of being" and the "physics of becoming". Process philosophy covers not just scientific intuitions and experiences, but can be used as a conceptual bridge to facilitate discussions among religion, philosophy, and science.Process philosophy is sometimes classified as closer to continental philosophy than analytic philosophy, because it is usually only taught in continental philosophy departments. However, other sources state that process philosophy should be placed somewhere in the middle between the poles of analytic versus continental methods in contemporary philosophy. History: In ancient Greek thought Heraclitus proclaimed that the basic nature of all things is change. History: The quotation from Heraclitus appears in Plato's Cratylus twice; in 401d as: τὰ ὄντα ἰέναι τε πάντα καὶ μένειν οὐδένTa onta ienai te panta kai menein ouden"All entities move and nothing remains still"and in 402a"πάντα χωρεῖ καὶ οὐδὲν μένει" καὶ "δὶς ἐς τὸν αὐτὸν ποταμὸν οὐκ ἂν ἐμβαίης"Panta chōrei kai ouden menei kai dis es ton auton potamon ouk an embaies "Everything changes and nothing remains still ... and ... you cannot step twice into the same stream" Heraclitus considered fire as the most fundamental element. History: "All things are an interchange for fire, and fire for all things, just like goods for gold and gold for goods." The following is an interpretation of Heraclitus's concepts into modern terms by Nicholas Rescher. History: "...reality is not a constellation of things at all, but one of processes. The fundamental "stuff" of the world is not material substance, but volatile flux, namely "fire", and all things are versions thereof (puros tropai). Process is fundamental: the river is not an object, but a continuing flow; the sun is not a thing, but an enduring fire. Everything is a matter of process, of activity, of change (panta rhei)." An early expression of this viewpoint is in Heraclitus's fragments. He posits strife, ἡ ἔρις (strife, conflict), as the underlying basis of all reality defined by change. The balance and opposition in strife were the foundations of change and stability in the flux of existence. History: Nietzsche and Kierkegaard In his written works, Friedrich Nietzsche proposed what has been regarded as a philosophy of becoming that encompasses a "naturalistic doctrine intended to counter the metaphysical preoccupation with being", and a theory of "the incessant shift of perspectives and interpretations in a world that lacks a grounding essence".Søren Kierkegaard posed questions of individual becoming in Christianity which were opposed to the ancient Greek philosophers' focus on the indifferent becoming of the cosmos. However, he established as much of a focus on aporia as Heraclitus and others previously had, such as in his concept of the leap of faith which marks an individual becoming. As well as this, Kierkegaard opposed his philosophy to Hegel's system of philosophy approaching becoming and difference for what he saw as a "dialectical conflation of becoming and rationality", making the system take upon the same trait of motionlessness as Parmenides' system. History: Twentieth century In the early twentieth century, the philosophy of mathematics was undertaken to develop mathematics as an airtight, axiomatic system in which every truth could be derived logically from a set of axioms. In the foundations of mathematics, this project is variously understood as logicism or as part of the formalist program of David Hilbert. Alfred North Whitehead and Bertrand Russell attempted to complete, or at least facilitate, this program with their seminal book Principia Mathematica, which purported to build a logically consistent set theory on which to found mathematics. After this, Whitehead extended his interest to natural science, which he held needed a deeper philosophical basis. He intuited that natural science was struggling to overcome a traditional ontology of timeless material substances that does not suit natural phenomena. According to Whitehead, material is more properly understood as 'process'. In 1929, he produced the most famous work of process philosophy, Process and Reality, continuing the work begun by Hegel but describing a more complex and fluid dynamic ontology. History: Process thought describes truth as "movement" in and through substance (Hegelian truth), rather than substances as fixed concepts or "things" (Aristotelian truth). Since Whitehead, process thought is distinguished from Hegel in that it describes entities that arise or coalesce in becoming, rather than being simply dialectically determined from prior posited determinates. These entities are referred to as complexes of occasions of experience. It is also distinguished in being not necessarily conflictual or oppositional in operation. Process may be integrative, destructive or both together, allowing for aspects of interdependence, influence, and confluence, and addressing coherence in universal as well as particular developments, i.e., those aspects not befitting Hegel's system. Additionally, instances of determinate occasions of experience, while always ephemeral, are nonetheless seen as important to define the type and continuity of those occasions of experience that flow from or relate to them. Whitehead's Process and Reality: Alfred North Whitehead began teaching and writing on process and metaphysics when he joined Harvard University in 1924.In his book Science and the Modern World (1925), Whitehead noted that the human intuitions and experiences of science, aesthetics, ethics, and religion influence the worldview of a community, but that in the last several centuries science dominates Western culture. Whitehead sought a holistic, comprehensive cosmology that provides a systematic descriptive theory of the world which can be used for the diverse human intuitions gained through ethical, aesthetic, religious, and scientific experiences, and not just the scientific.Whitehead's influences were not restricted to philosophers or physicists or mathematicians. He was influenced by the French philosopher Henri Bergson (1859–1941), whom he credits along with William James and John Dewey in the preface to Process and Reality. Whitehead's Process and Reality: Process metaphysics For Whitehead, metaphysics is about logical frameworks for the conduct of discussions of the character of the world. It is not directly and immediately about facts of nature, but only indirectly so, in that its task is to explicitly formulate the language and conceptual presuppositions that are used to describe the facts of nature. Whitehead thinks that discovery of previously unknown facts of nature can in principle call for reconstruction of metaphysics.: 13, 19 The process metaphysics elaborated in Process and Reality posits an ontology which is based on the two kinds of existence of an entity, that of actual entity and that of abstract entity or abstraction, also called 'object'.Actual entity is a term coined by Whitehead to refer to the entities that really exist in the natural world. For Whitehead, actual entities are spatiotemporally extended events or processes. An actual entity is how something is happening, and how its happening is related to other actual entities. The actually existing world is a multiplicity of actual entities overlapping one another.The ultimate abstract principle of actual existence for Whitehead is creativity. Creativity is a term coined by Whitehead to show a power in the world that allows the presence of an actual entity, a new actual entity, and multiple actual entities. Creativity is the principle of novelty. It is manifest in what can be called 'singular causality'. This term may be contrasted with the term 'nomic causality'. An example of singular causation is that I woke this morning because my alarm clock rang. An example of nomic causation is that alarm clocks generally wake people in the morning. Aristotle recognizes singular causality as efficient causality. For Whitehead, there are many contributory singular causes for an event. A further contributory singular cause of my being awoken by my alarm clock this morning was that I was lying asleep near it till it rang. Whitehead's Process and Reality: An actual entity is a general philosophical term for an utterly determinate and completely concrete individual particular of the actually existing world or universe of changeable entities considered in terms of singular causality, about which categorical statements can be made. Whitehead's most far-reaching and radical contribution to metaphysics is his invention of a better way of choosing the actual entities. Whitehead chooses a way of defining the actual entities that makes them all alike, qua actual entities, with a single exception. Whitehead's Process and Reality: For example, for Aristotle, the actual entities were the substances, such as Socrates. Besides Aristotle's ontology of substances, another example of an ontology that posits actual entities is in the monads of Leibniz, which are said to be 'windowless'. Whitehead's actual entities For Whitehead's ontology of processes as defining the world, the actual entities exist as the only fundamental elements of reality. The actual entities are of two kinds, temporal and atemporal. Whitehead's Process and Reality: With one exception, all actual entities for Whitehead are temporal and are occasions of experience (which are not to be confused with consciousness). An entity that people commonly think of as a simple concrete object, or that Aristotle would think of as a substance, is, in this ontology, considered to be a temporally serial composite of indefinitely many overlapping occasions of experience. A human being is thus composed of indefinitely many occasions of experience. Whitehead's Process and Reality: The one exceptional actual entity is at once both temporal and atemporal: God. He is objectively immortal, as well as being immanent in the world. He is objectified in each temporal actual entity; but He is not an eternal object. Whitehead's Process and Reality: The occasions of experience are of four grades. The first grade comprises processes in a physical vacuum such as the propagation of an electromagnetic wave or gravitational influence across empty space. The occasions of experience of the second grade involve just inanimate matter; "matter" being the composite overlapping of occasions of experience from the previous grade. The occasions of experience of the third grade involve living organisms. Occasions of experience of the fourth grade involve experience in the mode of presentational immediacy, which means more or less what are often called the qualia of subjective experience. So far as we know, experience in the mode of presentational immediacy occurs in only more evolved animals. That some occasions of experience involve experience in the mode of presentational immediacy is the one and only reason why Whitehead makes the occasions of experience his actual entities; for the actual entities must be of the ultimately general kind. Consequently, it is inessential that an occasion of experience have an aspect in the mode of presentational immediacy; occasions of the grades one, two, and three, lack that aspect. Whitehead's Process and Reality: There is no mind-matter duality in this ontology, because "mind" is simply seen as an abstraction from an occasion of experience which has also a material aspect, which is of course simply another abstraction from it; thus the mental aspect and the material aspect are abstractions from one and the same concrete occasion of experience. The brain is part of the body, both being abstractions of a kind known as persistent physical objects, neither being actual entities. Though not recognized by Aristotle, there is biological evidence, written about by Galen, that the human brain is an essential seat of human experience in the mode of presentational immediacy. We may say that the brain has a material and a mental aspect, all three being abstractions from their indefinitely many constitutive occasions of experience, which are actual entities. Whitehead's Process and Reality: Time, causality, and process Inherent in each actual entity is its respective dimension of time. Potentially, each Whiteheadean occasion of experience is causally consequential on every other occasion of experience that precedes it in time, and has as its causal consequences every other occasion of experience that follows it in time; thus it has been said that Whitehead's occasions of experience are 'all window', in contrast to Leibniz's 'windowless' monads. In time defined relative to it, each occasion of experience is causally influenced by prior occasions of experiences, and causally influences future occasions of experience. An occasion of experience consists of a process of prehending other occasions of experience, reacting to them. This is the process in process philosophy. Whitehead's Process and Reality: Such process is never deterministic. Consequently, free will is essential and inherent to the universe. Whitehead's Process and Reality: The causal outcomes obey the usual well-respected rule that the causes precede the effects in time. Some pairs of processes cannot be connected by cause-and-effect relations, and they are said to be spatially separated. This is in perfect agreement with the viewpoint of the Einstein theory of special relativity and with the Minkowski geometry of spacetime. It is clear that Whitehead respected these ideas, as may be seen for example in his 1919 book An Enquiry concerning the Principles of Natural Knowledge as well as in Process and Reality. In this view, time is relative to an inertial reference frame, different reference frames defining different versions of time. Whitehead's Process and Reality: Atomicity The actual entities, the occasions of experience, are logically atomic in the sense that an occasion of experience cannot be cut and separated into two other occasions of experience. This kind of logical atomicity is perfectly compatible with indefinitely many spatio-temporal overlaps of occasions of experience. One can explain this kind of atomicity by saying that an occasion of experience has an internal causal structure that could not be reproduced in each of the two complementary sections into which it might be cut. Nevertheless, an actual entity can completely contain each of indefinitely many other actual entities. Whitehead's Process and Reality: Another aspect of the atomicity of occasions of experience is that they do not change. An actual entity is what it is. An occasion of experience can be described as a process of change, but it is itself unchangeable. The reader should bear in mind that the atomicity of the actual entities is of a simply logical or philosophical kind, thoroughly different in concept from the natural kind of atomicity that describes the atoms of physics and chemistry. Whitehead's Process and Reality: Topology Whitehead's theory of extension was concerned with the spatio-temporal features of his occasions of experience. Fundamental to both Newtonian and to quantum theoretical mechanics is the concept of momentum. The measurement of a momentum requires a finite spatiotemporal extent. Because it has no finite spatiotemporal extent, a single point of Minkowski space cannot be an occasion of experience, but is an abstraction from an infinite set of overlapping or contained occasions of experience, as explained in Process and Reality. Though the occasions of experience are atomic, they are not necessarily separate in extension, spatiotemporally, from one another. Indefinitely many occasions of experience can overlap in Minkowski space. Whitehead's Process and Reality: Nexus is a term coined by Whitehead to show the network actual entity from the universe. In the universe of actual entities spread actual entity. Actual entities are clashing with each other and form other actual entities. The birth of an actual entity based on an actual entity, actual entities around him referred to as nexus.An example of a nexus of temporally overlapping occasions of experience is what Whitehead calls an enduring physical object, which corresponds closely with an Aristotelian substance. An enduring physical object has a temporally earliest and a temporally last member. Every member (apart from the earliest) of such a nexus is a causal consequence of the earliest member of the nexus, and every member (apart from the last) of such a nexus is a causal antecedent of the last member of the nexus. There are indefinitely many other causal antecedents and consequences of the enduring physical object, which overlap, but are not members, of the nexus. No member of the nexus is spatially separate from any other member. Within the nexus are indefinitely many continuous streams of overlapping nexūs, each stream including the earliest and the last member of the enduring physical object. Thus an enduring physical object, like an Aristotelian substance, undergoes changes and adventures during the course of its existence. Whitehead's Process and Reality: In some contexts, especially in the theory of relativity in physics, the word 'event' refers to a single point in Minkowski or in Riemannian space-time. A point event is not a process in the sense of Whitehead's metaphysics. Neither is a countable sequence or array of points. A Whiteheadian process is most importantly characterized by extension in space-time, marked by a continuum of uncountably many points in a Minkowski or a Riemannian space-time. The word 'event', indicating a Whiteheadian actual entity, is not being used in the sense of a point event. Whitehead's Process and Reality: Whitehead's abstractions Whitehead's abstractions are conceptual entities that are abstracted from or derived from and founded upon his actual entities. Abstractions are themselves not actual entities. They are the only entities that can be real but are not actual entities. This statement is one form of Whitehead's 'ontological principle'. Whitehead's Process and Reality: An abstraction is a conceptual entity that refers to more than one single actual entity. Whitehead's ontology refers to importantly structured collections of actual entities as nexuses of actual entities. Collection of actual entities into a nexus emphasizes some aspect of those entities, and that emphasis is an abstraction, because it means that some aspects of the actual entities are emphasized or dragged away from their actuality, while other aspects are de-emphasized or left out or left behind. Whitehead's Process and Reality: 'Eternal object' is a term coined by Whitehead. It is an abstraction, a possibility, or pure potential. It can be ingredient into some actual entity. It is a principle that can give a particular form to an actual entity.Whitehead admitted indefinitely many eternal objects. An example of an eternal object is a number, such as the number 'two'. Whitehead held that eternal objects are abstractions of a very high degree of abstraction. Many abstractions, including eternal objects, are potential ingredients of processes. Whitehead's Process and Reality: Relation between actual entities and abstractions stated in the ontological principle For Whitehead, besides its temporal generation by the actual entities which are its contributory causes, a process may be considered as a concrescence of abstract ingredient eternal objects. God enters into every temporal actual entity. Whitehead's ontological principle is that whatever reality pertains to an abstraction is derived from the actual entities upon which it is founded or of which it is comprised. Whitehead's Process and Reality: Causation and concrescence of a process Concrescence is a term coined by Whitehead to show the process of jointly forming an actual entity that was without form, but about to manifest itself into an entity Actual full (satisfaction) based on datums or for information on the universe. The process of forming an actual entity is the case based on the existing datums. Concretion process can be regarded as subjectification process.Datum is a term coined by Whitehead to show the different variants of information possessed by actual entity. In process philosophy, datum is obtained through the events of concrescence. Every actual entity has a variety of datum. Commentary on Whitehead and on process philosophy: Whitehead is not an idealist in the strict sense. Whitehead's thought may be regarded as related to the idea of panpsychism (also known as panexperientialism, because of Whitehead's emphasis on experience). On God Whitehead's philosophy is complex, subtle, and nuanced regarding the concept of God". In Process and Reality Corrected Edition (1978), wherein regarding "God" the editors elaborate Whitehead's conception. Commentary on Whitehead and on process philosophy: He is the unconditioned actuality of conceptual feeling at the base of things; so that by reason of this primordial actuality, there is an order in the relevance of eternal objects to the process of creation.: 344  [...] The particularities of the actual world presuppose it; while it merely presupposes the general metaphysical character of creative advance, of which it is the primordial exemplification. [emphasis in original]: 344 Process philosophy, might be considered according to some theistic forms of religion to give God a special place in the universe of occasions of experience. Regarding Whitehead's use of the term "occasions" in reference to "God", Process and Reality Corrected Edition explains: 'Actual entities' - also termed 'actual occasions' - are the final real things of which the world is made up. There is no going behind actual entities to find anything more real. They differ among themselves: God is an actual entity, and so is the most trivial puff of existence in far-off empty space. But, though there are gradations of importance, and diversities of function, yet in the principles which actuality exemplifies all are on the same level. The final facts are, all alike, actual entities; and these actual entities are drops of experience, complex and interdependent.: 18 It also can be assumed within some forms of theology that a God encompasses all the other occasions of experience but also transcends them and this might lead to it being argued that Whitehead endorses some form of panentheism. Since, it is argued theologically, that "free will" is inherent to the nature of the universe, Whitehead's God is not omnipotent in Whitehead's metaphysics. God's role is to offer enhanced occasions of experience. God participates in the evolution of the universe by offering possibilities, which may be accepted or rejected. Whitehead's thinking here has given rise to process theology, whose prominent advocates include Charles Hartshorne, John B. Cobb, Jr., and Hans Jonas, who was also influenced by the non-theological philosopher Martin Heidegger. However, other process philosophers have questioned Whitehead's theology, seeing it as a regressive Platonism.Whitehead enumerated three essential natures of God. The primordial nature of God consists of all potentialities of existence for actual occasions, which Whitehead dubbed eternal objects. God can offer possibilities by ordering the relevance of eternal objects. The consequent nature of God prehends everything that happens in reality. As such, God experiences all of reality in a sentient manner. The last nature is the superjective. This is the way in which God's synthesis becomes a sense-datum for other actual entities. In some sense, God is prehended by existing actual entities. Legacy and applications: Biology In plant morphology, Rolf Sattler developed a process morphology (dynamic morphology) that overcomes the structure/process (or structure/function) dualism that is commonly taken for granted in biology. According to process morphology, structures such as leaves of plants do not have processes, they are processes.In evolution and in development, the nature of the changes of biological objects are considered by many authors to be more radical than in physical systems. In biology, changes are not just changes of state in a pre-given space, instead the space and more generally the mathematical structures required to understand object change over time. Legacy and applications: Ecology With its perspective that everything is interconnected, that all life has value, and that non-human entities are also experiencing subjects, process philosophy has played an important role in discourse on ecology and sustainability. The first book to connect process philosophy with environmental ethics was John B. Cobb, Jr.'s 1971 work, Is It Too Late: A Theology of Ecology. In a more recent book (2018) edited by John B. Cobb, Jr. and Wm. Andrew Schwartz, Putting Philosophy to Work: Toward an Ecological Civilization contributors explicitly explore the ways in which process philosophy can be put to work to address the most urgent issues facing our world today, by contributing to a transition toward an ecological civilization. That book emerged from the largest international conference held on the theme of ecological civilization (Seizing an Alternative: Toward an Ecological Civilization) which was organized by the Center for Process Studies in June 2015. The conference brought together roughly 2,000 participants from around the world and featured such leaders in the environmental movement as Bill McKibben, Vandana Shiva, John B. Cobb, Jr., Wes Jackson, and Sheri Liao. The notion of ecological civilization is often affiliated with the process philosophy of Alfred North Whitehead—especially in China. Legacy and applications: Mathematics In the philosophy of mathematics, some of Whitehead's ideas re-emerged in combination with cognitivism as the cognitive science of mathematics and embodied mind theses. Legacy and applications: Somewhat earlier, exploration of mathematical practice and quasi-empiricism in mathematics from the 1950s to 1980s had sought alternatives to metamathematics in social behaviours around mathematics itself: for instance, Paul Erdős's simultaneous belief in Platonism and a single "big book" in which all proofs existed, combined with his personal obsessive need or decision to collaborate with the widest possible number of other mathematicians. The process, rather than the outcomes, seemed to drive his explicit behaviour and odd use of language, as if the synthesis of Erdős and collaborators in seeking proofs, creating sense-datum for other mathematicians, was itself the expression of a divine will. Certainly, Erdős behaved as if nothing else in the world mattered, including money or love, as emphasized in his biography The Man Who Loved Only Numbers. Legacy and applications: Medicine Several fields of science and especially medicine seem to make liberal use of ideas in process philosophy, notably the theory of pain and healing of the late 20th century. The philosophy of medicine began to deviate somewhat from scientific method and an emphasis on repeatable results in the very late 20th century by embracing population thinking, and a more pragmatic approach to issues in public health, environmental health and especially mental health. In this latter field, R. D. Laing, Thomas Szasz and Michel Foucault were instrumental in moving medicine away from emphasis on "cures" and towards concepts of individuals in balance with their society, both of which are changing, and against which no benchmarks or finished "cures" were very likely to be measurable. Legacy and applications: Psychology In psychology, the subject of imagination was again explored more extensively since Whitehead, and the question of feasibility or "eternal objects" of thought became central to the impaired theory of mind explorations that framed postmodern cognitive science. A biological understanding of the most eternal object, that being the emerging of similar but independent cognitive apparatus, led to an obsession with the process "embodiment", that being, the emergence of these cognitions. Like Whitehead's God, especially as elaborated in J. J. Gibson's perceptual psychology emphasizing affordances, by ordering the relevance of eternal objects (especially the cognitions of other such actors), the world becomes. Or, it becomes simple enough for human beings to begin to make choices, and to prehend what happens as a result. These experiences may be summed in some sense but can only approximately be shared, even among very similar cognitions with identical DNA. An early explorer of this view was Alan Turing who sought to prove the limits of expressive complexity of human genes in the late 1940s, to put bounds on the complexity of human intelligence and so assess the feasibility of artificial intelligence emerging. Since 2000, Process Psychology has progressed as an independent academic and therapeutic discipline: In 2000, Michel Weber created the Whitehead Psychology Nexus: an open forum dedicated to the cross-examination of Alfred North Whitehead's process philosophy and the various facets of the contemporary psychological field. Legacy and applications: Philosophy of movement The philosophy of movement is a sub-area within process philosophy that treats processes as movements. It studies processes as flows, folds, and fields in historical patterns of centripetal, centrifugal, tensional, and elastic motion. See Thomas Nail's philosophy of movement and process materialism.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Process trailer** Process trailer: A process trailer, also known as insert trailer and low loader, is a trailer towed by a tracking vehicle for the purpose of being used as a moving camera platform. They are generally very low to the ground to give a realistic perspective of height and can be expanded in width to allow the camera to achieve a wider shot. Process trailers are most often used to shoot dialogue scenes inside cars or other vehicles while reducing risk for actors who would otherwise drive while delivering lines. The trailer is composed of a wheeled platform, low to the ground, with the vehicle secured on top. The vehicle on the platform is known as a "picture car". The platform itself is then towed by another vehicle with crew members and camera equipment to film the actors in the vehicle. Although process trailers are safer for actors, there is still a significant risk to the driver and passengers of the towing vehicle - for this reason, process trailers are often led by a police vehicles to prevent traffic accidents. In Australia, process trailers must be accompanied by police and may only be used with a permit.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Guluronic acid** Guluronic acid: Guluronic acid is a uronic acid monosaccharide that may be derived from gulose. l-Guluronic acid is a C-3 epimer of l-galacturonic acid and a C-5 epimer of d-mannuronic acid. Along with d-mannuronic acid, l-guluronic acid is a component of alginic acid, a polysaccharide found in brown algae. α-L-Guluronic acid has been found to bind divalent metal ions (such as calcium and strontium) through the carboxylate moiety and through the axial-equatorial-axial arrangement of hydroxyl groups found around the ring.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Collier's sign** Collier's sign: Collier's sign (also known as Collier's tucked lid sign or posterior fossa stare) is bilateral or unilateral eyelid retraction. Collier's sign: It is an accepted medical sign of a midbrain lesion, first described in 1927 by J Collier. With the eyes in the primary position, the sclera can be seen above the cornea, and further upgaze increases the distance between the eyelids and irises. Causes include upper dorsal midbrain supranuclear lesions such as Parinaud's syndrome, 'top of the basilar syndrome', midbrain infarction, neurodegeneration or tumour, multiple sclerosis, encephalitis, and Miller-Fisher syndrome. The cause is thought to be damage to the posterior commissure levator inhibitory fibres which originate in the M-group of neurons.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Bell boots** Bell boots: Bell boots, or overreach boots, are a type of protective boot worn by a horse. They encircle the horse's ankle, and protect the back of the pastern and the heels of the animal. Uses of bell boots: Bell boots are usually worn to prevent overreaching (when the horse "grabs" his front heels with the toes of his back feet, resulting in injury), or if the horse is wearing shoe studs, to protect him from accidentally injuring himself with the stud of the opposing hoof. In some cases a horse with corrective or poor shoeing wears shoes that protrude behind the foot, making it easier for a horse to overreach and spring or completely pull off the shoe. This is most commonly seen when the horse is jumping, working in mud or on a slippery surface, running cross-country, or longeing, and bell boots can help prevent this from occurring. Bell boots are occasionally worn when shipping a horse, if the bandages or boots used do not provide protection to the heel region, or if a horse tends to pull his front shoes by stepping on them with his back feet. Bell boots are also sometimes used when the horse is turned out, for extra protection or to help prevent him from accidentally pulling a shoe if he is especially exuberant while playing. Applying bell boots: Bell boots are usually made of rubber. They may be open, with Velcro or other fastenings to close them, or closed and slipped on over the hoof. Although open bell boots are the easiest to apply, close bell boots are more secure as they have no chance of slipping off. To apply closed bell boots, it is easiest to turn them inside out, before slipping them over the toe of the foot. It may also help to place them in warm water so they will expand before trying to put them on. A correctly sized bell boot should just touch the ground behind the bulbs of the heel while the horse is standing. The mouth of the bell boot should be just loose enough to fit a finger or two between it and the horse's pastern. Causes of discomfort: Most horses do not mind wearing bell boots and suffer no adverse effects when they are used properly. However, even a correctly fitted bell boot may chafe and cause discomfort to a horse if the material the boot is made of is exceedingly stiff or if the horse has especially sensitive skin.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Skills-based routing** Skills-based routing: Skills-based routing (SBR), or skills-based call routing, is a call-assignment strategy used in call centres to assign incoming calls to the most suitable agent, instead of simply choosing the next available agent. It is an enhancement to the automatic call distributor (ACD) systems found in most call centres. The need for skills-based routing has arisen as call centres have become larger and dealt with a wider variety of call types. In the past, agents answering calls were generally able to be assigned to only one queue taking one type of call. This meant that agents who could deal with a range of call types had to be manually reassigned to different queue at different times of the day to make the best use of their skills, or face being exposed to a wide variety of calls for which they were not trained. With skills-based routing, the skills needed for a particular call are often assessed by the dialled telephone number and the calling number or caller's identity, as well as choices made in any associated IVR system. Given this assessment, a skills-based routing system then attempts to match the call to a suitably trained agent—the thinking being that an agent with matching skills will be able to provide a better service than one who does not. As a consequence, the separate large queues that were characteristic of the ACD-driven call centre have disappeared. Instead, each caller seems to have their own waiting area that they may share with only one or two others. Instead of being served in the order of their arrival, calls are served as agents with appropriate skills become available. Manufacturers claim that this technology improves customer service, shortens call-handling time, makes training shorter and easier, and thus increases agent utilisation, productivity, and, hence, revenue. Skills-based routing has thus become a major selling point, over the simpler ACD that it replaces. Skills-based routing: However, independent analysts and consultants argue that the extra complexity of a skills-based routing system might not return the claimed benefits. They outline the difficulty of predetermining the needed skills and suggest that a poorly implemented skills-based routing system might result in poor service, because the wrong measures of service quality are being used.Theoretical work on skills-based routing system tends to be more limited, with researchers trying to identify suitable queueing theory and operations research models to represent the problems that are raised by skills-based routing systems. Skills-based routing: Some consider it a fruitful area of research. Others claim that the traditional queueing theory formula, such as Erlang-C, are no longer relevant for determining staff schedules, because they are inaccurate. They also imply that theoretical approaches will not be accurate, because of the complexity involved—arguing that simulation needs to be used instead. Although these claims need to be considered carefully, as it is argued also that the inaccuracies result from failing to understand the assumptions of the Erlang-C approach, instead of actual inaccuracy with the theory.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**KAlgebra** KAlgebra: KAlgebra is a mathematical graph calculator included in the KDE education package. While it is based on the MathML content markup language, knowledge of MathML is not required for use. The calculator includes numerical, logical, symbolic, and analytical functions, and can plot the results onto a 2D or 3D graph. KAlgebra is free and open source software, licensed under the GPL-2.0-or-later license. KAlgebra: KAlgebra has been mentioned by various media sources as free / open source educational programs. User interface and syntax: KAlgebra uses an intuitive algebraic syntax, similar to those used on modern graphing calculators. User-entered expressions are converted to MathML in the background, or they can be entered directly. The program is divided into four views, Console, 2D Graph, 3D Graph, and Dictionary. A series of calculations can be performed with user-defined scripts, which are macros that can be reused and shared. User interface and syntax: The dictionary includes a comprehensive list of all built-in functions in KAlgebra. Functions can be looked up with parameters, examples, formulas and sample plots. Over 100 functions and operations are currently supported. Graphing and dictionary: In the 2D and 3D graph views, functions can evaluated and plotted. Currently KAlgebra only supports 3D graphs explicitly dependent only on the x and y. Both views support defining the viewpoint. The user can hover their cursor over a line and find the exact X and Y values for 2D graphs, as well as create a live tangent line. Graphing and dictionary: In the 3D view, the user can control the viewpoint position with the keyboard's arrow keys, and zooming in and out is done with the W and S keys respectively. The user can also draw lines and make dots on the 3D graph and export the graph in various formats.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Vaginal microbicide** Vaginal microbicide: A vaginal microbicide is a microbicide for vaginal use. Most commonly such a product would be a topical gel or cream inserted into the vagina so that it may treat some infection in the vagina, such as types of vaginitis. Along with rectal microbicides, vaginal microbicides are currently the subject of medical research on microbicides for sexually transmitted diseases to determine the circumstances under which and the extent to which they provide protection against infection. Researchers are trying to develop a product which would act as protection against the contraction of a sexually transmitted infection during vaginal sexual intercourse. Vaginal microbicides for sexually transmitted diseases: Scientists are trying to develop effective microbicides to reduce the risk of contracting a sexually transmitted infection, and in particular, to reduce the risk of contracting HIV. Vaginal microbicides for sexually transmitted diseases: Target market Researchers have investigated who has interest in using a vaginal microbicide. Condoms are highly effective in preventing the transmission of infection, but worldwide, the decision to use condoms is more often a decision made by males than females. A vaginal microbicide which could prevent sexual transmission of infection would further empower women to influence the result of their sexual encounters. The demographic interested in using the produce included women with the following characteristics: The number of women interested in using such a product has been characterized as being significant enough to merit product development and marketing. Vaginal microbicides for sexually transmitted diseases: Characteristics The ideal vaginal microbicide would have the following characteristics: provide protection against infection not require application at the time of intercourse not harm the natural tissueThe criteria of not harming natural tissue has been the most troublesome aspect of product design. For HIV: Several unrelated chemical mechanisms have been proposed for vaginal microbicides. In all cases, the medicine would be contained in a gel or cream substrate and then inserted into the vagina, where the medicine would activate. Surfactants The first vaginal microbicide which researchers studied was nonoxynol-9, which acted as a surfactant. Blocking HIV binding PRO 2000, carrageenan, and cellulose sulphate have all been studied as microbicides to block HIV binding. Topical antiretrovirals Tenofovir has been studied as a topical antiretroviral. One example of a tenofovir study is CAPRISA 004.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**False peak** False peak: In mountaineering, a false peak or false summit is a peak that appears to be the pinnacle of the mountain but upon reaching, it turns out the summit is higher. False peaks can have significant and discouraging effects on climbers' psychological states by inducing feelings of lost hope or even failure. The term false peak can also be applied idiomatically to non-mountaineering activities where obstacles posing as the end goal produce the same psychological effects.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Neoeriocitrin** Neoeriocitrin: Neoeriocitrin is a 7-O-glycoside of the flavanone eriodictyol and the disaccharide neohesperidose (α-L-rhamnopyranosyl-(1→2)-β-D-glucopyranose). Note that the 'neo' in the name in this case does not refer to the position of the B-ring (which is not in a neo position), but refer to the glycosyl moiety.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Food Factor** Food Factor: Food Factor is the FIRST Lego League (FLL) competition for 2011-12; released on September 2. It focuses on food safety and methods to prevent contamination.This is the first year that the name of the challenge theme of FLL is different from Jr.FLL. Jr.FLL's theme for 2011-12 is Snack Attack. Project: Teams are tasked with identifying a food item and tracking its journey from creation to consumption. From this, teams identify potential sources of contamination and create solutions to those problems. Teams then share their project with the community and with judges at competition. Gameplay: The table performance portion of Food Factor is played on a 4 ft by 8 ft field rimmed by wood boards. At competition, two of these fields are placed together to form an 8 ft square. In each 2+1⁄2-minute match, a team competes on each field with their robot to earn up to 452 points manipulating the mission models. The touch penalty objects are "good" bacteria models. All 12 are worth 6 points each when located in base, but are removed every time the robot is touched outside of base. Gameplay: Missions All of the Food Factor missions relate to various food topics and food safety problems: Pollution Reversal - 4 points per ball (up to 8 points) Corn Harvest - up to 9 points Fishing - up to 18 points Pizza and Ice Cream - 7 points each (up to 14 points) Farm Fresh Produce - 9 points Distant Travel - 9 points Cooking Time - 14 points Storage Temperature - 20 points Pest Removal - 15 points each (up to 30 points) Refrigerated Ground Transport - up to 20 points Groceries - 2 points each (up to 24 points) Disinfect - up to 12 points each (up to 48 points) Hand Wash/Bacterial - 3 points each (up to 144 points) Hand Wash/Viral - up to 13 points Good Bacteria - 6 points each (up to 72 points in total)
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**C1QL1** C1QL1: The complement component 1, q subcomponent-like 1 (or C1QL1) is encoded by a gene located at chromosome 17q21.31. It is a secreted protein and is 258 amino acids in length. The protein is widely expressed but its expression is highest in the brain and may also be involved in regulation of motor control. The pre-mRNA of this protein is subject to RNA editing. Protein function: Its physiological function is unknown. It is a member of the C1Q domain proteins which have important signalling roles in inflammation and in adaptive immunity. RNA editing: Editing type The pre-mRNA of this protein is subject to A to I RNA editing, which is catalyzed by a family of adenosine deaminases acting on RNA (ADARs) that specifically recognize adenosines within double-stranded regions of pre-mRNAs and deaminate them to inosine. Inosines are recognised as guanosine by the cell's translational machinery. There are three members of the ADAR family: ADARs 1-3, with ADAR 1 and ADAR 2 being the only enzymatically active members. ADAR 3 is thought to have a regulatory role in the brain. ADAR 1 and ADAR 2 are widely expressed in tissues while ADAR 3 is restricted to the brain. The double-stranded regions of RNA are formed by base-pairing between residues in a region complementary to the region of the editing site. This complementary region is usually found in a neighbouring intron but can also be located in an exonic sequence. The region that pairs with the editing region is known as an Editing Complementary Sequence (ECS). RNA editing: Editing sites The candidate editing sites were determined experimentally by comparison of cDNA sequences and genomically encoded DNA from the same individual to avoid single nucleotide polymorphisms (SNPs). Two of the three editing sites found in mouse gene were found in the human transcript. However, only the Q/R site was detected in all RNA, with the T/A site detected just once. Both sites are found within exon 1.Q/R site This site is found in exon 1 at position 66. Editing results in a codon change from a Glutamine codon to an Arginine codon. RNA editing: T/A site This site is also found in exon 1, at position 63. It was only detected in one genomic sample indicating that the edited residue may be an SNP. However, the secondary structure of the RNA is predicted, around the editing site, to be highly conserved in mice and humans. This indicates that the T/A site may still be shown to be a site of A to I RNA editing. Editing at this site would result in an amino acid change from a Threonine to an Alanine. RNA editing: The ECS is also predicted to be found within exon 1 at a location 5' to the editing region. Editing regulation Editing is differentially expressed in the cerebellum and cortex. This regulation is also present in mice suggesting conservation of editing regulation. No editing has been detected in human lung, heart, kidney or spleen tissue. RNA editing: Evolutionary conservation The sequence of exon 1 is highly conserved in mammalian species and editing of the pre-mRNA of this protein is likely to occur in mice, rat, dog and cow as well as humans. Even though the ECS is not conserved in non-mammals, an alternative ECS has been predicted in Zebrafish with a similar structure but in a different location. The Ecs is found downstream of the editing sites. RNA editing: Effects on Protein structure These predicted editing sites result in the translation of an Arginine instead of a Glutamine at the Q/R site and an Alanine instead of a Threonine at the T/A site. These codon changes are nonsynomonous. Since the editing sites are located just before a collagen like trimerization domain, editing may effect protein oligomerization. This region is also likely to be a protease domain. It is not known if the amino acid changes caused by editing could have an effect on these domains.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Occupy movement hand signals** Occupy movement hand signals: The Occupy movement hand signals are a group of hand signals used by Occupy movement protesters to negotiate a consensus. Hand signals are used instead of conventional audible signals, like applause, shouts, or booing, because they do not interrupt the speaker using the human microphone, a system where the front of the crowd repeats the speaker so that the content can be heard at the back of the crowd. The signals have been compared to other hand languages used by soldiers, cliques and Wall Street traders.Between sharing of information on Facebook, Twitter, and other news reports, the hand signals have become common at other Occupy movement protest locations. Some protesters go to neighboring groups to assist in teaching the hand signals along with other general cooperation. There are YouTube videos showing the hand signals, though the signals are not universal at all locations. Example signals: Twinkles and down twinkles are referred to as a "temperature check". They indicate if a group is getting close to consensus. Twinkles are also known as "sparkle" or "jazz hands" or spirit fingers. Origins: In addition to commonalities with various sign languages, and cultural gestures, these or similar hand signals have been used by other groups and events prior to the Occupy Wall Street protests. These include: Camp for Climate Action The Woodcraft Folk Direct Action Network The 15-M Movement beginning in Spain 2011 UK Uncut Civil rights movement Quaker meetings Global Justice Movement Influence: Some followers of agile software development processes have drawn on the Occupy movement's hand signs in an attempt to improve communication during meetings, notably the UK's Government Digital Service.After the Occupy movements, these hand signals were used by other social movements such as the School strike for the climate, Ende Gelände and Extinction Rebellion.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Supercritical angle fluorescence microscopy** Supercritical angle fluorescence microscopy: Supercritical angle fluorescence microscopy (SAF) is a technique to detect and characterize fluorescent species (proteins, biomolecules, pharmaceuticals, etc.) and their behaviour close or even adsorbed or linked at surfaces. The method is able to observe molecules in a distance of less than 100 to 0 nanometer from the surface even in presence of high concentrations of fluorescent species around. Using an aspheric lens for excitation of a sample with laser light, fluorescence emitted by the specimen is collected above the critical angle of total internal reflection selectively and directed by a parabolic optics onto a detector. The method was invented in 1998 in the laboratories of Stefan Seeger at University of Regensburg/Germany and later at University of Zurich/Switzerland. SAF microscopy principle: The principle how SAF Microscopy works is as follows: A fluorescent specimen does not emit fluorescence isotropically when it comes close to a surface, but approximately 70% of the fluorescence emitted is directed into the solid phase. Here, the main part enters the solid body above the critical angle. When the emitter is located just 200 nm above the surface, fluorescent light entering the solid body above the critical angle is decreased dramatically. Hence, SAF Microscopy is ideally suited to discriminate between molecules and particles at or close to surfaces and all other specimen present in the bulk. Typical SAF-setup: The typical SAF setup consists of a laser line (typically 450-633 nm), which is reflected into the aspheric lens by a dichroic mirror. The lens focuses the laser beam in the sample, causing the particles to fluoresce. The fluorescent light then passes through a parabolic lens before reaching a detector, typically a photomultiplier tube or avalanche photodiode detector. It is also possible to arrange SAF elements as arrays, and image the output onto a CCD, allowing the detection of multiple analytes.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**HTree** HTree: An HTree is a specialized tree data structure for directory indexing, similar to a B-tree. They are constant depth of either one or two levels, have a high fanout factor, use a hash of the filename, and do not require balancing. The HTree algorithm is distinguished from standard B-tree methods by its treatment of hash collisions, which may overflow across multiple leaf and index blocks. HTree indexes are used in the ext3 and ext4 Linux filesystems, and were incorporated into the Linux kernel around 2.5.40. HTree indexing improved the scalability of Linux ext2 based filesystems from a practical limit of a few thousand files, into the range of tens of millions of files per directory. History: The HTree index data structure and algorithm were developed by Daniel Phillips in 2000 and implemented for the ext2 filesystem in February 2001. A port to the ext3 filesystem by Christopher Li and Andrew Morton in 2002 during the 2.5 kernel series added journal based crash consistency. With minor improvements, HTree continues to be used in ext4 in the Linux 3.x.x kernel series. Use: ext2 HTree indexes were originally developed for ext2 but the patch never made it to the official branch. The dir_index feature can be enabled when creating an ext2 filesystem, but the ext2 code won't act on it. ext3 HTree indexes are available in ext3 when the dir_index feature is enabled. ext4 HTree indexes are turned on by default in ext4. This feature is implemented in Linux kernel 2.6.23. HTree indexes is also used for file extents when a file needs more than the 4 extents stored in the inode. The large_dir feature of ext4 is implemented in Linux kernel 4.13. PHTree: PHTree (Physically stable HTree) is a derivation intended as a successor. It fixes all the known issues with HTree except for write multiplication. It is used in the Tux3 filesystem.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Opal** Opal: Opal is a hydrated amorphous form of silica (SiO2·nH2O); its water content may range from 3 to 21% by weight, but is usually between 6 and 10%. Due to its amorphous property, it is classified as a mineraloid, unlike crystalline forms of silica, which are considered minerals. It is deposited at a relatively low temperature and may occur in the fissures of almost any kind of rock, being most commonly found with limonite, sandstone, rhyolite, marl, and basalt. Opal: The name opal is believed to be derived from the Sanskrit word upala (उपल), which means 'jewel', and later the Greek derivative opállios (ὀπάλλιος), which means 'to see a change in color'. Opal: There are two broad classes of opal: precious and common. Precious opal displays play-of-color (iridescence); common opal does not. Play-of-color is defined as "a pseudo chromatic optical effect resulting in flashes of colored light from certain minerals, as they are turned in white light." The internal structure of precious opal causes it to diffract light, resulting in play-of-color. Depending on the conditions in which it formed, opal may be transparent, translucent, or opaque, and the background color may be white, black, or nearly any color of the visual spectrum. Black opal is considered the rarest, while white, gray, and green opals are the most common. Precious opal: Precious opal shows a variable interplay of internal colors, and though it is a mineraloid, it has an internal structure. At microscopic scales, precious opal is composed of silica spheres some 150–300 nm (5.9×10−6–1.18×10−5 in) in diameter in a hexagonal or cubic close-packed lattice. It was shown by J. V. Sanders in the mid-1960s that these ordered silica spheres produce the internal colors by causing the interference and diffraction of light passing through the microstructure of the opal. The regularity of the sizes and the packing of these spheres is a prime determinant of the quality of precious opal. Where the distance between the regularly packed planes of spheres is around half the wavelength of a component of visible light, the light of that wavelength may be subject to diffraction from the grating created by the stacked planes. The colors that are observed are determined by the spacing between the planes and the orientation of planes with respect to the incident light. The process can be described by Bragg's law of diffraction. Precious opal: Visible light cannot pass through large thicknesses of the opal. This is the basis of the optical band gap in a photonic crystal. The notion that opals are photonic crystals for visible light was expressed in 1995 by Vasily Astratov's group. In addition, microfractures may be filled with secondary silica and form thin lamellae inside the opal during its formation. The term opalescence is commonly used to describe this unique and beautiful phenomenon, which in gemology is termed play of color. In gemology, opalescence is applied to the hazy-milky-turbid sheen of common or potch opal which does not show a play of color. Opalescence is a form of adularescence. Precious opal: For gemstone use, most opal is cut and polished to form a cabochon. "Natural" opal refers to polished stones consisting wholly of precious opal. Opals too thin to produce a "natural" opal may be combined with other materials to form "composite" gems. An opal doublet consists of a relatively thin layer of precious opal, backed by a layer of dark-colored material, most commonly ironstone, dark or black common opal (potch), onyx, or obsidian. The darker backing emphasizes the play of color and results in a more attractive display than a lighter potch. An opal triplet is similar to a doublet but has a third layer, a domed cap of clear quartz or plastic on the top. The cap takes a high polish and acts as a protective layer for the opal. The top layer also acts as a magnifier, to emphasize the play of color of the opal beneath, which is often an inferior specimen or an extremely thin section of precious opal. Triplet opals tend to have a more artificial appearance and are not classed as precious gemstones, but rather "composite" gemstones. Jewelry applications of precious opal can be somewhat limited by opal's sensitivity to heat due primarily to its relatively high water content and predisposition to scratching. Combined with modern techniques of polishing, a doublet opal can produce a similar effect to Natural black or boulder opal at a fraction of the price. Doublet opal also has the added benefit of having genuine opal as the top visible and touchable layer, unlike triplet opals. Common opal: Besides the gemstone varieties that show a play of color, the other kinds of common opal include the milk opal, milky bluish to greenish (which can sometimes be of gemstone quality); resin opal, which is honey-yellow with a resinous luster; wood opal, which is caused by the replacement of the organic material in wood with opal; menilite, which is brown or grey; hyalite, a colorless glass-clear opal sometimes called Muller's glass; geyserite, also called siliceous sinter, deposited around hot springs or geysers; and diatomaceous earth, the accumulations of diatom shells or tests. Common opal often displays a hazy-milky-turbid sheen from within the stone. In gemology, this optical effect is strictly defined as opalescence which is a form of adularescence. Other varieties of opal: "Girasol opal" is a term sometimes mistakenly and improperly used to refer to fire opals, as well as a type of transparent to semitransparent type milky quartz from Madagascar which displays an asterism, or star effect when cut properly. However, the true girasol opal is a type of hyalite opal that exhibits a bluish glow or sheen that follows the light source around. It is not a play of color as seen in precious opal, but rather an effect from microscopic inclusions. It is also sometimes referred to as water opal, too, when it is from Mexico. The two most notable locations of this type of opal are Oregon and Mexico.A Peruvian opal (also called blue opal) is a semi-opaque to opaque blue-green stone found in Peru, which is often cut to include the matrix in the more opaque stones. It does not display a play of color. Blue opal also comes from Oregon and Idaho in the Owyhee region, as well as from Nevada around the Virgin Valley.Opal is also formed by diatoms. Diatoms are a form of algae that, when they die, often form layers at the bottoms of lakes, bays, or oceans. Their cell walls are made up of hydrated silicon dioxide which gives them [structural coloration] and therefore the appearance of tiny opals when viewed under a microscope. These cell walls or "tests" form the “grains” for the diatomaceous earth. This sedimentary rock is white, opaque, and chalky in texture. Diatomite has multiple industrial uses such as filtering or adsorbing since it has a fine particle size and very porous nature, and gardening to increase water absorption. History: Opal was rare and very valuable in antiquity. In Europe, it was a gem prized by royalty. Until the opening of vast deposits in Australia in the 19th century the only known source was Červenica beyond the Roman frontier in Slovakia. Opal is the national gemstone of Australia. Sources: The primary sources of opal are Australia and Ethiopia, but because of inconsistent and widely varying accountings of their respective levels of extraction, it is difficult to accurately state what proportion of the global supply of opal comes from either country. Sources: Australian opal has been cited as accounting for 95–97% of the world's supply of precious opal, with the state of South Australia accounting for 80% of the world's supply. In 2012, Ethiopian opal production was estimated to be 14,000 kg (31,000 lb) by the United States Geological Survey. USGS data from the same period (2012), reveals Australian opal production to be $41 million. Because of the units of measurement, it is not possible to directly compare Australian and Ethiopian opal production, but these data and others suggest that the traditional percentages given for Australian opal production may be overstated. Yet, the validity of data in the USGS report appears to conflict with that of Laurs et al. and Mesfin, who estimated the 2012 Ethiopian opal output (from Wegal Tena) to be only 750 kg (1,650 lb). Sources: Australia The town of Coober Pedy in South Australia is a major source of opal. The world's largest and most valuable gem opal "Olympic Australis" was found in August 1956 at the "Eight Mile" opal field in Coober Pedy. It weighs 17,000 carats (3.4 kg; 7.5 lb) and is 11 inches (280 mm) long, with a height of 4+3⁄4 in (120 mm) and a width of 4+1⁄2 in (110 mm).The Mintabie Opal Field in South Australia located about 250 km (160 mi) northwest of Coober Pedy has also produced large quantities of crystal opal and the rarer black opal. Over the years, it has been sold overseas incorrectly as Coober Pedy opal. The black opal is said to be some of the best examples found in Australia. Sources: Andamooka in South Australia is also a major producer of matrix opal, crystal opal, and black opal. Another Australian town, Lightning Ridge in New South Wales, is the main source of black opal, opal containing a predominantly dark background (dark gray to blue-black displaying the play of color), collected from the Griman Creek Formation. Boulder opal consists of concretions and fracture fillings in a dark siliceous ironstone matrix. It is found sporadically in western Queensland, from Kynuna in the north, to Yowah and Koroit in the south. Its largest quantities are found around Jundah and Quilpie in South West Queensland. Australia also has opalized fossil remains, including dinosaur bones in New South Wales and South Australia, and marine creatures in South Australia. Sources: Ethiopia It has been reported that Northern African opal was used to make tools as early as 4000 BC. The first published report of gem opal from Ethiopia appeared in 1994, with the discovery of precious opal in the Menz Gishe District, North Shewa Province. The opal, found mostly in the form of nodules, was of volcanic origin and was found predominantly within weathered layers of rhyolite. This Shewa Province opal was mostly dark brown in color and had a tendency to crack. These qualities made it unpopular in the gem trade. In 2008, a new opal deposit was found approximately 180 km north of Shewa Province, near the town of Wegel Tena, in Ethiopia's Wollo Province. The Wollo Province opal was different from the previous Ethiopian opal finds in that it more closely resembled the sedimentary opals of Australia and Brazil, with a light background and often vivid play-of-color. Wollo Province opal, more commonly referred to as "Welo" or "Wello" opal, has become the dominant Ethiopian opal in the gem trade. Sources: Virgin Valley, Nevada The Virgin Valley opal fields of Humboldt County in northern Nevada produce a wide variety of precious black, crystal, white, fire, and lemon opal. The black fire opal is the official gemstone of Nevada. Most of the precious opal is partial wood replacement. The precious opal is hosted and found in situ within a subsurface horizon or zone of bentonite, which is considered a "lode" deposit. Opals which have weathered out of the in situ deposits are alluvial and considered placer deposits. Miocene-age opalised teeth, bones, fish, and a snake head have been found. Some of the opal has high water content and may desiccate and crack when dried. The largest producing mines of Virgin Valley have been the famous Rainbow Ridge, Royal Peacock, Bonanza, Opal Queen, and WRT Stonetree/Black Beauty mines. The largest unpolished black opal in the Smithsonian Institution, known as the "Roebling opal", came out of the tunneled portion of the Rainbow Ridge Mine in 1917, and weighs 2,585 carats (517.0 g; 18.24 oz). The largest polished black opal in the Smithsonian Institution comes from the Royal Peacock opal mine in the Virgin Valley, weighing 160 carats (32 g; 1.1 oz), known as the "Black Peacock". Sources: Mexico Fire opal is a transparent to translucent opal with warm body colors of yellow to orange to red. Although fire opals don't usually show any play of color, they occasionally exhibit bright green flashes. The most famous source of fire opals is the state of Querétaro in Mexico; these opals are commonly called Mexican fire opals. Fire opals that do not show a play of color are sometimes referred to as jelly opals. Mexican opals are sometimes cut in their rhyolitic host material if it is hard enough to allow cutting and polishing. This type of Mexican opal is referred to as a Cantera opal. Another type of opal from Mexico, referred to as Mexican water opal, is a colorless opal that exhibits either a bluish or golden internal sheen.Opal occurs in significant quantity and variety in central Mexico, where mining and production first originated in the state of Querétaro. In this region the opal deposits are located mainly in the mountain ranges of three municipalities: Colón, Tequisquiapan and Ezequiel Montes. During the 1960s through to the mid-1970s, the Querétaro mines were heavily mined. Today's opal miners report that it was much easier to find quality opals with a lot of fire and play of color back then, whereas today the gem-quality opals are very hard to come by and command hundreds of US dollars or more. The orange-red background color is characteristic of all "fire opals," including "Mexican fire opal". Sources: The oldest mine in Querétaro is Santa Maria del Iris. This mine was opened around 1870 and has been reopened at least 28 times since. At the moment there are about 100 mines in the regions around Querétaro, but most of them are now closed. The best quality of opals came from the mine Santa Maria del Iris, followed by La Hacienda la Esperanza, Fuentezuelas, La Carbonera, and La Trinidad. Important deposits in the state of Jalisco were not discovered until the late 1950s. Sources: In 1957, Alfonso Ramirez (of Querétaro) accidentally discovered the first opal mine in Jalisco: La Unica, located on the outer area of the volcano of Tequila, near the Huitzicilapan farm in Magdalena. By 1960 there were around 500 known opal mines in this region alone. Other regions of the country that also produce opals (of lesser quality) are Guerrero, which produces an opaque opal similar to the opals from Australia (some of these opals are carefully treated with heat to improve their colors so high-quality opals from this area may be suspect). There are also some small opal mines in Morelos, Durango, Chihuahua, Baja California, Guanajuato, Puebla, Michoacán, and Estado de México. Sources: Other locations Another source of white base opal or creamy opal in the United States is Spencer, Idaho. A high percentage of the opal found there occurs in thin layers. Other significant deposits of precious opal around the world can be found in the Czech Republic, Canada, Slovakia, Hungary, Turkey, Indonesia, Brazil (in Pedro II, Piauí), Honduras (more precisely in Erandique), Guatemala and Nicaragua. In late 2008, NASA announced the discovery of opal deposits on Mars. Synthetic opal: Opals of all varieties have been synthesized experimentally and commercially. The discovery of the ordered sphere structure of precious opal led to its synthesis by Pierre Gilson in 1974. The resulting material is distinguishable from natural opal by its regularity; under magnification, the patches of color are seen to be arranged in a "lizard skin" or "chicken wire" pattern. Furthermore, synthetic opals do not fluoresce under ultraviolet light. Synthetics are also generally lower in density and are often highly porous. Synthetic opal: Opals which have been created in a laboratory are often termed "lab-created opals", which, while classifiable as man-made and synthetic, are very different from their resin-based counterparts which are also considered man-made and synthetic. The term "synthetic" implies that a stone has been created to be chemically and structurally indistinguishable from a genuine one, and genuine opal contains no resins or polymers. The finest modern lab-created opals do not exhibit the lizard skin or columnar patterning of earlier lab-created varieties, and their patterns are non-directional. They can still be distinguished from genuine opals, however, by their lack of inclusions and the absence of any surrounding non-opal matrix. While many genuine opals are cut and polished without a matrix, the presence of irregularities in their play-of-color continues to mark them as distinct from even the best lab-created synthetics. Synthetic opal: Other research in macroporous structures have yielded highly ordered materials that have similar optical properties to opals and have been used in cosmetics. Synthetic opals are also deeply investigated in photonics for sensing and light management purposes. Local atomic structure of opals: The lattice of spheres of opal that cause interference with light is several hundred times larger than the fundamental structure of crystalline silica. As a mineraloid, no unit cell describes the structure of opal. Nevertheless, opals can be roughly divided into those that show no signs of crystalline order (amorphous opal) and those that show signs of the beginning of crystalline order, commonly termed cryptocrystalline or microcrystalline opal. Dehydration experiments and infrared spectroscopy have shown that most of the H2O in the formula of SiO2·nH2O of opals is present in the familiar form of clusters of molecular water. Isolated water molecules, and silanols, structures such as SiOH, generally form a lesser proportion of the total and can reside near the surface or in defects inside the opal. Local atomic structure of opals: The structure of low-pressure polymorphs of anhydrous silica consists of frameworks of fully corner bonded tetrahedra of SiO4. The higher temperature polymorphs of silica cristobalite and tridymite are frequently the first to crystallize from amorphous anhydrous silica, and the local structures of microcrystalline opals also appear to be closer to that of cristobalite and tridymite than to quartz. The structures of tridymite and cristobalite are closely related and can be described as hexagonal and cubic close-packed layers. It is therefore possible to have intermediate structures in which the layers are not regularly stacked. Local atomic structure of opals: Microcrystalline opal Microcrystalline opal or Opal-CT has been interpreted as consisting of clusters of stacked cristobalite and tridymite over very short length scales. The spheres of opal in microcrystalline opal are themselves made up of tiny nanocrystalline blades of cristobalite and tridymite. Microcrystalline opal has occasionally been further subdivided in the literature. Water content may be as high as 10 wt%. Opal-CT, also called lussatine or lussatite, is interpreted as consisting of localized order of α-cristobalite with a lot of stacking disorder. Typical water content is about 1.5 wt%. Local atomic structure of opals: Noncrystalline opal Two broad categories of noncrystalline opals, sometimes just referred to as "opal-A" ("A" stands for "amorphous"), have been proposed. The first of these is opal-AG consisting of aggregated spheres of silica, with water filling the space in between. Precious opal and potch opal are generally varieties of this, the difference being in the regularity of the sizes of the spheres and their packing. The second "opal-A" is opal-AN or water-containing amorphous silica-glass. Hyalite is another name for this. Local atomic structure of opals: Noncrystalline silica in siliceous sediments is reported to gradually transform to opal-CT and then opal-C as a result of diagenesis, due to the increasing overburden pressure in sedimentary rocks, as some of the stacking disorder is removed. Opal surface chemical groups The surface of opal in contact with water is covered by siloxane bonds (≡Si–O–Si≡) and silanol groups (≡Si–OH). This makes the opal surface very hydrophilic and capable of forming numerous hydrogen bonds. Etymology: The word 'opal' is adapted from the Latin term opalus. The origin of this word in turn is a matter of debate, but most modern references suggest it is adapted from the Sanskrit word úpala meaning ‘precious stone’.References to the gem are made by Pliny the Elder. It is suggested to have been adapted from Ops, the wife of Saturn, and goddess of fertility. The portion of Saturnalia devoted to Ops was "Opalia", similar to opalus. Etymology: Another common claim that the term is adapted from the Ancient Greek word, opallios. This word has two meanings, one is related to "seeing" and forms the basis of the English words like "opaque"; the other is "other" as in "alias" and "alter". It is claimed that opalus combined these uses, meaning "to see a change in color". However, historians have noted the first appearances of opallios do not occur until after the Romans had taken over the Greek states in 180 BC and they had previously used the term paederos.However, the argument for the Sanskrit origin is strong. The term first appears in Roman references around 250 BC, at a time when the opal was valued above all other gems. The opals were supplied by traders from the Bosporus, who claimed the gems were being supplied from India. Before this, the stone was referred to by a variety of names, but these fell from use after 250 BC. Historical superstitions: In the Middle Ages, opal was considered a stone that could provide great luck because it was believed to possess all the virtues of each gemstone whose color was represented in the color spectrum of the opal. It was also said to grant invisibility if wrapped in a fresh bay leaf and held in the hand. As a result, the opal was seen as the patron gemstone for thieves during the medieval period. Following the publication of Sir Walter Scott's Anne of Geierstein in 1829, opal acquired a less auspicious reputation. In Scott's novel, the Baroness of Arnheim wears an opal talisman with supernatural powers. When a drop of holy water falls on the talisman, the opal turns into a colorless stone and the Baroness dies soon thereafter. Due to the popularity of Scott's novel, people began to associate opals with bad luck and death. Within a year of the publishing of Scott's novel in April 1829, the sale of opals in Europe dropped by 50%, and remained low for the next 20 years or so.Even as recently as the beginning of the 20th century, it was believed that when a Russian saw an opal among other goods offered for sale, he or she should not buy anything more, as the opal was believed to embody the evil eye.Opal is considered the birthstone for people born in October. Examples: The Olympic Australis, the world's largest and most valuable gem opal, found in Coober Pedy The Andamooka Opal, presented to Queen Elizabeth II, also known as the Queen's Opal The Addyman Plesiosaur from Andamooka, "the finest known opalised skeleton on Earth" The Burning of Troy, the now-lost opal presented to Joséphine de Beauharnais by Napoleon I of France and the first named opal The Flame Queen Opal The Halley's Comet Opal, the world's largest uncut black opal Although the clock faces above the information stand in Grand Central Terminal in New York City are often said to be opal, they are in fact opalescent glass The Roebling Opal, Smithsonian Institution The Galaxy Opal, listed as the "World's Largest Polished Opal" in the 1992 Guinness Book of Records The Rainbow Virgin, "the finest crystal opal specimen ever unearthed" The Sea of Opal, the largest black opal in the world The Fire of Australia, assumed to be "the finest uncut opal in existence" Beverly the Bug, the first known example of an opal with an insect inclusion
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Trophic level** Trophic level: The trophic level of an organism is the position it occupies in a food web. A food chain is a succession of organisms that eat other organisms and may, in turn, be eaten themselves. The trophic level of an organism is the number of steps it is from the start of the chain. A food web starts at trophic level 1 with primary producers such as plants, can move to herbivores at level 2, carnivores at level 3 or higher, and typically finish with apex predators at level 4 or 5. The path along the chain can form either a one-way flow or a food "web". Ecological communities with higher biodiversity form more complex trophic paths. Trophic level: The word trophic derives from the Greek τροφή (trophē) referring to food or nourishment. History: The concept of trophic level was developed by Raymond Lindeman (1942), based on the terminology of August Thienemann (1926): "producers", "consumers", and "reducers" (modified to "decomposers" by Lindeman). Overview: The three basic ways in which organisms get food are as producers, consumers, and decomposers. Overview: Producers (autotrophs) are typically plants or algae. Plants and algae do not usually eat other organisms, but pull nutrients from the soil or the ocean and manufacture their own food using photosynthesis. For this reason, they are called primary producers. In this way, it is energy from the sun that usually powers the base of the food chain. An exception occurs in deep-sea hydrothermal ecosystems, where there is no sunlight. Here primary producers manufacture food through a process called chemosynthesis. Overview: Consumers (heterotrophs) are species that cannot manufacture their own food and need to consume other organisms. Animals that eat primary producers (like plants) are called herbivores. Animals that eat other animals are called carnivores, and animals that eat both plants and other animals are called omnivores. Overview: Decomposers (detritivores) break down dead plant and animal material and wastes and release it again as energy and nutrients into the ecosystem for recycling. Decomposers, such as bacteria and fungi (mushrooms), feed on waste and dead matter, converting it into inorganic chemicals that can be recycled as mineral nutrients for plants to use again.Trophic levels can be represented by numbers, starting at level 1 with plants. Further trophic levels are numbered subsequently according to how far the organism is along the food chain. Overview: Level 1 Plants and algae make their own food and are called producers. Level 2 Herbivores eat plants and are called primary consumers. Level 3 Carnivores that eat herbivores are called secondary consumers. Level 4 Carnivores that eat other carnivores are called tertiary consumers. Apex predator By definition, healthy adult apex predators have no predators (with members of their own species a possible exception) and are at the highest numbered level of their food web. Overview: In real-world ecosystems, there is more than one food chain for most organisms, since most organisms eat more than one kind of food or are eaten by more than one type of predator. A diagram that sets out the intricate network of intersecting and overlapping food chains for an ecosystem is called its food web. Decomposers are often left off food webs, but if included, they mark the end of a food chain. Thus food chains start with primary producers and end with decay and decomposers. Since decomposers recycle nutrients, leaving them so they can be reused by primary producers, they are sometimes regarded as occupying their own trophic level.The trophic level of a species may vary if it has a choice of diet. Virtually all plants and phytoplankton are purely phototrophic and are at exactly level 1.0. Many worms are at around 2.1; insects 2.2; jellyfish 3.0; birds 3.6. A 2013 study estimates the average trophic level of human beings at 2.21, similar to pigs or anchovies. This is only an average, and plainly both modern and ancient human eating habits are complex and vary greatly. For example, a traditional Inuit living on a diet consisting primarily of seals would have a trophic level of nearly 5. Biomass transfer efficiency: In general, each trophic level relates to the one below it by absorbing some of the energy it consumes, and in this way can be regarded as resting on, or supported by, the next lower trophic level. Food chains can be diagrammed to illustrate the amount of energy that moves from one feeding level to the next in a food chain. This is called an energy pyramid. The energy transferred between levels can also be thought of as approximating to a transfer in biomass, so energy pyramids can also be viewed as biomass pyramids, picturing the amount of biomass that results at higher levels from biomass consumed at lower levels. However, when primary producers grow rapidly and are consumed rapidly, the biomass at any one moment may be low; for example, phytoplankton (producer) biomass can be low compared to the zooplankton (consumer) biomass in the same area of ocean.The efficiency with which energy or biomass is transferred from one trophic level to the next is called the ecological efficiency. Consumers at each level convert on average only about 10% of the chemical energy in their food to their own organic tissue (the ten-per cent law). For this reason, food chains rarely extend for more than 5 or 6 levels. At the lowest trophic level (the bottom of the food chain), plants convert about 1% of the sunlight they receive into chemical energy. It follows from this that the total energy originally present in the incident sunlight that is finally embodied in a tertiary consumer is about 0.001% Evolution: Both the number of trophic levels and the complexity of relationships between them evolve as life diversifies through time, the exception being intermittent mass extinction events. Fractional trophic levels: Food webs largely define ecosystems, and the trophic levels define the position of organisms within the webs. But these trophic levels are not always simple integers, because organisms often feed at more than one trophic level. For example, some carnivores also eat plants, and some plants are carnivores. A large carnivore may eat both smaller carnivores and herbivores; the bobcat eats rabbits, but the mountain lion eats both bobcats and rabbits. Animals can also eat each other; the bullfrog eats crayfish and crayfish eat young bullfrogs. The feeding habits of a juvenile animal, and, as a consequence, its trophic level, can change as it grows up. Fractional trophic levels: The fisheries scientist Daniel Pauly sets the values of trophic levels to one in plants and detritus, two in herbivores and detritivores (primary consumers), three in secondary consumers, and so on. The definition of the trophic level, TL, for any consumer species is: TLi=1+∑j(TLj⋅DCij) where TLj is the fractional trophic level of the prey j, and DCij represents the fraction of j in the diet of i. That is, the consumer trophic level is one plus the weighted average of how much different trophic levels contribute to its food. Fractional trophic levels: In the case of marine ecosystems, the trophic level of most fish and other marine consumers takes a value between 2.0 and 5.0. The upper value, 5.0, is unusual, even for large fish, though it occurs in apex predators of marine mammals, such as polar bears and orcas.In addition to observational studies of animal behavior, and quantification of animal stomach contents, trophic level can be quantified through stable isotope analysis of animal tissues such as muscle, skin, hair, bone collagen. This is because there is a consistent increase in the nitrogen isotopic composition at each trophic level caused by fractionations that occur with the synthesis of biomolecules; the magnitude of this increase in nitrogen isotopic composition is approximately 3–4‰. Mean trophic level: In fisheries, the mean trophic level for the fisheries catch across an entire area or ecosystem is calculated for year y as: TLy=∑i(TLi⋅Yiy)∑iYiy where Yiy is the annual catch of the species or group i in year y, and TLi is the trophic level for species i as defined above.Fish at higher trophic levels usually have a higher economic value, which can result in overfishing at the higher trophic levels. Earlier reports found precipitous declines in mean trophic level of fisheries catch, in a process known as fishing down the food web. However, more recent work finds no relation between economic value and trophic level; and that mean trophic levels in catches, surveys and stock assessments have not in fact declined, suggesting that fishing down the food web is not a global phenomenon. However Pauly et al. note that trophic levels peaked at 3.4 in 1970 in the northwest and west-central Atlantic, followed by a subsequent decline to 2.9 in 1994. They report a shift away from long-lived, piscivorous, high-trophic-level bottom fishes, such as cod and haddock, to short-lived, planktivorous, low-trophic-level invertebrates (e.g., shrimp) and small, pelagic fish (e.g., herring). This shift from high-trophic-level fishes to low-trophic-level invertebrates and fishes is a response to changes in the relative abundance of the preferred catch. They consider that this is part of the global fishery collapse, which finds an echo in the overfished Mediterranean Sea.Humans have a mean trophic level of about 2.21, about the same as a pig or an anchovy. FiB index: Since biomass transfer efficiencies are only about 10%, it follows that the rate of biological production is much greater at lower trophic levels than it is at higher levels. Fisheries catch, at least, to begin with, will tend to increase as the trophic level declines. At this point the fisheries will target species lower in the food web. In 2000, this led Pauly and others to construct a "Fisheries in Balance" index, usually called the FiB index. The FiB index is defined, for any year y, by log ⁡Yy/(TE)TLyY0/(TE)TL0 where Yy is the catch at year y, TLy is the mean trophic level of the catch at year y, Y0 is the catch, TL0 the mean trophic level of the catch at the start of the series being analyzed, and TE is the transfer efficiency of biomass or energy between trophic levels. FiB index: The FiB index is stable (zero) over periods of time when changes in trophic levels are matched by appropriate changes in the catch in the opposite direction. The index increases if catches increase for any reason, e.g. higher fish biomass, or geographic expansion. Such decreases explain the "backward-bending" plots of trophic level versus catch originally observed by Pauly and others in 1998. Tritrophic and other interactions: One aspect of trophic levels is called tritrophic interaction. Ecologists often restrict their research to two trophic levels as a way of simplifying the analysis; however, this can be misleading if tritrophic interactions (such as plant–herbivore–predator) are not easily understood by simply adding pairwise interactions (plant-herbivore plus herbivore–predator, for example). Significant interactions can occur between the first trophic level (plant) and the third trophic level (a predator) in determining herbivore population growth, for example. Simple genetic changes may yield morphological variants in plants that then differ in their resistance to herbivores because of the effects of the plant architecture on enemies of the herbivore. Plants can also develop defenses against herbivores such as chemical defenses.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Cetrimonium bromide** Cetrimonium bromide: Cetrimonium bromide ([(C16H33)N(CH3)3]Br; cetyltrimethylammonium bromide; hexadecyltrimethylammonium bromide; CTAB) is a quaternary ammonium surfactant. Cetrimonium bromide: It is one of the components of the topical antiseptic cetrimide. The cetrimonium (hexadecyltrimethylammonium) cation is an effective antiseptic agent against bacteria and fungi. It is also one of the main components of some buffers for the extraction of DNA. It has been widely used in synthesis of gold nanoparticles (e.g., spheres, rods, bipyramids), mesoporous silica nanoparticles (e.g., MCM-41), and hair conditioning products. The closely related compounds cetrimonium chloride and cetrimonium stearate are also used as topical antiseptics and may be found in many household products such as shampoos and cosmetics. CTAB, due to its relatively high cost, is typically only used in select cosmetics. Cetrimonium bromide: As with most surfactants, CTAB forms micelles in aqueous solutions. At 303 K (30 °C) it forms micelles with aggregation number 75-120 (depending on method of determination; average ~95) and degree of ionization, α = 0.2–0.1 (fractional charge; from low to high concentration). The binding constant (K°) of Br− counterion to a CTA+ micelle at 303 K (30 °C) is ca. 400 M-1. This value is calculated from Br− and CTA+ ion selective electrode measurements and conductometry data by using literature data for micelle size (r = ~3 nm), extrapolated to the critical micelle concentration of 1 mM. However, K° varies with total surfactant concentration so it is extrapolated to the point at which micelle concentration is zero. Applications: Biological Cell lysis is a convenient tool to isolate certain macromolecules that exist primarily inside of the cell. Cell membranes consist of hydrophilic and lipophilic endgroups. Therefore, detergents are often used to dissolve these membranes since they interact with both polar and nonpolar endgroups. CTAB has emerged as the preferred choice for biological use because it maintains the integrity of precipitated DNA during its isolation. Cells typically have high concentrations of macromolecules, such as glycoproteins and polysaccharides, that co-precipitate with DNA during the extraction process, causing the extracted DNA to lose purity. The positive charge of the CTAB molecule allows it to denature these molecules that would interfere with this isolation. Applications: Medical CTAB has been shown to have potential use as an apoptosis-promoting anticancer agent for head and neck cancer (HNC). In vitro, CTAB interacted additively with γ radiation and cisplatin, two standard HNC therapeutic agents. CTAB exhibited anticancer cytotoxicity against several HNC cell lines with minimal effects on normal fibroblasts, a selectivity that exploits cancer-specific metabolic aberrations. In vivo, CTAB ablated tumor-forming capacity of FaDu cells and delayed growth of established tumors. Thus, using this approach, CTAB was identified as a potential apoptogenic quaternary ammonium compound possessing in vitro and in vivo efficacy against HNC models. CTAB is also recommended by the World Health Organisation (WHO) as a purification agent in the downstream vaccine processing of polysaccharide vaccines. Applications: Protein electrophoresis Glycoproteins form broad, fuzzy bands in SDS-PAGE (Laemmli-electrophoresis) because of their broad distribution of negative charges. Using positively charged detergents such as CTAB will avoid issues associated with glycoproteins. Proteins can be blotted from CTAB-gels in analogy to western blots ("eastern blot"), and Myelin-associated high hydrophobic protein can be analyzed using CTAB 2-DE. Applications: DNA extraction CTAB serves as an important surfactant in the DNA extraction buffer system to remove membrane lipids and promote cell lysis. Separation is also successful when the tissue contains high amounts of polysaccharides. CTAB binds to the polysaccharides when the salt concentration is high, thus removing polysaccharides from solution. A typical recipe can be to combine 100 mL of 1 M Tris HCl (pH 8.0), 280 mL 5 M NaCl, 40 mL of 0.5 M EDTA, and 20 g of CTAB then add double distilled water (ddH2O) to bring total volume to 1 L. Nanoparticle synthesis: Surfactants play a key role in nanoparticle synthesis by adsorbing to the surface of the forming nanoparticle and lowering its surface energy. Surfactants also help to prevent aggregation (e.g. via DLVO mechanisms). Nanoparticle synthesis: Au nanoparticle synthesis Gold (Au) nanoparticles are interesting to researchers because of their unique properties that can be used in applications such as catalysis, optics, electronics, sensing, and medicine. Control of nanoparticle size and shape is important in order to tune its properties. CTAB has been a widely used reagent to both impart stability to these nanoparticles as well as control their morphologies. CTAB may play a role in controlling nanoparticle size and shape by selectively or more strongly binding to various emerging crystal facets. Nanoparticle synthesis: Some of this control originates from the reaction of CTAB with other reagents in the gold nanoparticle synthesis. For example, in aqueous gold nanoparticle syntheses, chlorauric acid (HAuCl4) may react with CTAB to create a CTA+-AuCl−4 complex. The gold complex is then reacted with ascorbic acid to produce hydrochloric acid, an ascorbic acid radical, and CTA-AuCl3. The ascorbic acid radical and CTA-AuCl3 react spontaneously to create metallic Au0 nanoparticles and other byproducts. An alternative or simultaneous reaction is the substitution of Cl− with Br− about the Au(III) center. Both complexation with the ammonium cation and/or speciation of the Au(III) precursor influence the kinetics of the nanoparticle formation reaction and therefore influence the size, shape, and (size and shape) distributions of the resulting particles. Nanoparticle synthesis: Mesoporous materials CTAB is used as the template for the first report of ordered mesoporous materials. Microporous and mesoporous inorganic solids (with pore diameters of ≤20 Å and ~20–500 Å respectively) have found great utility as catalysts and sorption media because of their large internal surface area. Typical microporous materials are crystalline framework solids, such as zeolites, but the largest pore dimensions are still below 2 nm which greatly limit application. Examples of mesoporous solids include silicas and modified layered materials, but these are invariably amorphous or paracrystalline, with pores that are irregularly spaced and broadly distributed in size. There is a need to prepare highly ordered mesoporous material with good mesoscale crystallinity. The synthesis of mesoporous solids from the calcination of aluminosilicate gels in the presence of surfactants was reported. The material possesses regular arrays of uniform channels, the dimensions of which can be tailored (in the range of 16 Å to >100 Å) through the choice of surfactant, auxiliary chemicals, and reaction conditions. It was proposed that the formation of these materials takes place by means of a liquid-crystal 'templating' mechanism, in which the silicate material forms inorganic walls between ordered surfactant micelles. CTAB formed micelles in the solution and these micelles further formed a two dimensional hexagonal mesostructure. The silicon precursor began to hydrolyze between the micelles and finally filled the gap with silicon dioxide. The template could be further removed by calcination and left a pore structure behind. These pores mimicked exactly the structure of mesoscale soft template and led to highly ordered mesoporous silica materials. Toxicity: CTAB has been used for applications from nanoparticle synthesis to cosmetics. Due to its use in human products, along with other applications, it is essential to be made aware of the hazards this agent contains. The Santa Cruz Biotechnology, Inc. offers a comprehensive MSDS for CTAB and should be referred to for additional questions or concerns. Animal testing has shown ingestion of less than 150 g of the agent can lead to adverse health effects or possibly death by CTAB causing chemical burns throughout the esophagus and gastrointestinal tract that can be followed by nausea and vomiting. If the substance continues through the gastrointestinal tract, it will be poorly absorbed in the intestines followed by excretion in feces. Toxicity has also been tested on aquatic life including Brachydanio rerio (zebra fish) and Daphnia magna (Water flea). Zebra fish showed CTAB toxicity when exposed to 0.3 mg/L for 96 hours, and water fleas showed CTAB toxicity when exposed to 0.03 mg/L for 48 hours.CTAB along with other quaternary ammonium salts have frequently been used in cosmetics at concentrations up to 10%. Cosmetics at that concentration must only be used as rinse-off types such as shampoos. Other leave-on cosmetics are considered only safe at or below 0.25% concentrations. Injections into the body cavity of pregnant mice showed embryotoxic and teratogenic effects. Only teratogenic effects were seen with 10 mg/kg doses, while both effects were seen at 35 mg/kg doses. Oral doses of 50 mg/kg/day showed embryotoxic effects as well. Similar tests were completed by giving rats 10, 20, and 45 mg/kg/day of CTAB in their drinking water for one year. At the 10 and 20 mg/kg/day doses, the rats did not have any toxic symptoms. At the highest dose, the rats began experiencing weight loss. The weight loss in the male rats was attributed to less efficient food conversion. The tests showed no microscopic alterations to the gastrointestinal tract of the rats.Other toxicity tests have been conducted using incubated human skin HaCaT keratinocyte cells. These human cells were incubated with gold nanorods that were synthesized using seed-mediated, surfactant-assisted growth of gold nanoparticles. Gold nanoparticles are shown to be nontoxic, however once the nanoparticles are put through the growth solutions, the newly formed nanorods are highly toxic. This large increase in toxicity is attributed to the CTAB that is used in the growth solutions to cause anisotropic growth. Experiments also showed the toxicity of bulk CTAB and the synthesized gold nanorods to be equivalent. Toxicity tests showed CTAB remaining toxic with concentrations as low as 10 μM. The human cells show CTAB being nontoxic at concentrations less than 1 μM. Without the use of CTAB in this synthesis, the gold nanorods are not stable; they break into nanoparticles or undergo aggregation.The mechanism for cytotoxicity has not been extensively studied, but there has been possible mechanisms proposed. One proposal showed two methods that led to the cytotoxicity in U87 and A172 glioblastoma cells. The first method showed CTAB exchanging with phospholipids causing rearrangement of the membrane allowing β-galactoside to enter into the cell by way of cavities. At low concentrations, there are not enough cavities to cause death to the cells, but with increasing the CTAB concentration, more phospholipids are displaced causing more cavities in the membrane leading to cell death. The second proposed method is based on the dissociation of CTAB into CTA+ and Br− within the mitochondrial membrane. The positively charged CTA+ binds to the ATP synthase not allowing H+ to bind stopping the synthesis of ATP and resulting in cell death.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Lithium ion manganese oxide battery** Lithium ion manganese oxide battery: A lithium ion manganese oxide battery (LMO) is a lithium-ion cell that uses manganese dioxide, MnO2, as the cathode material. They function through the same intercalation/de-intercalation mechanism as other commercialized secondary battery technologies, such as LiCoO2. Cathodes based on manganese-oxide components are earth-abundant, inexpensive, non-toxic, and provide better thermal stability. Compounds: Spinel LiMn2O4 One of the more studied manganese oxide-based cathodes is LiMn2O4, a cation ordered member of the spinel structural family (space group Fd3m). In addition to containing inexpensive materials, the three-dimensional structure of LiMn2O4 lends itself to high rate capability by providing a well connected framework for the insertion and de-insertion of Li+ ions during discharge and charge of the battery. In particular, the Li+ ions occupy the tetrahedral sites within the Mn2O4 polyhedral frameworks adjacent to empty octahedral sites. As a consequence of this structural arrangement, batteries based on LiMn2O4 cathodes have demonstrated a higher rate-capability compared to materials with two-dimensional frameworks for Li+ diffusion.A significant disadvantage of cathodes based on LiMn2O4 is the surface degradation observed when the average oxidation state of the manganese drops below Mn+3.5. At this concentration, the formally Mn(III) at the surface can disproportionate to form Mn(IV) and Mn(II) by the Hunter mechanism. The Mn(II) formed is soluble in most electrolytes and its dissolution degrades the cathode. With this in mind many manganese cathodes are substituted or doped to keep the average manganese oxidation state above +3.5 during battery use or they will suffer from lower overall capacities as a function of cycle life and temperature. Compounds: Layered Li2MnO3 Li2MnO3 is a lithium rich layered rocksalt structure that is made of alternating layers of lithium ions and lithium and manganese ions in a 1:2 ratio, similar to the layered structure of LiCoO2. In the nomenclature of layered compounds it can be written Li(Li0.33Mn0.67)O2. Although Li2MnO3 is electrochemically inactive, it can be charged to a high potential (4.5 V v.s Li0) in order to undergo lithiation/de-lithiation or delithiated using an acid leaching process followed by mild heat treatment. However, extracting lithium from Li2MnO3 at such a high potential can also be charge compensated by loss of oxygen from the electrode surface which leads to poor cycling stability. New allotropes of Li2MnO3 have been discovered which have better structural stability against oxygen release (longer cycle-life). Compounds: Layered LiMnO2 The layered manganese oxide LiMnO2 is constructed from corrugated layers of manganese/oxide octahedra and is electrochemically unstable. The distortions and deviation from truly planar metal oxide layers are a manifestation of the electronic configuration of the Mn(III) Jahn-Teller ion. A layered variant, isostructural with LiCoO2, was prepared in 1996 by ion exchange from the layered compound NaMnO2, however long term cycling and the defect nature of the charged compound led to structural degradation and cation equilibration to other phases. Compounds: Layered Li2MnO2 The layered manganese oxide Li2MnO2 is structurally related to Li2MnO3 and LiCoO2 with similar transition metal oxide layers separated by a layer containing two lithium cations occupying the available two tetrahedral sites in the lattice rather the one octahedral site. The material is typically made by low voltage lithiation of the parent compound, direct lithiation using liquid ammonia, or via use of an organic lithiating reagent. Stability on cycling has been demonstrated in symmetric cells although due to Mn(II) formation and dissolution cycling degradation is expected. Stabilization of the structure using dopants and substitutions to decrease the amount of reduced manganese cations has been a successful route to extending the cycle life of these lithium rich reduced phases. These layered manganese oxide layers are so rich in lithium. Compounds: x Li2MnO3 • y Li1+aMn2-aO4 • z LiMnO2 composites One of the main research efforts in the field of lithium-manganese oxide electrodes for lithium-ion batteries involves developing composite electrodes using structurally integrated layered Li2MnO3, layered LiMnO2, and spinel LiMn2O4, with a chemical formula of x Li2MnO3 • y Li1+aMn2-aO4 • z LiMnO2, where x+y+z=1. The combination of these structures provides increased structural stability during electrochemical cycling while achieving higher capacity and rate-capability. A rechargeable capacity in excess of 250 mAh/g was reported in 2005 using this material, which has nearly twice the capacity of current commercialized rechargeable batteries of the same dimensions.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**L(R)** L(R): In set theory, L(R) (pronounced L of R) is the smallest transitive inner model of ZF containing all the ordinals and all the reals. Construction: It can be constructed in a manner analogous to the construction of L (that is, Gödel's constructible universe), by adding in all the reals at the start, and then iterating the definable powerset operation through all the ordinals. Assumptions: In general, the study of L(R) assumes a wide array of large cardinal axioms, since without these axioms one cannot show even that L(R) is distinct from L. But given that sufficient large cardinals exist, L(R) does not satisfy the axiom of choice, but rather the axiom of determinacy. However, L(R) will still satisfy the axiom of dependent choice, given only that the von Neumann universe, V, also satisfies that axiom. Results: Given the assumptions above, some additional results of the theory are: Every projective set of reals – and therefore every analytic set and every Borel set of reals – is an element of L(R). Every set of reals in L(R) is Lebesgue measurable (in fact, universally measurable) and has the property of Baire and the perfect set property. L(R) does not satisfy the axiom of uniformization or the axiom of real determinacy. R#, the sharp of the set of all reals, has the smallest Wadge degree of any set of reals not contained in L(R). While not every relation on the reals in L(R) has a uniformization in L(R), every such relation does have a uniformization in L(R#). Given any (set-size) generic extension V[G] of V, L(R) is an elementary submodel of L(R) as calculated in V[G]. Thus the theory of L(R) cannot be changed by forcing. L(R) satisfies AD+.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Viruses of the Mind** Viruses of the Mind: "Viruses of the Mind" is an essay by British evolutionary biologist Richard Dawkins, first published in the book Dennett and His Critics: Demystifying Mind (1993). Dawkins originally wrote the essay in 1991 and delivered it as a Voltaire Lecture on 6 November 1992 at the Conway Hall Humanist Centre. The essay discusses how religion can be viewed as a meme, an idea previously expressed by Dawkins in The Selfish Gene (1976). Dawkins analyzes the propagation of religious ideas and behaviors as a memetic virus, analogous to how biological and computer viruses spread. The essay was later published in A Devil's Chaplain (2003) and its ideas are further explored in the television programme, The Root of All Evil? (2006). Content: Dawkins defines the "symptoms" of being infected by the "virus of religion", providing examples for most of them, and tries to define a connection between the elements of religion and its survival value (invoking Zahavi's handicap principle of sexual selection, applied to believers of a religion). Dawkins also describes religious beliefs as "mind-parasites", and as "gangs [that] will come to constitute a package, which may be sufficiently stable to deserve a collective name such as Roman Catholicism ... or ... component parts to a single virus". Content: Dawkins suggests that religious belief in the "faith-sufferer" typically shows the following elements: It is impelled by some deep, inner conviction that something is true, or right, or virtuous: a conviction that doesn't seem to owe anything to evidence or reason, but which, nevertheless, the believer feels as totally compelling and convincing. The believer typically makes a positive virtue of faith's being strong and unshakable, despite it not being based upon evidence. There is a conviction that "mystery", per se, is a good thing; the belief that it is not a virtue to solve mysteries but to enjoy them and revel in their insolubility. There may be intolerant behaviour towards perceived rival faiths, in extreme cases even the killing of opponents or advocating of their deaths. Believers may be similarly violent in disposition towards apostates or heretics, even if those espouse only a slightly different version of the faith. The particular convictions that the believer holds, while having nothing to do with evidence, are likely to resemble those of the believer's parents. If the believer is one of the rare exceptions who follows a different religion from his parents, the explanation may be cultural transmission from a charismatic individual. Content: The internal sensations of the 'faith-sufferer' may be reminiscent of those more ordinarily associated with sexual love.Dawkins stresses his claim that religious beliefs do not spread as a result of evidence in their support, but typically by cultural transmission, in most cases from parents or from charismatic individuals. He refers to this as involving "epidemiology, not evidence". Further Dawkins distinguishes this process from the spread of scientific ideas, which, he suggests, is constrained by the requirement to conform with certain virtues of standard methodology: "testability, evidential support, precision, quantifiability, consistency, intersubjectivity, repeatability, universality, progressiveness, independence of cultural milieu, and so on". He points out that faith "spreads despite a total lack of every single one of these virtues". Critical reactions: Alister McGrath, a Christian theologian, has commented critically on Dawkins' analysis, suggesting that "memes have no place in serious scientific reflection", that there is strong evidence that such ideas are not spread by random processes, but by deliberate intentional actions, that "evolution" of ideas is more Lamarckian than Darwinian, and suggests there is no evidence that epidemiological models usefully explain the spread of religious ideas. McGrath also cites a meta-review of 100 studies and argues that "If religion is reported as having a positive effect on human well-being by 79% of recent studies in the field, how can it conceivably be regarded as analogous to a virus?"
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Carbyl sulfate** Carbyl sulfate: Carbyl sulfate is an organosulfur compound. The white solid is the product of the reaction of sulfur trioxide and ethylene. It is used in preparation of some dyes and other organosulfur compounds. Carbyl sulfate is a colorless, crystalline, hygroscopic substance although commercial product can appear as a liquid. Because of its unpleasant properties carbyl sulfate is difficult to handle and is usually not isolated but further processed to give secondary products. Production: Regnault and Heinrich Gustav Magnus reported first in the years 1838 to 1839 on the compound as reaction product of anhydrous ethanol and anhydrous sulfuric acid. Carbyl sulfate is produced in the highly exothermic (about 800 kcal/kg) reaction of ethylene and sulfur trioxide in the vapor phase in nearly quantitative yield. Production: Disulfuric acid and chlorosulfuric acid can also be used as a sulfonating agent, replacing sulfur trioxide. Instead of ethylene, ethylene-forming agents can be used, e.g. ethanol or diethyl ether.The product of industrial processes is a water-clear liquid which has - in accordance with D.S. Breslow (107.5 to 109 °C) - a melting range from 102 to 108 °C. Previously stated melting point of about 80 °C results from adhering sulfur trioxide. Reactions and use: As a cyclic sulfate ester, it is an alkylating agent. Hydrolysis affords ethionic acid, which retains one sulfate ester group. Ethionic acid undergoes further hydrolysis to isethionic acid: Carbyl sulfate is used as precursor for vinylsulfonic acid and sodium vinyl sulfonate, which are important activated alkenes and are used e. g. as anionic comonomers. A number of functional compounds with a variety of applications are available by nucleophilic addition at the activated double bond of the vinyl sulfonic acid and its derivatives. Safety: The material is highly reactive. It can decompose explosively when heated above 170 °C.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Wharton's jelly** Wharton's jelly: Wharton's jelly (substantia gelatinea funiculi umbilicalis) is a gelatinous substance within the umbilical cord, largely made up of mucopolysaccharides (hyaluronic acid and chondroitin sulfate). It acts as a mucous connective tissue containing some fibroblasts and macrophages, and is derived from extra-embryonic mesoderm of the connecting stalk. Umbilical cord occlusion: As a mucous connective tissue, it is rich in proteoglycans, and protects and insulates umbilical blood vessels. Wharton's jelly, when exposed to temperature changes, collapses structures within the umbilical cord and thus provides a physiological clamping of the cord, typically three minutes after birth. Stem cells: Cells in Wharton's jelly express several stem cell genes, including telomerase. They can be extracted, cultured, and induced to differentiate into mature cell types such as neurons. Wharton's jelly is therefore a potential source of adult stem cells, often collected from cord blood. Wharton's jelly-derived mesenchymal stem cells may have immunomodulatory effect on lymphocytes. Wharton's jelly tissue transplantation has shown to be able to reduce traumatic brain injury in rats. Etymology: It is named for the English physician and anatomist Thomas Wharton (1614–1673) who first described it in his publication Adenographia, or "The Description of the Glands of the Entire Body", first published in 1656.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**GPR156** GPR156: GPR156 (G protein-coupled receptor 156), is a human gene which encodes a G protein-coupled receptor belonging to metabotropic glutamate receptor subfamily. By sequence homology, this gene was proposed as being a possible GABAB receptor subunit, however when expressed in cells alone or with other GABAB subunits, no response to GABAB ligands could be detected. Therefore, the function of this protein remains to be elucidated. In vitro studies on GPR156 constitutive activity revealed a high level of basal activation and coupling with members of the Gi/Go heterotrimeric G protein family.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Bastnäsite** Bastnäsite: The mineral bastnäsite (or bastnaesite) is one of a family of three carbonate-fluoride minerals, which includes bastnäsite-(Ce) with a formula of (Ce, La)CO3F, bastnäsite-(La) with a formula of (La, Ce)CO3F, and bastnäsite-(Y) with a formula of (Y, Ce)CO3F. Some of the bastnäsites contain OH− instead of F− and receive the name of hydroxylbastnasite. Most bastnäsite is bastnäsite-(Ce), and cerium is by far the most common of the rare earths in this class of minerals. Bastnäsite and the phosphate mineral monazite are the two largest sources of cerium and other rare-earth elements. Bastnäsite: Bastnäsite was first described by the Swedish chemist Wilhelm Hisinger in 1838. It is named for the Bastnäs mine near Riddarhyttan, Västmanland, Sweden. Bastnäsite also occurs as very high-quality specimens at the Zagi Mountains, Pakistan. Bastnäsite occurs in alkali granite and syenite and in associated pegmatites. It also occurs in carbonatites and in associated fenites and other metasomatites. Composition: Bastnäsite has cerium, lanthanum and yttrium in its generalized formula but officially the mineral is divided into three minerals based on the predominant rare-earth element. There is bastnäsite-(Ce) with a more accurate formula of (Ce, La)CO3F. There is also bastnäsite-(La) with a formula of (La, Ce)CO3F. And finally there is bastnäsite-(Y) with a formula of (Y, Ce)CO3F. There is little difference in the three in terms of physical properties and most bastnäsite is bastnäsite-(Ce). Cerium in most natural bastnäsites usually dominates the others. Bastnäsite and the phosphate mineral monazite are the two largest sources of cerium, an important industrial metal. Composition: Bastnäsite is closely related to the mineral series parisite. The two are both rare-earth fluorocarbonates, but parisite's formula of Ca(Ce, La, Nd)2(CO3)3F2 contains calcium (and a small amount of neodymium) and a different ratio of constituent ions. Parisite could be viewed as a formula unit of calcite (CaCO3) added to two formula units of bastnäsite. In fact, the two have been shown to alter back and forth with the addition or loss of CaCO3 in natural environments.Bastnäsite forms a series with the minerals hydroxylbastnäsite-(Ce) [(Ce,La)CO3(OH,F)] and hydroxylbastnäsite-(Nd). The three are members of a substitution series that involves the possible substitution of fluoride (F−) ions with hydroxyl (OH−) ions. Name: Bastnäsite gets its name from its type locality, the Bastnäs Mine, Riddarhyttan, Västmanland, Sweden. Ore from the Bastnäs Mine led to the discovery of several new minerals and chemical elements by Swedish scientists such as Jöns Jakob Berzelius, Wilhelm Hisinger and Carl Gustav Mosander. Among these are the chemical elements cerium, which was described by Hisinger in 1803, and lanthanum in 1839. Hisinger, who was also the owner of the Bastnäs mine, chose to name one of the new minerals bastnäsit when it was first described by him in 1838. Occurrence: Although a scarce mineral and never in great concentrations, it is one of the more common rare-earth carbonates. Bastnäsite has been found in karst bauxite deposits in Hungary, Greece and the Balkans region. Also found in carbonatites, a rare carbonate igneous intrusive rock, at the Fen Complex, Norway; Bayan Obo, Mongolia; Kangankunde, Malawi; Kizilcaoren, Turkey and the Mountain Pass rare earth mine in California, US. At Mountain Pass, bastnäsite is the leading ore mineral. Some bastnäsite has been found in the unusual granites of the Langesundsfjord area, Norway; Kola Peninsula, Russia; Mont Saint-Hilaire mines, Ontario, and Thor Lake deposits, Northwest Territories, Canada. Hydrothermal sources have also been reported. Occurrence: The formation of hydroxylbastnasite (NdCO3OH) can also occur via the crystallization of a rare-earth bearing amorphous precursor. With increasing temperature, the habit of NdCO3OH crystals changes progressively to more complex spherulitic or dendritic morphologies. The development of these crystal morphologies has been suggested to be controlled by the level at which supersaturation is reached in the aqueous solution during the breakdown of the amorphous precursor. At higher temperature (e.g., 220 °C) and after rapid heating (e.g. < 1 h) the amorphous precursor breaks down rapidly and the fast supersaturation promotes spherulitic growth. At a lower temperature (e.g., 165 °C) and slow heating (100 min) the supersaturation levels are approached more slowly than required for spherulitic growth, and thus more regular triangular pyramidal shapes form. Mining history: In 1949, the huge carbonatite-hosted bastnäsite deposit was discovered at Mountain Pass, San Bernardino County, California. This discovery alerted geologists to the existence of a whole new class of rare earth deposit: the rare earth containing carbonatite. Other examples were soon recognized, particularly in Africa and China. The exploitation of this deposit began in the mid-1960s after it had been purchased by Molycorp (Molybdenum Corporation of America). The lanthanide composition of the ore included 0.1% europium oxide, which was needed by the color television industry, to provide the red phosphor, to maximize picture brightness. The composition of the lanthanides was about 49% cerium, 33% lanthanum, 12% neodymium, and 5% praseodymium, with some samarium and gadolinium, or distinctly more lanthanum and less neodymium and heavies as compared to commercial monazite. The europium content was at least double that of a typical monazite. Mountain Pass bastnäsite was the world's major source of lanthanides from the 1960s to the 1980s. Thereafter, China became an increasingly important rare earth supply. Chinese deposits of bastnäsite include several in Sichuan Province, and the massive deposit at Bayan Obo, Inner Mongolia, which had been discovered early in the 20th century, but not exploited until much later. Bayan Obo is currently (2008) providing the majority of the world's lanthanides. Bayan Obo bastnäsite occurs in association with monazite (plus enough magnetite to sustain one of the largest steel mills in China), and unlike carbonatite bastnäsites, is relatively closer to monazite lanthanide compositions, with the exception of its generous 0.2% content of europium. Ore technology: At Mountain Pass, bastnäsite ore was finely ground, and subjected to flotation to separate the bulk of the bastnäsite from the accompanying barite, calcite, and dolomite. Marketable products include each of the major intermediates of the ore dressing process: flotation concentrate, acid-washed flotation concentrate, calcined acid washed bastnäsite, and finally a cerium concentrate, which was the insoluble residue left after the calcined bastnäsite had been leached with hydrochloric acid. The lanthanides that dissolved as a result of the acid treatment were subjected to solvent extraction, to capture the europium, and purify the other individual components of the ore. A further product included a lanthanide mix, depleted of much of the cerium, and essentially all of samarium and heavier lanthanides. The calcination of bastnäsite had driven off the carbon dioxide content, leaving an oxide-fluoride, in which the cerium content had become oxidized to the less basic quadrivalent state. However, the high temperature of the calcination gave less-reactive oxide, and the use of hydrochloric acid, which can cause reduction of quadrivalent cerium, led to an incomplete separation of cerium and the trivalent lanthanides. By contrast, in China, processing of bastnäsite, after concentration, starts with heating with sulfuric acid. Ore technology: Extraction of rare-earth metals Bastnäsite ore is typically used to produce rare-earth metals. The following steps and process flow diagram detail the rare-earth-metal extraction process from the ore. After extraction, bastnasite ore is typically used in this process, with an average of 7% REO (rare-earth oxides). The ore goes through comminution using rod mills, ball mills, or autogenous mills. Steam is consistently used to condition the ground ore, along with soda ash fluosilicate, and usually Tail Oil C-30. This is done to coat the various types of rare earth metals with either flocculent, collectors, or modifiers for easier separation in the next step. Flotation using the previous chemicals to separate the gangue from the rare-earth metals. Concentrate the rare-earth metals and filter out large particles. Remove excess water by heating to ~100 °C. Add HCl to solution to reduce pH to < 5. This enables certain REM (rare-earth metals) to become soluble (Ce is an example). Oxidizing roast further concentrates the solution to approximately 85% REO. This is done at ~100 °C and higher if necessary. Enables solution to concentrate further and filters out large particles again. Reduction agents (based on area) are used to remove Ce as Ce carbonate or CeO2, typically. Solvents are added (solvent type and concentration based on area, availability, and cost) to help separate Eu, Sm, and Gd from La, Nd, and Pr. Reduction agents (based on area) are used to oxidize Eu, Sm, and Gd. Eu is precipitated and calcified. Gd is precipitated as an oxide. Sm is precipitated as an oxide. Solvent is recycled into step 11. Additional solvent is added based on concentration and purity. La separated from Nd, Pr, and SX. Nd and Pr separated. SX goes on for recovery and recycle. One way to collect La is adding HNO3, creating La(NO3)3. HNO3 typically added at a very high molarity (1–5 M), depending on La concentration and amount. Another method is to add HCl to La, creating LaCl3. HCl is added at 1 M to 5 M depending on La concentration. Solvent from La, Nd, and Pr separation is recycled to step 11. Nd is precipitated as an oxide product. Pr is precipitated as an oxide product.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**3DXRD** 3DXRD: Three-dimensional X-ray diffraction (3DXRD) is a microscopy technique using hard X-rays (with energy in the 30-100 keV range) to investigate the internal structure of polycrystalline materials in three dimensions. For a given sample, 3DXRD returns the shape, juxtaposition, and orientation of the crystallites ("grains") it is made of. 3DXRD allows investigating micrometer- to millimetre-sized samples with resolution ranging from hundreds of nanometers to micrometers. Other techniques employing X-rays to investigate the internal structure of polycrystalline materials include X-ray diffraction contrast tomography (DCT) and high energy X-ray diffraction (HEDM).Compared with destructive techniques, e.g. three-dimensional electron backscatter diffraction (3D EBSD), with which the sample is serially sectioned and imaged, 3DXRD and similar X-ray nondestructive techniques have the following advantages: They require less sample preparation, thus limiting the introduction of new structures in the sample. 3DXRD: They can be used to investigate larger samples and to employ more complicated sample environments. They enable to study how 3D grain structures evolve with time. Since measurements do not alter the sample, different types of analysis can be made in sequence. Experimental setup: 3DXRD measurements are performed using various experimental geometries. The classical 3DXRD setup is similar to the conventional tomography setting used at synchrotrons: the sample, mounted on a rotation stage, is illuminated using quasi-parallel monochromatic X-ray beam. Each time a certain grain within the sample satisfies the Bragg condition, a diffracted beam is generated. This signal is transmitted through the sample and collected by two-dimensional detectors. Since different grains satisfy the Bragg condition at different angles, the sample is rotated to probe the complete sample structure. Crucial for 3DXRD is the idea to mimic a three-dimensional detector by positioning a number of two-dimensional detectors at different distances from the centre of rotation of the sample, and exposing these either simultaneously (many detectors are semi-transparent to hard X-rays) or at different times. Experimental setup: At present (April 2017), a 3DXRD microscope is installed at the Materials Science beamline of the ESRF. Software: To determine the crystallographic orientation of the grains in the considered sample, the following software packages are in use: Fable and GrainSpotter. Reconstructing the 3D shape of the grains is nontrivial and three approaches are available to do so, respectively based on simple back-projection, forward projection, algebraic reconstruction technique and Monte Carlo method-based reconstruction. Applications: With 3DXRD, it is possible to study in situ the time evolution of materials under different conditions. Among others, the technique has been used to map the elastic strains and stresses in a pre-strained nickel-titanium wire. Related techniques: The scientists involved in developing 3DXRD contributed to the development of three other three-dimensional non-destructive techniques for the material sciences, respectively using electrons and neutrons as a probe: three-dimensional orientation mapping in the transmission electron microscope (3D-OMiTEM), time-of-flight 3D neutron diffraction for multigrain crystallography (ToF 3DND) and laue 3D neutron diffraction (Laue3DND).Using a system of lenses, the synchrotron technique dark-field X-ray microscopy (DFXRM) extends the capabilities of 3DXRD, allowing to focus on a deeply embedded single grain and to reconstruct its 3D structure and its crystalline properties. DFXRM is under development at the European Synchrotron Research Facility (ESRF), beamline ID06.In a laboratory setting, 3D grain maps using X-rays as a probe can be obtained using laboratory diffraction contrast tomography (LabDCT), a technique derived from 3DXRD.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**SYBL1** SYBL1: Vesicle-associated membrane protein 7 (VAMP-7), is a protein that in humans is encoded by the VAMP7 gene also known as the or SYBL1 gene. Function: VAMP-7 is a transmembrane protein that is a member of the soluble N-ethylmaleimide-sensitive factor attachment protein receptor (SNARE) family. VAMP-7 localizes to late endosomes and lysosomes and is involved in the fusion of transport vesicles to their target membranes. Interactions: VAMP-7 has been shown to interact with SNAP23 and AP3D1.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Blood–gas partition coefficient** Blood–gas partition coefficient: Blood–gas partition coefficient, also known as Ostwald coefficient for blood–gas, is a term used in pharmacology to describe the solubility of inhaled general anesthetics in blood. According to Henry's law, the ratio of the concentration in blood to the concentration in gas that is in contact with that blood, when the partial pressure in both compartments is equal, is nearly constant at sufficiently low concentrations. The partition coefficient is defined as this ratio and, therefore, has no units. The concentration of the anesthetic in blood includes the portion that is undissolved in plasma and the portion that is dissolved (bound to plasma proteins). The more soluble the inhaled anesthetic is in blood compared to in air, the more it binds to plasma proteins in the blood and the higher the blood–gas partition coefficient. Blood–gas partition coefficient: It is inversely related to induction rate. Induction rate is defined as the speed at which an agent produces anesthesia. The higher the blood:gas partition coefficient, the lower will be the induction rate. Blood–gas partition coefficient: Newer anesthetics (such as desflurane) typically have smaller blood–gas partition coefficients than older ones (such as ether); this leads to faster onset of anesthesia and faster emergence from anesthesia once application of the anesthetic is stopped, which may be preferable in certain clinical scenarios. If an anesthetic has a high coefficient, then a large amount of it will have to be taken up in the body's blood before being passed on to the fatty (lipid) tissues of the brain where it can exert its effect. Blood–gas partition coefficient: The potency of an anesthetic is associated with its lipid solubility, which is measured by its oil/gas partition coefficient.Minimum alveolar concentration (MAC) is defined as the alveolar concentration of anesthetic gas that prevents a movement response in half of subjects undergoing a painful (surgical) stimulus; simplified, it is the exhaled gas concentration required to produce anaesthetic effects – an inverse indicator of anesthetic gas potency.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Old Nassau reaction** Old Nassau reaction: The Old Nassau reaction or Halloween reaction is a chemical clock reaction in which a clear solution turns orange and then black. This reaction was discovered by two undergraduate students at Princeton University researching the inhibition of the iodine clock reaction (or Landolt reaction) by Hg2+, resulting in the formation of orange HgI2. Orange and black are the school colors of Princeton University, and "Old Nassau" is a nickname for Princeton, named for its historic administration building, Nassau Hall. Chemical equation: The reactions involved are as follows: Na2S2O5 + H2O → 2 NaHSO3 IO3− + 3 HSO3− → I− + 3 SO42− + 3 H+ This reaction reduces iodate ions to iodide ions. Hg2+ + 2 I− → HgI2 Orange mercury iodide solid is precipitated until the mercury is used up. IO3− + 5 I− + 6 H+ → 3 I2 + 3 H2O The excess I− and IO3− undergo the iodide-iodate reaction I2 + starch → a blue/black complex A blue/black starch-iodine complex is formed.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Rattlesnake round-up** Rattlesnake round-up: Rattlesnake round-ups (or roundups), also known as rattlesnake rodeos, are annual events common in the rural Midwest and Southern United States, where the primary attractions are captured wild rattlesnakes which are sold, displayed, killed for food or animal products (such as snakeskin) or released back into the wild. Rattlesnake round-ups originated in the first half of the 20th century for adventure and excitement, as well as to achieve local extirpation of perceived pest species. Typically a round-up will also include trade stalls, food, rides, and other features associated with fairs, as well as snake shows that provide information on rattlesnake biology, identification, and safety. To date, round-ups where snakes are killed take place in Alabama, Georgia, Oklahoma, and Texas, with largest events in Texas and Oklahoma. Many round-ups are no longer slaughtering snakes, but have transitioned to educational festivals celebrating rattlesnakes and other wildlife. All round-ups in Pennsylvania return snakes to the wild and two former round-ups in Georgia and Florida use captive animals for their festivals. The largest rattlesnake round-up in the United States is held in Sweetwater, Texas. Held annually in mid-March since 1958, the event currently attracts approximately 30,000 visitors per year and in 2006 each annual round-up was said to result in the capture of 1% of the state's rattlesnake population, but there are no data or studies to support this claim.Round-ups have economic and social importance to the communities that hold them. The events often attract thousands of tourists, which can bring hundreds of thousands of dollars of revenue into small towns; the Sweetwater Round-Up's economic impact was estimated to exceed US$5 million in 2006. Snake collectors often make large profits selling snakes at the events. Rattlesnake round-up: Cash prizes and trophies are often given out to participants in categories like heaviest, longest, or most snakes. These incentives result in all size classes of snakes being targeted equally. Most roundups target the western diamondback rattlesnake (Crotalus atrox), though some events target prairie rattlesnakes (C. viridis), timber rattlesnakes (C. horridus), or the eastern diamondback rattlesnake (C. adamanteus).A harvest of several hundred to several thousand kilograms of snakes is typical for many roundups. In Texas, up to 125,000 snakes could have been removed annually from the wild during the 1990s. However, effects of roundups on rattlesnake populations are unclear. Harvest size at roundups is highly variable from year to year but does not show a consistent downward trend, even after decades of annual roundup events in some areas. C. atrox is listed as Least Concern by the IUCN. However, poaching and roundups have been destructive to populations of timber rattlesnakes (C. horridus) in the northeastern United States. Some groups are concerned that local C. atrox populations may be declining rapidly, even if the global population is unaffected. Rattlesnake round-ups became a concern by animal welfare groups and conservationists due to claims of animal cruelty and excessive threat of future endangerment. In response, some round-ups impose catch size restrictions or release captured snakes back into the wild. Media: In the Simpsons episode "Whacking Day" (Season 04, Episode 20), Lisa and Bart try to save snakes from being killed.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Elementary amenable group** Elementary amenable group: In mathematics, a group is called elementary amenable if it can be built up from finite groups and abelian groups by a sequence of simple operations that result in amenable groups when applied to amenable groups. Since finite groups and abelian groups are amenable, every elementary amenable group is amenable - however, the converse is not true. Elementary amenable group: Formally, the class of elementary amenable groups is the smallest subclass of the class of all groups that satisfies the following conditions: it contains all finite and all abelian groups if G is in the subclass and H is isomorphic to G, then H is in the subclass it is closed under the operations of taking subgroups, forming quotients, and forming extensions it is closed under directed unions.The Tits alternative implies that any amenable linear group is locally virtually solvable; hence, for linear groups, amenability and elementary amenability coincide.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Tele-TASK** Tele-TASK: Tele-TASK is a university research project in the e-learning area. It can be applied to lecture recording, post-processing and distribution. Research topics include e-learning, tele-teaching, semantic web, video analysis, speech recognition, collaborative learning, social networking, web technologies, recommendation systems, statistics and video codecs and conversion. The project was founded by Christoph Meinel and his research group at the University of Trier. When he accepted the chair for Internet Technologies and Systems at Hasso Plattner Institute at the University of Potsdam/Germany, the tele-TASK project also moved with him. Reference software was developed as proof of concept, such as an online e-lecture archive a lecture recording system and a post-production tool.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**DNA fragmentation** DNA fragmentation: DNA fragmentation is the separation or breaking of DNA strands into pieces. It can be done intentionally by laboratory personnel or by cells, or can occur spontaneously. Spontaneous or accidental DNA fragmentation is fragmentation that gradually accumulates in a cell. It can be measured by e.g. the Comet assay or by the TUNEL assay. DNA fragmentation: Its main units of measurement is the DNA Fragmentation Index (DFI). A DFI of 20% or more significantly reduces the success rates after ICSI.DNA fragmentation was first documented by Williamson in 1970 when he observed discrete oligomeric fragments occurring during cell death in primary neonatal liver cultures. He described the cytoplasmic DNA isolated from mouse liver cells after culture as characterized by DNA fragments with a molecular weight consisting of multiples of 135 kDa. This finding was consistent with the hypothesis that these DNA fragments were a specific degradation product of nuclear DNA. Intentional: DNA fragmentation is often necessary prior to library construction or subcloning for DNA sequences. A variety of methods involving the mechanical breakage of DNA have been employed where DNA is fragmented by laboratory personnel. Such methods include sonication, needle shear, nebulisation, point-sink shearing and passage through a pressure cell. Intentional: Restriction digest is the intentional laboratory breaking of DNA strands. It is an enzyme-based treatment used in biotechnology to cut DNA into smaller strands in order to study fragment length differences among individuals or for gene cloning. This method fragments DNA either by the simultaneous cleavage of both strands, or by generation of nicks on each strand of dsDNA to produce dsDNA breaks. Intentional: Acoustic shearing of the transmission of high-frequency acoustic energy waves delivered to a DNA library. The transducer is bowl shaped so that the waves converge at the target of interest. Intentional: Nebulization forces DNA through a small hole in a nebulizer unit, which results in the formation of a fine mist that is collected. Fragment size is determined by the pressure of the gas used to push the DNA through the nebulizer, the speed at which the DNA solution passes through the hole, the viscosity of the solution, and the temperature. Intentional: Sonication, a type of hydrodynamic shearing, subjects DNA to acoustic cavitation and hydrodynamic shearing by exposure to brief periods of sonication, usually resulting in 700bp fragments. For DNA fragmentation, sonication is commonly applied at burst cycles using a probe-type sonicator. Point-sink shearing, a type of hydrodynamic shearing, uses a syringe pump to create hydrodynamic shear forces by pushing a DNA library through a small abrupt contraction. About 90% of fragment lengths fall within a two-fold range. Needle shearing creates shearing forces by passing DNA libraries through small gauge needle. The DNA pass through a gauge needle several times to physically tear the DNA into fine pieces. Intentional: French pressure cells pass DNA through a narrow valve under high pressure to create high shearing forces. With a French press, the shear force can be carefully modulated by adjusting the piston pressure. The Press provides a single pass through the point of maximum shear force, limiting damage to delicate biological structures due to repeated shear, as occurs in other disruption methods. Intentional: In transposome mediated fragmentation (tagmentation) transposomes are prepared with DNA that is afterwards cut so that the transposition events result in fragmented DNA with adapters (instead of an insertion). The relative concentration of transposomes and DNA must be appropriate. Spontaneous: Apoptotic DNA fragmentation is a natural fragmentation that cells perform in apoptosis (programmed cell death). DNA fragmentation is a biochemical hallmark of apoptosis. In dying cells, DNA is cleaved by an endonuclease that fragments the chromatin into nucleosomal units, which are multiples of about 180-bp oligomers and appear as a DNA ladder when run on an agarose gel. The enzyme responsible for apoptotic DNA fragmentation is the Caspase-activated DNase. CAD is normally inhibited by another protein, the Inhibitor of Caspase Activated DNase (ICAD). During apoptosis, the apoptotic effector caspase, caspase 3, cleaves ICAD and thus causes CAD to become activated. Spontaneous: CAD cleaves the DNA at the internucleosomal linker sites between the nucleosomes, protein-containing structures that occur in chromatin at ~180-bp intervals. This is because the DNA is normally tightly wrapped around histones, the core proteins of the nucleosomes. The linker sites are the only parts of the DNA strand that are exposed and thus accessible to CAD. Men with sperm motility defects often have high levels of sperm DNA fragmentation. The degree of DNA fragmentation in sperm cells can predict outcomes for in vitro fertilization (IVF) and its expansion intracytoplasmic sperm injection (ICSI). The sperm chromatin dispersion test (SCD) and TUNEL assay are both effective in detecting sperm DNA damage. Using bright-field microscopy, the SCD test appears to be more sensitive than the TUNEL assay. Uses: DNA Fragmentation plays an important part in forensics, especially that of DNA profiling. Uses: Restriction Fragment Length Polymorphism (RFLP) is a technique for analyzing the variable lengths of DNA fragments that result from digesting a DNA sample with a restriction endonuclease. The restriction endonuclease cuts DNA at a specific sequence pattern known as a restriction endonuclease recognition site. The presence or absence of certain recognition sites in a DNA sample generates variable lengths of DNA fragments, which are separated using gel electrophoresis. They are then hybridized with DNA probes that bind to a complementary DNA sequence in the sample. Uses: In polymerase chain reaction (PCR) analysis, millions of exact copies of DNA from a biological sample are made. It used to amplify a specific region of a DNA strand (the DNA target). Most PCR methods typically amplify DNA fragments of between 0.1 and 10 kilo base pairs (kb), although some techniques allow amplification of fragments up to 40 kb in size. PCR also uses heat to separate the DNA strands. Uses: DNA fragmented during apoptosis, of a size from 1 to 20 nucleosomes, can be selectively isolated from the cells fixed in the denaturing fixative ethanol
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Out-of-home entertainment** Out-of-home entertainment: Out-of-home entertainment (OOHE or OHE) is a term coined by the amusement industry to collectively refer to experiences at regional attractions like theme parks and waterparks with their thrill rides and slides, and smaller community-based entertainment venues such as family entertainment and cultural venues. Out-of-home entertainment: In the US alone, there are nearly 30,000 attractions—theme and amusement parks, attractions, water parks, family entertainment centers, zoos, aquariums, science centers, museums, and resorts, producing a total nationwide economic impact of $219 billion in 2011, according to leading international industry association, International Association of Amusement Parks and Attractions (IAAPA). The industry directly employs more than 1.3 million and indirectly generates 1 million jobs in the US, creating a total job impact of 2.3 million.In recent years, the use of this term has gained acceptance with and been popularized by amusement industry players, industry associations, trade magazines and even securities analysts. This stems from the desire to distinguish between the social, competitive atmosphere and dedicated hardware found in location-based entertainment venues from at-home consumer-game entertainment, mobile entertainment or even augmented reality (AR) and virtual reality (VR). The reality is that the lines are increasingly blurred with today's sophisticated consumers and emerging technologies. Out-of-home entertainment: This term is not to be confused with out-of-home media advertising as used by the advertising industry, although the convergence of digital out-of-home advertising and the digital out-of-home entertainment is producing innovations in retail and hospitality, steeped in fundamentals of social gaming experiences defined by the video amusement industry during the 70’s. Overview: Digital out-of-home entertainment (also DOE) is a sector that is understood by few but is a fast-growing technology sector with plenty of innovations transforming the sector. Its roots lie in the popularity of coin-operated arcade video games such as racing, fighting, Japanese imports, or pinball that Generation X will vividly recall with fond memories of countless hours of their youth spent in dimly-lit video-game rooms (popularly known as 'arcades'). Overview: When Generation Y came along, an audience well-versed in digital gaming favored game consoles over arcade machines. So while video amusement remains an integral part of the popular culture fabric today, its relevancy is diminished and even perceived as 'dead' partly due to the lack of coverage by consumer-game media even as the amusement industry transformed itself and research and development investments continue to pour into the sector, evolving and growing the out-of-home, pay-to-play experience.In 2011, the non-profit Digital Out-of-Home Interactive Entertainment Network Association was established to help "define these amorphous groups that comprise this vibrant industry and illustrate how they all interact" with groups spanning from "family entertainment centers (FEC), location-based entertainment sites, visitor attractions, theme parks as well as retail, shopping malls and the hospitality sector – and not forgetting museums, heritage sites, schools". Forms of out-of-home entertainment: Moviegoing is one of the most popular and affordable forms of out-of-home entertainment. Other classic and expanded forms of OOHE making up the DOE sector include: Key actors in out-of-home entertainment: Family entertainment centers The traditional FECs is a classic form of OOHE that is easily understood by the public. FECs are essentially a converged outgrowth of theme restaurants and the winning formula of combining food and entertainment as a business model has been around for more than 30 years. The first Dave & Buster's was opened in 1982 in Dallas, Texas after discovering this winning formula and is a highly-successful FEC chain today with their "Eat, Drink, Play, Watch" offerings. Chuck E. Cheese first opened a store in 1977 and became the public embodiment of the typical children's party room combined with a pizza restaurant and arcade. Other restaurants started to come round to seeing the importance of amusement games and "anchor" attractions (bowling alleys, miniature golf, laser tags, batting cages, roller skating rinks, etc.) to encourage dwell time of 1–2 hours and stimulating repeat visits. Key actors in out-of-home entertainment: Arcade video game developers Probably known more by the blockbuster arcade video game titles they produced rather than by company names, these video game developers played a defining role in the birth of the video amusement industry. In 1972, Atari essentially created the first commercially successful video game Pong, marking the beginning of the coin-operated video game industry. In 1978, the first blockbuster arcade video game, Space Invaders was produced by Taito and ushered in the golden age of arcade video games. Namco (of Pac-Man's fame), Nintendo (Donkey Kong), Konami (Frogger), Capcom (Street Fighters), Sega AM2 (Daytona) are among some of the most notable video game developers that remain active today in the video amusement scene. Key actors in out-of-home entertainment: Video game publishers are also making inroads into the OOHE market by licensing iconic IPs (intellectual property) to experienced arcade game developers and manufacturers, such as the recent collaboration between Ubisoft and LAI Games to produce Virtual Rabbids: The Big Ride, an attendant-free VR attraction based on the popular Rabbids franchise. Key actors in out-of-home entertainment: Redemption game manufacturers A redemption game is an arcade amusement game involving skill that rewards the player (in gifts, tokens, etc.) proportionately to his or her score. One of the most popular redemption games, Skee Ball, has more than 100,000 Skee-Ball branded alley games in use worldwide by some estimates and continue to endure after more than a century. In 2016, BayTek Games bought the rights to Skee-Ball from Skee-Ball Amusement Games, Inc. Innovative Concepts in Entertainment (ICE), another reputable manufacturer, produced hit midway-style redemption games such as Down The Clown and Gold Fishin. Benchmark Games Int. has changed the game for players with Monsterdrop and Pop It & Win. LAI Games (formerly part of the Leisure and Allied Industries Group which founded Timezone) produced hit games such as Stacker and Speed of Light, the latter in which was embedded in popular culture with its appearance in Nickelodeon TV show Game Shakers.Merchandizers also fall in the redemption game category. ELAUT is the best known for creating and popularising claw machines, with notable cranes like "E-Claw" and "Big One". Key actors in out-of-home entertainment: Other notable players include Coast to Coast Entertainment, Apple Industries, Coastal Amusements, Universal Space (UNIS), Adrenaline Amusements. Key actors in out-of-home entertainment: Simulation video game manufacturers Another category of video amusement games are simulators. Raw Thrills, best known for developing arcade video games based on films such as Jurassic Park Arcade and AMC's The Walking Dead Arcade, is a common name found in medium and larger-sized FECs. Other established companies in this category are Triotech, maker of Typhoon - a 3D arcade machine with 2 seats and delivers up to 2G Forces of acceleration, and CJ 4DPLEX with their Mini Rider 3D - a 2-seat simulator on an electric motion base with a choice of several 3D movies.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Eureka effect** Eureka effect: The eureka effect (also known as the Aha! moment or eureka moment) refers to the common human experience of suddenly understanding a previously incomprehensible problem or concept. Some research describes the Aha! effect (also known as insight or epiphany) as a memory advantage, but conflicting results exist as to where exactly it occurs in the brain, and it is difficult to predict under what circumstances one can predict an Aha! moment. Eureka effect: Insight is a psychological term that attempts to describe the process in problem solving when a previously unsolvable puzzle becomes suddenly clear and obvious. Often this transition from not understanding to spontaneous comprehension is accompanied by an exclamation of joy or satisfaction, an Aha! moment. Eureka effect: A person utilizing insight to solve a problem is able to give accurate, discrete, all-or-nothing type responses, whereas individuals not using the insight process are more likely to produce partial, incomplete responses.A recent theoretical account of the Aha! moment started with four defining attributes of this experience. First, the Aha! moment appears suddenly; second, the solution to a problem can be processed smoothly, or fluently; third, the Aha! moment elicits positive affect; fourth, a person experiencing the Aha! moment is convinced that a solution is true. These four attributes are not separate but can be combined because the experience of processing fluency, especially when it occurs surprisingly (for example, because it is sudden), elicits both positive affect and judged truth.Insight can be conceptualized as a two phase process. The first phase of an Aha! experience requires the problem solver to come upon an impasse, where they become stuck and even though they may seemingly have explored all the possibilities, are still unable to retrieve or generate a solution. The second phase occurs suddenly and unexpectedly. After a break in mental fixation or re-evaluating the problem, the answer is retrieved. Some research suggest that insight problems are difficult to solve because of our mental fixation on the inappropriate aspects of the problem content. In order to solve insight problems, one must "think outside the box". It is this elaborate rehearsal that may cause people to have better memory for Aha! moments. Insight is believed to occur with a break in mental fixation, allowing the solution to appear transparent and obvious. History and etymology: The effect is named from a story about ancient Greek polymath Archimedes. In the story, Archimedes was asked (c. 250 BC) by the local king to determine whether a crown was pure gold. During a subsequent trip to a public bath, Archimedes noted that water was displaced when his body sank into the bath, and particularly that the volume of water displaced equaled the volume of his body immersed in the water. Having discovered how to measure the volume of an irregular object, and conceiving of a method to solve the king's problem, Archimedes allegedly leaped out and ran home naked, shouting εὕρηκα (eureka, "I have found it!"). This story is now thought to be fictional, because it was first mentioned by the Roman writer Vitruvius nearly 200 years after the date of the alleged event, and because the method described by Vitruvius would not have worked. However, Archimedes certainly did important, original work in hydrostatics, notably in his On Floating Bodies. Research: Initial research Research on the Aha! moment dates back more than 100 years, to the Gestalt psychologists' first experiments on chimpanzee cognition. In his 1921 book, Wolfgang Köhler described the first instance of insightful thinking in animals: One of his chimpanzees, Sultan, was presented with the task of reaching a banana that had been strung up high on the ceiling so that it was impossible to reach by jumping. After several failed attempts to reach the banana, Sultan sulked in the corner for a while, then suddenly jumped up and stacked a few boxes upon each other, climbed them and thus was able to grab the banana. This observation was interpreted as insightful thinking. Köhler's work was continued by Karl Duncker and Max Wertheimer. Research: The Eureka effect was later also described by Pamela Auble, Jeffrey Franks and Salvatore Soraci in 1979. The subject would be presented with an initially confusing sentence such as "The haystack was important because the cloth ripped". After a certain period of time of non-comprehension by the reader, the cue word (parachute) would be presented, the reader could comprehend the sentence, and this resulted in better recall on memory tests. Subjects spend a considerable amount of time attempting to solve the problem, and initially it was hypothesized that elaboration towards comprehension may play a role in increased recall. There was no evidence that elaboration had any effect for recall. It was found that both "easy" and "hard" sentences that resulted in an Aha! effect had significantly better recall rates than sentences that subjects were able to comprehend immediately. In fact equal recall rates were obtained for both "easy" and "hard" sentences which were initially noncomprehensible. It seems to be this noncomprehension to comprehension which results in better recall. The essence of the aha feeling underlining insight problem solving was systemically investigated by Danek et al. and Shen and his colleagues. Recently an attempt has been made in trying to understand the neurobiological basis of Eureka moment. Research: How people solve insight problems Currently there are two theories for how people arrive at the solution for insight problems. The first is the progress monitoring theory. The person will analyze the distance from their current state to the goal state. Once a person realizes that they cannot solve the problem while on their current path, they will seek alternative solutions. In insight problems this usually occurs late in the puzzle. The second way that people attempt to solve these puzzles is the representational change theory. The problem solver initially has a low probability for success because they use inappropriate knowledge as they set unnecessary constraints on the problem. Once the person relaxes his or her constraints, they can bring previously unavailable knowledge into working memory to solve the problem. The person also utilizes chunk decomposition, where he or she will separate meaningful chunks into their component pieces. Both constraint relaxation and chunk decomposition allow for a change in representation, that is, a change in the distribution of activation across working memory, at which point they may exclaim, "Aha!" Currently both theories have support, with the progress monitoring theory being more suited to multiple step problems, and the representational change theory more suited to single step problems.The Eureka effect on memory occurs only when there is an initial confusion. When subjects were presented with a clue word before the confusing sentence was presented, there was no effect on recall. If the clue was provided after the sentence was presented, an increase in recall occurred. Research: Memory It had been determined that recall is greater for items that were generated by the subject versus if the subject was presented with the stimuli. There seems to be a memory advantage for instances where people are able to produce an answer themselves, recall was higher when Aha! reactions occurred. They tested sentences that were initially hard to understand, but when presented with a cued word, the comprehension became more apparent. Other evidence was found indicating that effort in processing visual stimuli was recalled more frequently than the stimuli that were simply presented. This study was done using connect-the-dots or verbal instruction to produce either a nonsense or real image. It is believed that effort made to comprehend something when encoding induces activation of alternative cues that later participate in recall. Research: Cerebral lateralization Functional magnetic resonance imaging and electroencephalogram studies have found that problem solving requiring insight involves increased activity in the right cerebral hemisphere as compared with problem solving not requiring insight. In particular, increased activity was found in the right hemisphere anterior superior temporal gyrus. Research: Sleep Some unconscious processing may take place while a person is asleep, and there are several cases of scientific discoveries coming to people in their dreams. Friedrich August Kekulé von Stradonitz claimed that the ring structure of benzene came to him in a dream where a snake was eating its own tail. Studies have shown increased performance at insight problems if the subjects slept during a break between receiving the problem and solving it. Sleep may function to restructure problems, and allow new insights to be reached. Henri Poincaré stated that he valued sleep as a time for "unconscious thought" that helped him break through problems. Research: Other theories Professor Stellan Ohlsson believes that at the beginning of the problem-solving process, some salient features of the problem are incorporated into a mental representation of the problem. In the first step of solving the problem, it is considered in the light of previous experience. Eventually, an impasse is reached, where all approaches to the problem have failed, and the person becomes frustrated. Ohlsson believes that this impasse drives unconscious processes which change the mental representation of a problem, and cause novel solutions to occur. Research: General procedure for conducting ERP and EEG studies When studying insight, or the Aha! effect, ERP or EEG general methods are used. Initially a baseline measurement is taken, which generally asks the subject to simply remember an answer to a question. Following this, subjects are asked to focus on the screen while a logogriph is shown, and then they are given time with a blank screen to get the answer, once they do they are required to press a key. After which the answer appears on the screen. The subjects are then asked to press one key to indicate that they thought of the correct answer and another to indicate if they got the answer wrong, finally, not to press a key at all if they were unsure or did not know the answer. Research: Evidence in EEG studies Resting-state neural activity has a standing influence on cognitive strategies used when solving problems, particularly in the case of deriving solutions by methodical search or by sudden insight. The two cognitive strategies used involve both search and analysis of current state of a problem, to the goal state of that problem, while insight problems are a sudden awareness of the solution to a problem.Subjects studied were first recorded on the base-line resting state of thinking. After being tested using the method described in the General Procedure for Conducting ERP and EEG Studies, the ratio of insight versus non-insight solution were made to determine whether an individual is classified as a high insight (HI) or a low insight (LI) individual. Discriminating between HI and LI individuals were important as both groups use different cognitive strategies to solve anagram problems used in this study. Right hemisphere activation is believed to be involved in Aha! effects, so it comes as no surprise that HI individuals would show greater activation in the right hemisphere than the left hemisphere when compared to the LI individuals. Evidence was found to support this idea, there was greater activation in HI subjects at the right dorsal-frontal (low-alpha band), right inferior-frontal (beta and gamma bands) and the right parietal (gamma band) areas. As for LI subjects, left inferior-frontal and left anterior-temporal areas were active (low-alpha band). Research: There were also differences in attention between individuals of HI and LI. It has been suggested that individuals who are highly creative exhibit diffuse attention, thus allowing them a greater range of environmental stimuli. It was found that individuals who displayed HI would have less resting state occipital alpha-band activity, meaning there would be less inhibition of the visual system. Individuals that were less creative were found to focus their attention, thus causing them to sample less of their environment. Although, LI individuals were shown to have more occipital beta activity, consistent with heightened focused attention. Research: Evidence in ERP studies Source localization is hard in ERP studies, and it may be difficult to distinguish signals of insight from signals of the existing cognitive skills it builds on or the unwarranted mental fixation it breaks, but the following conclusions have been offered. Research: One study found that "Aha" answers produced more negative ERP results, N380 in the ACC, than the "No-Aha" answers, 250–500 ms, after an answer was produced. The authors suspected that this N380 in the ACC is a sign of breaking the mental set, and reflects the Aha! effect. Another study was done showed that an Aha! effect elicited an N320 in the central-posterior region. A third study, by Qiu and Zhang (2008), found that there was a N350 in the posterior cingulate cortex for successful guessing, not in the anterior cingulate cortex. The posterior cingulate cortex seems to play a more non-executive function in monitoring and inhibiting the mind set and cognitive function.Another significant finding of this study was a late positive component (LPC) in successful guessing and then recognition of the answer at 600 and 700 ms, post-stimulus, in the parahippocampal gyrus (BA34). The data suggests that the parahippocampus is involved in searching for a correct answer by manipulating it in working memory, and integrating relationships. The parahippocampal gyrus may reflect the formation of novel associations while solving insight problems. Research: A fourth ERP study is fairly similar, but this study claims to have anterior cingulate cortex activation at N380, which may be responsible for the mediation of breaking the mental set. Other areas of interest were prefrontal cortex (PFC), the posterior parietal cortex, and the medial temporal lobe. If subjects failed to solve the riddle, and then were shown the correct answer, they displayed the feeling of insight, which was reflected on the electroencephalogram recordings. Research: Evidence in fMRI studies A study with the goal of recording the activity that occurs in the brain during an Aha! moment using fMRIs was conducted in 2003 by Jing Luo and Kazuhisa Niki. Participants in this study were presented with a series of Japanese riddles, and asked to rate their impressions toward each question using the following scale: (1) I can understand this question very well and know the answer; (2) I can understand this question very well and feel it is interesting, but I do not know the answer; or (3) I cannot understand this question and do not know the answer. Research: This scale allowed the researchers to only look at participants who would experience an Aha! moment upon viewing the answer to the riddle. In previous studies on insight, researchers have found that participants reported feelings of insight when they viewed the answer to an unsolved riddle or problem. Luo and Niki had the goal of recording these feelings of insight in their participants using fMRIs. This method allowed the researchers to directly observe the activity that was occurring in the participant's brains during an Aha! moment. Research: An example of a Japanese riddle used in the study: The thing that can move heavy logs, but cannot move a small nail → A river.Participants were given 3 minutes to respond to each riddle, before the answer to the riddle was revealed. If the participant experienced an Aha! moment upon viewing the correct answer, any brain activity would be recorded on the fMRI. Research: The fMRI results for this study showed that when participants were given the answer to an unsolved riddle, the activity in their right hippocampus increased significantly during these Aha! moments. This increased activity in the right hippocampus may be attributed to the formation of new associations between old nodes. These new associations will in turn strengthen memory for the riddles and their solutions. Research: Although various studies using EEGs, ERPs, and fMRI's report activation in a variety of areas in the brain during Aha! moments, this activity occurs predominantly in the right hemisphere. More details on the neural basis of insight see a recent review named "New advances in the neural correlates of insight: A decade in review of the insightful brain" Insight problems and problems with insight: Insight problems The Nine Dot Problem The Nine Dot Problem is a classic spatial problem used by psychologists to study insight. Insight problems and problems with insight: The problem consists of a 3 × 3 square created by 9 black dots. The task is to connect all 9 dots using exactly 4 straight lines, without retracing or removing one's pen from the paper. Kershaw & Ohlsson report that in a laboratory setting with a time limit of 2 or 3 minutes, the expected solution rate is 0%. Insight problems and problems with insight: The difficulty with the Nine Dot Problem is that it requires respondents to look beyond the conventional figure-ground relationships that create subtle, illusory spatial constraints and (literally) "think outside of the box". Breaking the spatial constraints shows a shift in attention in working memory and utilizing new knowledge factors to solve the puzzle. Verbal riddles Verbal riddles are becoming popular problems in insight research. Insight problems and problems with insight: Example: "A man was washing windows on a high-rise building when he fell from the 40-foot ladder to the concrete path below. Amazingly, he was unhurt. Why? [Answer] He slipped from the bottom rung!" Matchstick arithmetic A subset of matchstick puzzles, matchstick arithmetic, which was developed and used by G. Knoblich, involves matchsticks that are arranged to show a simple but incorrect math equation in Roman numerals. The task is to correct the equation by moving only one matchstick. Insight problems and problems with insight: Anagrams Anagrams involve manipulating the order of a given set of letters in order to create one or many words. The original set of letters may be a word itself, or simply a jumble. Example: Santa can be transformed to spell Satan. Rebus puzzles Rebus puzzles, also called "wordies", involve verbal and visual cues that force the respondent to restructure and "read between the lines" (almost literally) to solve the puzzle. Some examples: Puzzle: you just me [Answer: just between you and me] Puzzle: PUNISHMENT [Answer: capital punishment] Puzzle: i i i OOOOO [Answer: circles under the eyes] Remote Associates Test (RAT) The Remote Associates Test (known as the RAT) was developed by Martha Mednick in 1962 to test creativity. However, it has recently been utilized in insight research. Insight problems and problems with insight: The test consists of presenting participants with a set of words, such as lick, mine, and shaker. The task is to identify the word that connects these three seemingly unrelated ones. In this example, the answer is salt. The link between words is associative, and does not follow rules of logic, concept formation or problem solving, and thus requires the respondent to work outside of these common heuristical constraints. Insight problems and problems with insight: Performance on the RAT is known to correlate with performance on other standard insight problems. Insight problems and problems with insight: The Eight Coin Problem In this problem a set of 8 coins is arranged on a table in a certain configuration, and the subject is told to move 2 coins so that all coins touch exactly three others. The difficulty in this problem comes from thinking of the problem in a purely 2-dimensional way, when a 3-dimensional approach is the only way to solve the problem. Insight problems and problems with insight: Problems with insight Insight research is problematic because of the ambiguity and lack of agreement among psychologists of its definition. This could largely be explained by the phenomenological nature of insight, and the difficulty in catalyzing its occurrence, as well as the ways in which it is experimentally "triggered". The pool of insight problems currently employed by psychologists is small and tepid, and due to its heterogeneity and often high difficulty level, is not conducive of validity or reliability. One of the biggest issues surrounding insight problems is that for most participants, they are simply too difficult. For many problems, this difficulty revolves around the requisite restructuring or re-conceptualization of the problem or possible solutions, for example, drawing lines beyond the square composed of dots in the Nine-Dot Problem. Insight problems and problems with insight: Furthermore, there are issues related to the taxonomy of insight problems. Puzzles and problems that are utilized in experiments to elicit insight may be classified in two ways. "Pure" insight problems are those that necessitate the use of insight, whereas "hybrid" insight problems are those that can be solved by other methods, such as the trial and error. As Weisberg (1996) points out, the existence of hybrid problems in insight research poses a significant threat to any evidence gleaned from studies that employ them. While the phenomenological experience of insight can help to differentiate insight-solving from non-insight solving (by asking the respondent to describe how they solved the problem, for example), the risk that non-insight solving has been mistaken for insight solving still exists. Likewise, issues surrounding the validity of insight evidence is also threatened by the characteristically small sample sizes. Experimenters may recruit an initially adequate sample size, but because of the level of difficulty inherent to insight problems, only a small fraction of any sample will successfully solve the puzzle or task given to them; placing serious limits on usable data. In the case of studies using hybrid problems, the final sample is at even greater risk of being very small by way of having to exclude whatever percentage of respondents solved their given puzzle without utilizing insight. The Aha! effect and scientific discovery: There are several examples of scientific discoveries being made after a sudden flash of insight. One of the key insights in developing his special theory of relativity came to Albert Einstein while talking to his friend Michele Besso: I started the conversation with him in the following way: "Recently I have been working on a difficult problem. Today I come here to battle against that problem with you." We discussed every aspect of this problem. Then suddenly I understood where the key to this problem lay. Next day I came back to him again and said to him, without even saying hello, "Thank you. I've completely solved the problem." However, Einstein has said that the whole idea of special relativity did not come to him as a sudden, single eureka moment, and that he was "led to it by steps arising from the individual laws derived from experience". Similarly, Carl Friedrich Gauss said after a eureka moment: "I have the result, only I do not yet know how to get to it."Sir Alec Jeffreys had a eureka moment in his lab in Leicester after looking at the X-ray film image of a DNA experiment at 9:05 am on Monday 10 September 1984, which unexpectedly showed both similarities and differences between the DNA of different members of his technician's family. Within about half an hour, he realized the scope of DNA profiling, which uses variations in the genetic code to identify individuals. The method has become important in forensic science to assist detective work, and in resolving paternity and immigration disputes. It can also be applied to non-human species, such as in wildlife population genetics studies. Before his methods were commercialised in 1987, Jeffreys' laboratory was the only centre carrying out DNA fingerprinting in the world.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Steroid acne** Steroid acne: Steroid acne is an adverse reaction to corticosteroids, and presents as small, firm follicular papules on the forehead, cheeks, and chest.: 137  Steroid acne presents with monomorphous pink paupules, as well as comedones, which may be indistinguishable from those of acne vulgaris. Steroid acne is commonly associated with endogenous or exogenous sources of androgen, drug therapy, or diabetes and is less commonly associated with HIV infection or Hodgkin's disease.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Fluid warmer** Fluid warmer: A fluid warmer is a medical device used in healthcare facilities for warming fluids, crystalloid, colloid, or blood products, before being administered (intravenously or by other parenteral routes) to body temperature levels to prevent hypothermia in physically traumatized or surgical patients. Infusion fluid warmers are FDA-regulated medical devices, product code LGZ. They are unclassified devices with special considerations and require 510(k) clearance to be legally marketed in the United States. There are two primary categories of fluid warmers- those that warm fluids before use, typically warming cabinets, and those that actively warm fluids while being administered, in-line warming.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Bilinear interpolation** Bilinear interpolation: In mathematics, bilinear interpolation is a method for interpolating functions of two variables (e.g., x and y) using repeated linear interpolation. It is usually applied to functions sampled on a 2D rectilinear grid, though it can be generalized to functions defined on the vertices of (a mesh of) arbitrary convex quadrilaterals. Bilinear interpolation is performed using linear interpolation first in one direction, and then again in another direction. Although each step is linear in the sampled values and in the position, the interpolation as a whole is not linear but rather quadratic in the sample location. Bilinear interpolation is one of the basic resampling techniques in computer vision and image processing, where it is also called bilinear filtering or bilinear texture mapping. Computation: Suppose that we want to find the value of the unknown function f at the point (x, y). It is assumed that we know the value of f at the four points Q11 = (x1, y1), Q12 = (x1, y2), Q21 = (x2, y1), and Q22 = (x2, y2). Repeated linear interpolation We first do linear interpolation in the x-direction. This yields 11 21 12 22 ). We proceed by interpolating in the y-direction to obtain the desired estimate: 11 21 12 22 11 21 12 22 11 12 21 22 )][y2−yy−y1]. Note that we will arrive at the same result if the interpolation is done first along the y direction and then along the x direction. Polynomial fit An alternative way is to write the solution to the interpolation problem as a multilinear polynomial 00 10 01 11 xy, where the coefficients are found by solving the linear system 00 10 01 11 11 12 21 22 )], yielding the result 00 10 01 11 11 12 21 22 )]. Computation: Weighted mean The solution can also be written as a weighted mean of the f(Q): 11 11 12 12 21 21 22 22 ), where the weights sum to 1 and satisfy the transposed linear system 11 12 21 22 ]=[1xyxy], yielding the result 11 21 12 22 ]=1(x2−x1)(y2−y1)[x2y2−y2−x21−x2y1y1x2−1−x1y2y2x1−1x1y1−y1−x11][1xyxy], which simplifies to 11 12 21 22 =(x−x1)(y−y1)/((x2−x1)(y2−y1)), in agreement with the result obtained by repeated linear interpolation. The set of weights can also be interpreted as a set of generalized barycentric coordinates for a rectangle. Computation: Alternative matrix form Combining the above, we have 11 12 21 22 )][x2y2−y2−x21−x2y1y1x2−1−x1y2y2x1−1x1y1−y1−x11][1xyxy]. On the unit square If we choose a coordinate system in which the four points where f is known are (0, 0), (0, 1), (1, 0), and (1, 1), then the interpolation formula simplifies to f(x,y)≈f(0,0)(1−x)(1−y)+f(0,1)(1−x)y+f(1,0)x(1−y)+f(1,1)xy, or equivalently, in matrix operations: f(x,y)≈[1−xx][f(0,0)f(0,1)f(1,0)f(1,1)][1−yy]. Here we also recognize the weights: 11 12 21 22 =xy. Alternatively, the interpolant on the unit square can be written as 00 10 01 11 xy, where 00 10 01 11 =f(1,1)−f(1,0)−f(0,1)+f(0,0). In both cases, the number of constants (four) correspond to the number of data points where f is given. Properties: As the name suggests, the bilinear interpolant is not linear; but it is linear (i.e. affine) along lines parallel to either the x or the y direction, equivalently if x or y is held constant. Along any other straight line, the interpolant is quadratic. Even though the interpolation is not linear in the position (x and y), at a fixed point it is linear in the interpolation values, as can be seen in the (matrix) equations above. Properties: The result of bilinear interpolation is independent of which axis is interpolated first and which second. If we had first performed the linear interpolation in the y direction and then in the x direction, the resulting approximation would be the same. The interpolant is a bilinear polynomial, which is also a harmonic function satisfying Laplace's equation. Its graph is a bilinear Bézier surface patch. Inverse and generalization: In general, the interpolant will assume any value (in the convex hull of the vertex values) at an infinite number of points (forming branches of hyperbolas), so the interpolation is not invertible. Inverse and generalization: However, when bilinear interpolation is applied to two functions simultaneously, such as when interpolating a vector field, then the interpolation is invertible (under certain conditions). In particular, this inverse can be used to find the "unit square coordinates" of a point inside any convex quadrilateral (by considering the coordinates of the quadrilateral as a vector field which is bilinearly interpolated on the unit square). Using this procedure bilinear interpolation can be extended to any convex quadrilateral, though the computation is significantly more complicated if it is not a parallelogram. The resulting map between quadrilaterals is known as a bilinear transformation, bilinear warp or bilinear distortion. Inverse and generalization: Alternatively, a projective mapping between a quadrilateral and the unit square may be used, but the resulting interpolant will not be bilinear. In the special case when the quadrilateral is a parallelogram, a linear mapping to the unit square exists and the generalization follows easily. The obvious extension of bilinear interpolation to three dimensions is called trilinear interpolation. Application in image processing: In computer vision and image processing, bilinear interpolation is used to resample images and textures. An algorithm is used to map a screen pixel location to a corresponding point on the texture map. A weighted average of the attributes (color, transparency, etc.) of the four surrounding texels is computed and applied to the screen pixel. This process is repeated for each pixel forming the object being textured.When an image needs to be scaled up, each pixel of the original image needs to be moved in a certain direction based on the scale constant. However, when scaling up an image by a non-integral scale factor, there are pixels (i.e., holes) that are not assigned appropriate pixel values. In this case, those holes should be assigned appropriate RGB or grayscale values so that the output image does not have non-valued pixels. Application in image processing: Bilinear interpolation can be used where perfect image transformation with pixel matching is impossible, so that one can calculate and assign appropriate intensity values to pixels. Unlike other interpolation techniques such as nearest-neighbor interpolation and bicubic interpolation, bilinear interpolation uses values of only the 4 nearest pixels, located in diagonal directions from a given pixel, in order to find the appropriate color intensity values of that pixel. Application in image processing: Bilinear interpolation considers the closest 2 × 2 neighborhood of known pixel values surrounding the unknown pixel's computed location. It then takes a weighted average of these 4 pixels to arrive at its final, interpolated value. Application in image processing: Example As seen in the example on the right, the intensity value at the pixel computed to be at row 20.2, column 14.5 can be calculated by first linearly interpolating between the values at column 14 and 15 on each rows 20 and 21, giving 20 14.5 15 14.5 15 14 91 14.5 14 15 14 210 150.5 21 14.5 15 14.5 15 14 162 14.5 14 15 14 95 128.5 , and then interpolating linearly between these values, giving 20.2 14.5 21 20.2 21 20 150.5 20.2 20 21 20 128.5 146.1. Application in image processing: This algorithm reduces some of the visual distortion caused by resizing an image to a non-integral zoom factor, as opposed to nearest-neighbor interpolation, which will make some pixels appear larger than others in the resized image.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**Simulation Interoperability Standards Organization** Simulation Interoperability Standards Organization: The Simulation Interoperability Standards Organization (SISO) is an organization dedicated to the promotion of modeling and simulation interoperability and reuse for the benefit of diverse modeling and simulation communities, including developers, procurers, and users, worldwide. History: The Simulation Interoperability Standards Organization (SISO) originated with a small conference held April 26 and 27, 1989, called, "Interactive Networked Simulation for Training". The original conference attracted approximately 60 people. The group was concerned that there was activity occurring in networked simulation, but that it was occurring in isolation. The group believed that if there were a means to exchange information between companies and groups that the technology would advance more rapidly. History: The group also believed that once the technology begins to stabilize then there would also be a need for standardization. The technology and the consensus of the community would be captured in the standards as networking or simulation technology matured. The pre-history of SISO starts with SIMNET, a DARPA program from 1983 through 1991 that demonstrated the feasibility of networking substantial numbers of (relatively) low-cost simulators on a "virtual battlefield." Based on the success of this program, the US Army initiated a large-scale program called Combined Arms Tactical Training. In order to ensure that multiple teams of contractors would be able to bid on various components of this program, the Army Program Manager for Training Devices (PM TRADE), soon to be renamed as the Army Simulation Training and Instrumentation Command (STRICOM - now PEO STRI), in conjunction with DARPA and the newly established Defense Modeling and Simulation Office (DMSO now Modeling and Simulation Coordination Office (MSCO)), initiated a series of workshops at which user agencies and interested contractors could work together to develop standards based on the SIMNET protocols. History: The "First Conference on Standards for the Interoperability of Defense Simulations" was held on 22–23 August 1989 in Orlando, Florida. DIS Workshops were held semi-annually from 1989 through 1996. The first Simulation Interoperability Workshop (SIW) held under the SISO banner was the 1997 Spring SIW in Orlando. SIWs have continued semi-annually since 1997. In 2001, SISO also began holding annual Euro-SIWs at various locations in Europe. In 2003, the IEEE Computer Society Standards Activities Board (SAB) granted the SISO Standards Activities Committee (SAC) status as a recognized IEEE Sponsor Committee. SISO is also recognized as a Standards Development Organization (SDO) by NATO. In addition, SISO is a Category C Liaison Organization with ISO/IEC JTC 1 for the development of standards for the representation and interchange of data regarding Synthetic Environment Data Representation and Interchange Specification (SEDRIS).SISO was an original sponsor of SimSummit. Contributions: SISO originated, maintained, or contributed standards: IEEE 1278 Distributed Interactive Simulation (DIS) IEEE 1516 High Level Architecture (HLA) for Modeling and Simulation IEEE 1730 DSEEP Distributed Simulation Engineering and Execution Process ISO/IEC 18023-1, SEDRIS—Part 1: Functional specification ISO/IEC 18023-2, SEDRIS—Part 2: Abstract transmittal format ISO/IEC 18023-3, SEDRIS—Part 3: Transmittal format binary encoding ISO/IEC 18024-4, SEDRIS language bindings—Part 4: C ISO/IEC 18025, Environmental Data Coding Specification (EDCS) ISO/IEC 18041-4, EDCS language bindings—Part 4: C ISO/IEC 18026, Spatial Reference Model (SRM) ISO/IEC 18042-4, SRM language bindings—Part 4: C SISO-STD-001-2015: Guidance, Rationale, & Interoperability Modalities for the RPR FOM (GRIM 2.0) SISO-STD-001.1-2015: Real-time Platform Reference Federation Object Model (RPR FOM 2.0) SISO-STD-002-2006: Standard for: Link16 Simulations SISO-STD-003-2006; Base Object Model (BOM) Template Specification SISO-STD-003.1-2006; Guide for BOM Use and Implementation SISO-STD-004-2004: Dynamic Link Compatible HLA API Standard for the HLA Interface Specification SISO-STD-004.1-2004: Dynamic Link Compatible HLA API Standard for the HLA Interface Specification SISO-STD-005-200X: Link 11 A/B SISO-STD-006-200X: Commercial Off-the-Shelf (COTS) Simulation Package Interoperability (CSPI) SISO-STD-007-2008: Military Scenario Definition Language (MSDL) SISO-STD-008-200X: Coalition-Battle Management Language (C-BML)
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded
**PrintMaster** PrintMaster: PrintMaster is a greeting card and banner creation program for Commodore 64, Amiga, Apple II and IBM PC computers. PrintMaster sold more than two million copies. History: In 1986, the first version of PrintMaster was the target of a lawsuit by Broderbund, who alleged that PrintMaster was a direct copy of their popular The Print Shop program. The court found in favor of Broderbund, locating specific instances of copying. The program was re-worked to provide the same functionality, but through a different look and feel. History: Since the early 1990s, the name has been used for a basic desktop publishing software package, under the Broderbund brand. It was unique in that it provided libraries of clip-art and templates through a simple interface to build signs, greeting cards, posters and banners with household dot-matrix printers. Over the years, it was updated to accommodate changing file formats and printer technologies, including CD and DVD labels and inserts and photobook pages. PrintMaster is available in Platinum and Gold variants. History: PrintMaster 2.0 is the first consumer desktop publishing solution at retail to offer Macintosh and Windows compatibility and integrated professional printing. In September 2010, PrintMaster 2011 was released. Versions include Platinum, Gold, and Express for digital download. PrintMaster project types include banners, calendars, crafts, greeting cards, invitations, labels, signs, and scrapbook pages.
kaggle.com/datasets/mbanaei/all-paraphs-parsed-expanded